From 5882e21b3bff0afe2152eb3971d674bdb91e45a2 Mon Sep 17 00:00:00 2001 From: Joas Schilling Date: Wed, 25 May 2016 16:04:15 +0200 Subject: Update DAV unit tests to PSR-4 --- apps/dav/tests/unit/AppInfo/ApplicationTest.php | 62 ++ apps/dav/tests/unit/CalDAV/CalDavBackendTest.php | 505 +++++++++++ apps/dav/tests/unit/CalDAV/CalendarTest.php | 191 ++++ .../tests/unit/CalDAV/Schedule/IMipPluginTest.php | 91 ++ .../dav/tests/unit/CardDAV/AddressBookImplTest.php | 288 ++++++ apps/dav/tests/unit/CardDAV/AddressBookTest.php | 139 +++ .../dav/tests/unit/CardDAV/BirthdayServiceTest.php | 216 +++++ apps/dav/tests/unit/CardDAV/CardDavBackendTest.php | 632 +++++++++++++ .../dav/tests/unit/CardDAV/ContactsManagerTest.php | 43 + apps/dav/tests/unit/CardDAV/ConverterTest.php | 137 +++ apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php | 81 ++ apps/dav/tests/unit/CardDAV/SyncServiceTest.php | 145 +++ apps/dav/tests/unit/Comments/CommentsNodeTest.php | 459 ++++++++++ .../dav/tests/unit/Comments/CommentsPluginTest.php | 742 ++++++++++++++++ .../tests/unit/Comments/EntityCollectionTest.php | 118 +++ .../unit/Comments/EntityTypeCollectionTest.php | 92 ++ .../dav/tests/unit/Comments/RootCollectionTest.php | 170 ++++ apps/dav/tests/unit/Connector/PublicAuthTest.php | 177 ++++ apps/dav/tests/unit/Connector/Sabre/AuthTest.php | 611 +++++++++++++ .../Sabre/BlockLegacyClientPluginTest.php | 130 +++ .../Sabre/CommentsPropertiesPluginTest.php | 149 ++++ .../Connector/Sabre/CopyEtagHeaderPluginTest.php | 62 ++ .../Sabre/CustomPropertiesBackendTest.php | 313 +++++++ .../tests/unit/Connector/Sabre/DirectoryTest.php | 267 ++++++ .../Connector/Sabre/DummyGetResponsePluginTest.php | 70 ++ .../Connector/Sabre/Exception/ForbiddenTest.php | 57 ++ .../Connector/Sabre/Exception/InvalidPathTest.php | 58 ++ .../Connector/Sabre/ExceptionLoggerPluginTest.php | 83 ++ .../unit/Connector/Sabre/FakeLockerPluginTest.php | 174 ++++ apps/dav/tests/unit/Connector/Sabre/FileTest.php | 987 +++++++++++++++++++++ .../tests/unit/Connector/Sabre/FilesPluginTest.php | 469 ++++++++++ .../unit/Connector/Sabre/FilesReportPluginTest.php | 611 +++++++++++++ .../unit/Connector/Sabre/MaintenancePluginTest.php | 73 ++ apps/dav/tests/unit/Connector/Sabre/NodeTest.php | 149 ++++ .../tests/unit/Connector/Sabre/ObjectTreeTest.php | 355 ++++++++ .../tests/unit/Connector/Sabre/PrincipalTest.php | 273 ++++++ .../tests/unit/Connector/Sabre/QuotaPluginTest.php | 223 +++++ .../unit/Connector/Sabre/RequestTest/Auth.php | 117 +++ .../Connector/Sabre/RequestTest/DownloadTest.php | 73 ++ .../Sabre/RequestTest/EncryptionUploadTest.php | 46 + .../Sabre/RequestTest/ExceptionPlugin.php | 46 + .../Sabre/RequestTest/PartFileInRootUploadTest.php | 56 ++ .../Connector/Sabre/RequestTest/RequestTest.php | 146 +++ .../unit/Connector/Sabre/RequestTest/Sapi.php | 75 ++ .../Connector/Sabre/RequestTest/UploadTest.php | 211 +++++ .../unit/Connector/Sabre/SharesPluginTest.php | 259 ++++++ .../tests/unit/Connector/Sabre/TagsPluginTest.php | 417 +++++++++ .../tests/unit/DAV/BrowserErrorPagePluginTest.php | 58 ++ apps/dav/tests/unit/DAV/GroupPrincipalTest.php | 165 ++++ apps/dav/tests/unit/DAV/HookManagerTest.php | 152 ++++ apps/dav/tests/unit/DAV/Sharing/PluginTest.php | 83 ++ .../tests/unit/DAV/SystemPrincipalBackendTest.php | 131 +++ apps/dav/tests/unit/ServerTest.php | 43 + .../unit/SystemTag/SystemTagMappingNodeTest.php | 160 ++++ .../dav/tests/unit/SystemTag/SystemTagNodeTest.php | 312 +++++++ .../tests/unit/SystemTag/SystemTagPluginTest.php | 734 +++++++++++++++ .../SystemTag/SystemTagsByIdCollectionTest.php | 233 +++++ .../SystemTagsObjectMappingCollectionTest.php | 348 ++++++++ .../SystemTagsObjectTypeCollectionTest.php | 160 ++++ apps/dav/tests/unit/Upload/AssemblyStreamTest.php | 48 + apps/dav/tests/unit/Upload/FutureFileTest.php | 91 ++ apps/dav/tests/unit/appinfo/applicationtest.php | 62 -- apps/dav/tests/unit/caldav/caldavbackendtest.php | 504 ----------- apps/dav/tests/unit/caldav/calendartest.php | 191 ---- .../tests/unit/caldav/schedule/imipplugintest.php | 91 -- .../dav/tests/unit/carddav/addressbookimpltest.php | 288 ------ apps/dav/tests/unit/carddav/addressbooktest.php | 139 --- .../dav/tests/unit/carddav/birthdayservicetest.php | 216 ----- apps/dav/tests/unit/carddav/carddavbackendtest.php | 631 ------------- .../dav/tests/unit/carddav/contactsmanagertest.php | 43 - apps/dav/tests/unit/carddav/convertertest.php | 137 --- apps/dav/tests/unit/carddav/sharing/plugintest.php | 81 -- apps/dav/tests/unit/carddav/syncservicetest.php | 142 --- apps/dav/tests/unit/comments/commentnode.php | 459 ---------- apps/dav/tests/unit/comments/commentsplugin.php | 742 ---------------- apps/dav/tests/unit/comments/entitycollection.php | 118 --- .../tests/unit/comments/entitytypecollection.php | 92 -- apps/dav/tests/unit/comments/rootcollection.php | 170 ---- apps/dav/tests/unit/connector/publicauth.php | 177 ---- .../sabre/BlockLegacyClientPluginTest.php | 130 --- .../connector/sabre/DummyGetResponsePluginTest.php | 70 -- .../unit/connector/sabre/FakeLockerPluginTest.php | 174 ---- .../unit/connector/sabre/MaintenancePluginTest.php | 73 -- apps/dav/tests/unit/connector/sabre/auth.php | 611 ------------- .../connector/sabre/commentpropertiesplugin.php | 149 ---- .../connector/sabre/copyetagheaderplugintest.php | 62 -- .../connector/sabre/custompropertiesbackend.php | 313 ------- apps/dav/tests/unit/connector/sabre/directory.php | 267 ------ .../connector/sabre/exception/forbiddentest.php | 57 -- .../connector/sabre/exception/invalidpathtest.php | 58 -- .../unit/connector/sabre/exceptionloggerplugin.php | 83 -- apps/dav/tests/unit/connector/sabre/file.php | 987 --------------------- .../dav/tests/unit/connector/sabre/filesplugin.php | 469 ---------- .../unit/connector/sabre/filesreportplugin.php | 611 ------------- apps/dav/tests/unit/connector/sabre/node.php | 149 ---- apps/dav/tests/unit/connector/sabre/objecttree.php | 355 -------- apps/dav/tests/unit/connector/sabre/principal.php | 273 ------ .../dav/tests/unit/connector/sabre/quotaplugin.php | 223 ----- .../unit/connector/sabre/requesttest/auth.php | 117 --- .../connector/sabre/requesttest/downloadtest.php | 73 -- .../sabre/requesttest/encryptionuploadtest.php | 46 - .../sabre/requesttest/exceptionplugin.php | 46 - .../sabre/requesttest/partfileinrootupload.php | 56 -- .../connector/sabre/requesttest/requesttest.php | 146 --- .../unit/connector/sabre/requesttest/sapi.php | 75 -- .../connector/sabre/requesttest/uploadtest.php | 211 ----- .../tests/unit/connector/sabre/sharesplugin.php | 259 ------ apps/dav/tests/unit/connector/sabre/tagsplugin.php | 417 --------- apps/dav/tests/unit/dav/HookManagerTest.php | 152 ---- .../tests/unit/dav/browsererrorpageplugintest.php | 57 -- apps/dav/tests/unit/dav/groupprincipaltest.php | 164 ---- apps/dav/tests/unit/dav/sharing/plugintest.php | 83 -- .../tests/unit/dav/systemprincipalbackendtest.php | 131 --- apps/dav/tests/unit/phpunit.xml | 2 +- apps/dav/tests/unit/servertest.php | 43 - .../tests/unit/systemtag/systemtagmappingnode.php | 160 ---- apps/dav/tests/unit/systemtag/systemtagnode.php | 312 ------- apps/dav/tests/unit/systemtag/systemtagplugin.php | 734 --------------- .../unit/systemtag/systemtagsbyidcollection.php | 233 ----- .../systemtagsobjectmappingcollection.php | 348 -------- .../systemtag/systemtagsobjecttypecollection.php | 160 ---- apps/dav/tests/unit/upload/assemblystreamtest.php | 47 - apps/dav/tests/unit/upload/futurefiletest.php | 89 -- 123 files changed, 13567 insertions(+), 13557 deletions(-) create mode 100644 apps/dav/tests/unit/AppInfo/ApplicationTest.php create mode 100644 apps/dav/tests/unit/CalDAV/CalDavBackendTest.php create mode 100644 apps/dav/tests/unit/CalDAV/CalendarTest.php create mode 100644 apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php create mode 100644 apps/dav/tests/unit/CardDAV/AddressBookImplTest.php create mode 100644 apps/dav/tests/unit/CardDAV/AddressBookTest.php create mode 100644 apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php create mode 100644 apps/dav/tests/unit/CardDAV/CardDavBackendTest.php create mode 100644 apps/dav/tests/unit/CardDAV/ContactsManagerTest.php create mode 100644 apps/dav/tests/unit/CardDAV/ConverterTest.php create mode 100644 apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php create mode 100644 apps/dav/tests/unit/CardDAV/SyncServiceTest.php create mode 100644 apps/dav/tests/unit/Comments/CommentsNodeTest.php create mode 100644 apps/dav/tests/unit/Comments/CommentsPluginTest.php create mode 100644 apps/dav/tests/unit/Comments/EntityCollectionTest.php create mode 100644 apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php create mode 100644 apps/dav/tests/unit/Comments/RootCollectionTest.php create mode 100644 apps/dav/tests/unit/Connector/PublicAuthTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/AuthTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/FileTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/NodeTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/RequestTest/DownloadTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/RequestTest/ExceptionPlugin.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php create mode 100644 apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php create mode 100644 apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php create mode 100644 apps/dav/tests/unit/DAV/GroupPrincipalTest.php create mode 100644 apps/dav/tests/unit/DAV/HookManagerTest.php create mode 100644 apps/dav/tests/unit/DAV/Sharing/PluginTest.php create mode 100644 apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php create mode 100644 apps/dav/tests/unit/ServerTest.php create mode 100644 apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php create mode 100644 apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php create mode 100644 apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php create mode 100644 apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php create mode 100644 apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php create mode 100644 apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php create mode 100644 apps/dav/tests/unit/Upload/AssemblyStreamTest.php create mode 100644 apps/dav/tests/unit/Upload/FutureFileTest.php delete mode 100644 apps/dav/tests/unit/appinfo/applicationtest.php delete mode 100644 apps/dav/tests/unit/caldav/caldavbackendtest.php delete mode 100644 apps/dav/tests/unit/caldav/calendartest.php delete mode 100644 apps/dav/tests/unit/caldav/schedule/imipplugintest.php delete mode 100644 apps/dav/tests/unit/carddav/addressbookimpltest.php delete mode 100644 apps/dav/tests/unit/carddav/addressbooktest.php delete mode 100644 apps/dav/tests/unit/carddav/birthdayservicetest.php delete mode 100644 apps/dav/tests/unit/carddav/carddavbackendtest.php delete mode 100644 apps/dav/tests/unit/carddav/contactsmanagertest.php delete mode 100644 apps/dav/tests/unit/carddav/convertertest.php delete mode 100644 apps/dav/tests/unit/carddav/sharing/plugintest.php delete mode 100644 apps/dav/tests/unit/carddav/syncservicetest.php delete mode 100644 apps/dav/tests/unit/comments/commentnode.php delete mode 100644 apps/dav/tests/unit/comments/commentsplugin.php delete mode 100644 apps/dav/tests/unit/comments/entitycollection.php delete mode 100644 apps/dav/tests/unit/comments/entitytypecollection.php delete mode 100644 apps/dav/tests/unit/comments/rootcollection.php delete mode 100644 apps/dav/tests/unit/connector/publicauth.php delete mode 100644 apps/dav/tests/unit/connector/sabre/BlockLegacyClientPluginTest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/DummyGetResponsePluginTest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/FakeLockerPluginTest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/MaintenancePluginTest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/auth.php delete mode 100644 apps/dav/tests/unit/connector/sabre/commentpropertiesplugin.php delete mode 100644 apps/dav/tests/unit/connector/sabre/copyetagheaderplugintest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/custompropertiesbackend.php delete mode 100644 apps/dav/tests/unit/connector/sabre/directory.php delete mode 100644 apps/dav/tests/unit/connector/sabre/exception/forbiddentest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/exception/invalidpathtest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/exceptionloggerplugin.php delete mode 100644 apps/dav/tests/unit/connector/sabre/file.php delete mode 100644 apps/dav/tests/unit/connector/sabre/filesplugin.php delete mode 100644 apps/dav/tests/unit/connector/sabre/filesreportplugin.php delete mode 100644 apps/dav/tests/unit/connector/sabre/node.php delete mode 100644 apps/dav/tests/unit/connector/sabre/objecttree.php delete mode 100644 apps/dav/tests/unit/connector/sabre/principal.php delete mode 100644 apps/dav/tests/unit/connector/sabre/quotaplugin.php delete mode 100644 apps/dav/tests/unit/connector/sabre/requesttest/auth.php delete mode 100644 apps/dav/tests/unit/connector/sabre/requesttest/downloadtest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/requesttest/encryptionuploadtest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/requesttest/exceptionplugin.php delete mode 100644 apps/dav/tests/unit/connector/sabre/requesttest/partfileinrootupload.php delete mode 100644 apps/dav/tests/unit/connector/sabre/requesttest/requesttest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/requesttest/sapi.php delete mode 100644 apps/dav/tests/unit/connector/sabre/requesttest/uploadtest.php delete mode 100644 apps/dav/tests/unit/connector/sabre/sharesplugin.php delete mode 100644 apps/dav/tests/unit/connector/sabre/tagsplugin.php delete mode 100644 apps/dav/tests/unit/dav/HookManagerTest.php delete mode 100644 apps/dav/tests/unit/dav/browsererrorpageplugintest.php delete mode 100644 apps/dav/tests/unit/dav/groupprincipaltest.php delete mode 100644 apps/dav/tests/unit/dav/sharing/plugintest.php delete mode 100644 apps/dav/tests/unit/dav/systemprincipalbackendtest.php delete mode 100644 apps/dav/tests/unit/servertest.php delete mode 100644 apps/dav/tests/unit/systemtag/systemtagmappingnode.php delete mode 100644 apps/dav/tests/unit/systemtag/systemtagnode.php delete mode 100644 apps/dav/tests/unit/systemtag/systemtagplugin.php delete mode 100644 apps/dav/tests/unit/systemtag/systemtagsbyidcollection.php delete mode 100644 apps/dav/tests/unit/systemtag/systemtagsobjectmappingcollection.php delete mode 100644 apps/dav/tests/unit/systemtag/systemtagsobjecttypecollection.php delete mode 100644 apps/dav/tests/unit/upload/assemblystreamtest.php delete mode 100644 apps/dav/tests/unit/upload/futurefiletest.php diff --git a/apps/dav/tests/unit/AppInfo/ApplicationTest.php b/apps/dav/tests/unit/AppInfo/ApplicationTest.php new file mode 100644 index 00000000000..6b55fcaf966 --- /dev/null +++ b/apps/dav/tests/unit/AppInfo/ApplicationTest.php @@ -0,0 +1,62 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\AppInfo; + +use OCA\DAV\AppInfo\Application; +use OCP\Contacts\IManager; +use Test\TestCase; + +/** + * Class ApplicationTest + * + * @group DB + * + * @package OCA\DAV\Tests\Unit\AppInfo + */ +class ApplicationTest extends TestCase { + public function test() { + $app = new Application(); + $c = $app->getContainer(); + + // assert service instances in the container are properly setup + $s = $c->query('ContactsManager'); + $this->assertInstanceOf('OCA\DAV\CardDAV\ContactsManager', $s); + $s = $c->query('CardDavBackend'); + $this->assertInstanceOf('OCA\DAV\CardDAV\CardDavBackend', $s); + } + + public function testContactsManagerSetup() { + $app = new Application(); + $c = $app->getContainer(); + $c->registerService('CardDavBackend', function($c) { + $service = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $service->method('getAddressBooksForUser')->willReturn([]); + return $service; + }); + + // assert setupContactsProvider() is proper + /** @var IManager | \PHPUnit_Framework_MockObject_MockObject $cm */ + $cm = $this->getMockBuilder('OCP\Contacts\IManager')->disableOriginalConstructor()->getMock(); + $app->setupContactsProvider($cm, 'xxx'); + $this->assertTrue(true); + } +} diff --git a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php new file mode 100644 index 00000000000..0252457e737 --- /dev/null +++ b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php @@ -0,0 +1,505 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CalDAV; + +use DateTime; +use DateTimeZone; +use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\CalDAV\Calendar; +use OCA\DAV\Connector\Sabre\Principal; +use OCP\IL10N; +use Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet; +use Sabre\DAV\PropPatch; +use Sabre\DAV\Xml\Property\Href; +use Sabre\DAVACL\IACL; +use Test\TestCase; + +/** + * Class CalDavBackendTest + * + * @group DB + * + * @package OCA\DAV\Tests\unit\CalDAV + */ +class CalDavBackendTest extends TestCase { + + /** @var CalDavBackend */ + private $backend; + + /** @var Principal | \PHPUnit_Framework_MockObject_MockObject */ + private $principal; + + const UNIT_TEST_USER = 'principals/users/caldav-unit-test'; + const UNIT_TEST_USER1 = 'principals/users/caldav-unit-test1'; + const UNIT_TEST_GROUP = 'principals/groups/caldav-unit-test-group'; + + public function setUp() { + parent::setUp(); + + $this->principal = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Principal') + ->disableOriginalConstructor() + ->setMethods(['getPrincipalByPath', 'getGroupMembership']) + ->getMock(); + $this->principal->expects($this->any())->method('getPrincipalByPath') + ->willReturn([ + 'uri' => 'principals/best-friend' + ]); + $this->principal->expects($this->any())->method('getGroupMembership') + ->withAnyParameters() + ->willReturn([self::UNIT_TEST_GROUP]); + + $db = \OC::$server->getDatabaseConnection(); + $this->backend = new CalDavBackend($db, $this->principal); + + $this->tearDown(); + } + + public function tearDown() { + parent::tearDown(); + + if (is_null($this->backend)) { + return; + } + $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); + foreach ($books as $book) { + $this->backend->deleteCalendar($book['id']); + } + $subscriptions = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); + foreach ($subscriptions as $subscription) { + $this->backend->deleteSubscription($subscription['id']); + } + } + + public function testCalendarOperations() { + + $calendarId = $this->createTestCalendar(); + + // update it's display name + $patch = new PropPatch([ + '{DAV:}displayname' => 'Unit test', + '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'Calendar used for unit testing' + ]); + $this->backend->updateCalendar($calendarId, $patch); + $patch->commit(); + $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + $this->assertEquals('Unit test', $books[0]['{DAV:}displayname']); + $this->assertEquals('Calendar used for unit testing', $books[0]['{urn:ietf:params:xml:ns:caldav}calendar-description']); + + // delete the address book + $this->backend->deleteCalendar($books[0]['id']); + $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); + $this->assertEquals(0, count($books)); + } + + public function providesSharingData() { + return [ + [true, true, true, false, [ + [ + 'href' => 'principal:' . self::UNIT_TEST_USER1, + 'readOnly' => false + ], + [ + 'href' => 'principal:' . self::UNIT_TEST_GROUP, + 'readOnly' => true + ] + ]], + [true, false, false, false, [ + [ + 'href' => 'principal:' . self::UNIT_TEST_USER1, + 'readOnly' => true + ], + ]], + + ]; + } + + /** + * @dataProvider providesSharingData + */ + public function testCalendarSharing($userCanRead, $userCanWrite, $groupCanRead, $groupCanWrite, $add) { + + /** @var IL10N | \PHPUnit_Framework_MockObject_MockObject $l10n */ + $l10n = $this->getMockBuilder('\OCP\IL10N') + ->disableOriginalConstructor()->getMock(); + $l10n + ->expects($this->any()) + ->method('t') + ->will($this->returnCallback(function ($text, $parameters = array()) { + return vsprintf($text, $parameters); + })); + + $calendarId = $this->createTestCalendar(); + $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + $calendar = new Calendar($this->backend, $books[0], $l10n); + $this->backend->updateShares($calendar, $add, []); + $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER1); + $this->assertEquals(1, count($books)); + $calendar = new Calendar($this->backend, $books[0], $l10n); + $acl = $calendar->getACL(); + $this->assertAcl(self::UNIT_TEST_USER, '{DAV:}read', $acl); + $this->assertAcl(self::UNIT_TEST_USER, '{DAV:}write', $acl); + $this->assertAccess($userCanRead, self::UNIT_TEST_USER1, '{DAV:}read', $acl); + $this->assertAccess($userCanWrite, self::UNIT_TEST_USER1, '{DAV:}write', $acl); + $this->assertAccess($groupCanRead, self::UNIT_TEST_GROUP, '{DAV:}read', $acl); + $this->assertAccess($groupCanWrite, self::UNIT_TEST_GROUP, '{DAV:}write', $acl); + $this->assertEquals(self::UNIT_TEST_USER, $calendar->getOwner()); + + // test acls on the child + $uri = $this->getUniqueID('calobj'); + $calData = <<<'EOD' +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:ownCloud Calendar +BEGIN:VEVENT +CREATED;VALUE=DATE-TIME:20130910T125139Z +UID:47d15e3ec8 +LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z +DTSTAMP;VALUE=DATE-TIME:20130910T125139Z +SUMMARY:Test Event +DTSTART;VALUE=DATE-TIME:20130912T130000Z +DTEND;VALUE=DATE-TIME:20130912T140000Z +CLASS:PUBLIC +END:VEVENT +END:VCALENDAR +EOD; + + $this->backend->createCalendarObject($calendarId, $uri, $calData); + + /** @var IACL $child */ + $child = $calendar->getChild($uri); + $acl = $child->getACL(); + $this->assertAcl(self::UNIT_TEST_USER, '{DAV:}read', $acl); + $this->assertAcl(self::UNIT_TEST_USER, '{DAV:}write', $acl); + $this->assertAccess($userCanRead, self::UNIT_TEST_USER1, '{DAV:}read', $acl); + $this->assertAccess($userCanWrite, self::UNIT_TEST_USER1, '{DAV:}write', $acl); + $this->assertAccess($groupCanRead, self::UNIT_TEST_GROUP, '{DAV:}read', $acl); + $this->assertAccess($groupCanWrite, self::UNIT_TEST_GROUP, '{DAV:}write', $acl); + + // delete the address book + $this->backend->deleteCalendar($books[0]['id']); + $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); + $this->assertEquals(0, count($books)); + } + + public function testCalendarObjectsOperations() { + + $calendarId = $this->createTestCalendar(); + + // create a card + $uri = $this->getUniqueID('calobj'); + $calData = <<<'EOD' +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:ownCloud Calendar +BEGIN:VEVENT +CREATED;VALUE=DATE-TIME:20130910T125139Z +UID:47d15e3ec8 +LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z +DTSTAMP;VALUE=DATE-TIME:20130910T125139Z +SUMMARY:Test Event +DTSTART;VALUE=DATE-TIME:20130912T130000Z +DTEND;VALUE=DATE-TIME:20130912T140000Z +CLASS:PUBLIC +END:VEVENT +END:VCALENDAR +EOD; + + $this->backend->createCalendarObject($calendarId, $uri, $calData); + + // get all the cards + $calendarObjects = $this->backend->getCalendarObjects($calendarId); + $this->assertEquals(1, count($calendarObjects)); + $this->assertEquals($calendarId, $calendarObjects[0]['calendarid']); + + // get the cards + $calendarObject = $this->backend->getCalendarObject($calendarId, $uri); + $this->assertNotNull($calendarObject); + $this->assertArrayHasKey('id', $calendarObject); + $this->assertArrayHasKey('uri', $calendarObject); + $this->assertArrayHasKey('lastmodified', $calendarObject); + $this->assertArrayHasKey('etag', $calendarObject); + $this->assertArrayHasKey('size', $calendarObject); + $this->assertEquals($calData, $calendarObject['calendardata']); + + // update the card + $calData = <<<'EOD' +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:ownCloud Calendar +BEGIN:VEVENT +CREATED;VALUE=DATE-TIME:20130910T125139Z +UID:47d15e3ec8 +LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z +DTSTAMP;VALUE=DATE-TIME:20130910T125139Z +SUMMARY:Test Event +DTSTART;VALUE=DATE-TIME:20130912T130000Z +DTEND;VALUE=DATE-TIME:20130912T140000Z +END:VEVENT +END:VCALENDAR +EOD; + $this->backend->updateCalendarObject($calendarId, $uri, $calData); + $calendarObject = $this->backend->getCalendarObject($calendarId, $uri); + $this->assertEquals($calData, $calendarObject['calendardata']); + + // delete the card + $this->backend->deleteCalendarObject($calendarId, $uri); + $calendarObjects = $this->backend->getCalendarObjects($calendarId); + $this->assertEquals(0, count($calendarObjects)); + } + + public function testMultiCalendarObjects() { + + $calendarId = $this->createTestCalendar(); + + // create an event + $calData = <<<'EOD' +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:ownCloud Calendar +BEGIN:VEVENT +CREATED;VALUE=DATE-TIME:20130910T125139Z +UID:47d15e3ec8 +LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z +DTSTAMP;VALUE=DATE-TIME:20130910T125139Z +SUMMARY:Test Event +DTSTART;VALUE=DATE-TIME:20130912T130000Z +DTEND;VALUE=DATE-TIME:20130912T140000Z +CLASS:PUBLIC +END:VEVENT +END:VCALENDAR +EOD; + $uri0 = $this->getUniqueID('card'); + $this->backend->createCalendarObject($calendarId, $uri0, $calData); + $uri1 = $this->getUniqueID('card'); + $this->backend->createCalendarObject($calendarId, $uri1, $calData); + $uri2 = $this->getUniqueID('card'); + $this->backend->createCalendarObject($calendarId, $uri2, $calData); + + // get all the cards + $calendarObjects = $this->backend->getCalendarObjects($calendarId); + $this->assertEquals(3, count($calendarObjects)); + + // get the cards + $calendarObjects = $this->backend->getMultipleCalendarObjects($calendarId, [$uri1, $uri2]); + $this->assertEquals(2, count($calendarObjects)); + foreach($calendarObjects as $card) { + $this->assertArrayHasKey('id', $card); + $this->assertArrayHasKey('uri', $card); + $this->assertArrayHasKey('lastmodified', $card); + $this->assertArrayHasKey('etag', $card); + $this->assertArrayHasKey('size', $card); + $this->assertEquals($calData, $card['calendardata']); + } + + // delete the card + $this->backend->deleteCalendarObject($calendarId, $uri0); + $this->backend->deleteCalendarObject($calendarId, $uri1); + $this->backend->deleteCalendarObject($calendarId, $uri2); + $calendarObjects = $this->backend->getCalendarObjects($calendarId); + $this->assertEquals(0, count($calendarObjects)); + } + + /** + * @dataProvider providesCalendarQueryParameters + */ + public function testCalendarQuery($expectedEventsInResult, $propFilters, $compFilter) { + $calendarId = $this->createTestCalendar(); + $events = []; + $events[0] = $this->createEvent($calendarId, '20130912T130000Z', '20130912T140000Z'); + $events[1] = $this->createEvent($calendarId, '20130912T150000Z', '20130912T170000Z'); + $events[2] = $this->createEvent($calendarId, '20130912T173000Z', '20130912T220000Z'); + $events[3] = $this->createEvent($calendarId, '21130912T130000Z', '22130912T130000Z'); + + $result = $this->backend->calendarQuery($calendarId, [ + 'name' => '', + 'prop-filters' => $propFilters, + 'comp-filters' => $compFilter + ]); + + $expectedEventsInResult = array_map(function($index) use($events) { + return $events[$index]; + }, $expectedEventsInResult); + $this->assertEquals($expectedEventsInResult, $result, '', 0.0, 10, true); + } + + public function testGetCalendarObjectByUID() { + $calendarId = $this->createTestCalendar(); + $this->createEvent($calendarId, '20130912T130000Z', '20130912T140000Z'); + + $co = $this->backend->getCalendarObjectByUID(self::UNIT_TEST_USER, '47d15e3ec8'); + $this->assertNotNull($co); + } + + public function providesCalendarQueryParameters() { + return [ + 'all' => [[0, 1, 2, 3], [], []], + 'only-todos' => [[], ['name' => 'VTODO'], []], + 'only-events' => [[0, 1, 2, 3], [], [['name' => 'VEVENT', 'is-not-defined' => false, 'comp-filters' => [], 'time-range' => ['start' => null, 'end' => null], 'prop-filters' => []]],], + 'start' => [[1, 2, 3], [], [['name' => 'VEVENT', 'is-not-defined' => false, 'comp-filters' => [], 'time-range' => ['start' => new DateTime('2013-09-12 14:00:00', new DateTimeZone('UTC')), 'end' => null], 'prop-filters' => []]],], + 'end' => [[0], [], [['name' => 'VEVENT', 'is-not-defined' => false, 'comp-filters' => [], 'time-range' => ['start' => null, 'end' => new DateTime('2013-09-12 14:00:00', new DateTimeZone('UTC'))], 'prop-filters' => []]],], + 'future' => [[3], [], [['name' => 'VEVENT', 'is-not-defined' => false, 'comp-filters' => [], 'time-range' => ['start' => new DateTime('2099-09-12 14:00:00', new DateTimeZone('UTC')), 'end' => null], 'prop-filters' => []]],], + ]; + } + + private function createTestCalendar() { + $this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', [ + '{http://apple.com/ns/ical/}calendar-color' => '#1C4587FF' + ]); + $calendars = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($calendars)); + $this->assertEquals(self::UNIT_TEST_USER, $calendars[0]['principaluri']); + /** @var SupportedCalendarComponentSet $components */ + $components = $calendars[0]['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set']; + $this->assertEquals(['VEVENT','VTODO'], $components->getValue()); + $color = $calendars[0]['{http://apple.com/ns/ical/}calendar-color']; + $this->assertEquals('#1C4587FF', $color); + $this->assertEquals('Example', $calendars[0]['uri']); + $this->assertEquals('Example', $calendars[0]['{DAV:}displayname']); + $calendarId = $calendars[0]['id']; + + return $calendarId; + } + + private function createEvent($calendarId, $start = '20130912T130000Z', $end = '20130912T140000Z') { + + $calData = <<getUniqueID('event'); + $this->backend->createCalendarObject($calendarId, $uri0, $calData); + + return $uri0; + } + + public function testSyncSupport() { + $calendarId = $this->createTestCalendar(); + + // fist call without synctoken + $changes = $this->backend->getChangesForCalendar($calendarId, '', 1); + $syncToken = $changes['syncToken']; + + // add a change + $event = $this->createEvent($calendarId, '20130912T130000Z', '20130912T140000Z'); + + // look for changes + $changes = $this->backend->getChangesForCalendar($calendarId, $syncToken, 1); + $this->assertEquals($event, $changes['added'][0]); + } + + public function testSubscriptions() { + $id = $this->backend->createSubscription(self::UNIT_TEST_USER, 'Subscription', [ + '{http://calendarserver.org/ns/}source' => new Href('test-source') + ]); + + $subscriptions = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($subscriptions)); + $this->assertEquals($id, $subscriptions[0]['id']); + + $patch = new PropPatch([ + '{DAV:}displayname' => 'Unit test', + ]); + $this->backend->updateSubscription($id, $patch); + $patch->commit(); + + $subscriptions = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($subscriptions)); + $this->assertEquals($id, $subscriptions[0]['id']); + $this->assertEquals('Unit test', $subscriptions[0]['{DAV:}displayname']); + + $this->backend->deleteSubscription($id); + $subscriptions = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); + $this->assertEquals(0, count($subscriptions)); + } + + public function testScheduling() { + $this->backend->createSchedulingObject(self::UNIT_TEST_USER, 'Sample Schedule', ''); + + $sos = $this->backend->getSchedulingObjects(self::UNIT_TEST_USER); + $this->assertEquals(1, count($sos)); + + $so = $this->backend->getSchedulingObject(self::UNIT_TEST_USER, 'Sample Schedule'); + $this->assertNotNull($so); + + $this->backend->deleteSchedulingObject(self::UNIT_TEST_USER, 'Sample Schedule'); + + $sos = $this->backend->getSchedulingObjects(self::UNIT_TEST_USER); + $this->assertEquals(0, count($sos)); + } + + /** + * @dataProvider providesCalDataForGetDenormalizedData + */ + public function testGetDenormalizedData($expectedFirstOccurance, $calData) { + $actual = $this->invokePrivate($this->backend, 'getDenormalizedData', [$calData]); + $this->assertEquals($expectedFirstOccurance, $actual['firstOccurence']); + } + + public function providesCalDataForGetDenormalizedData() { + return [ + [0, "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:413F269B-B51B-46B1-AFB6-40055C53A4DC\r\nDTSTAMP:20160309T095056Z\r\nDTSTART;VALUE=DATE:16040222\r\nDTEND;VALUE=DATE:16040223\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:SUMMARY\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], + [null, "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:413F269B-B51B-46B1-AFB6-40055C53A4DC\r\nDTSTAMP:20160309T095056Z\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:SUMMARY\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"] + ]; + } + + private function assertAcl($principal, $privilege, $acl) { + foreach($acl as $a) { + if ($a['principal'] === $principal && $a['privilege'] === $privilege) { + $this->assertTrue(true); + return; + } + } + $this->fail("ACL does not contain $principal / $privilege"); + } + + private function assertNotAcl($principal, $privilege, $acl) { + foreach($acl as $a) { + if ($a['principal'] === $principal && $a['privilege'] === $privilege) { + $this->fail("ACL contains $principal / $privilege"); + return; + } + } + $this->assertTrue(true); + } + + private function assertAccess($shouldHaveAcl, $principal, $privilege, $acl) { + if ($shouldHaveAcl) { + $this->assertAcl($principal, $privilege, $acl); + } else { + $this->assertNotAcl($principal, $privilege, $acl); + } + } +} diff --git a/apps/dav/tests/unit/CalDAV/CalendarTest.php b/apps/dav/tests/unit/CalDAV/CalendarTest.php new file mode 100644 index 00000000000..cfaa2d89016 --- /dev/null +++ b/apps/dav/tests/unit/CalDAV/CalendarTest.php @@ -0,0 +1,191 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CalDAV; + +use OCA\DAV\CalDAV\BirthdayService; +use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\CalDAV\Calendar; +use OCP\IL10N; +use Sabre\DAV\PropPatch; +use Test\TestCase; + +class CalendarTest extends TestCase { + + /** @var IL10N */ + private $l10n; + + public function setUp() { + parent::setUp(); + $this->l10n = $this->getMockBuilder('\OCP\IL10N') + ->disableOriginalConstructor()->getMock(); + $this->l10n + ->expects($this->any()) + ->method('t') + ->will($this->returnCallback(function ($text, $parameters = array()) { + return vsprintf($text, $parameters); + })); + } + + public function testDelete() { + /** @var \PHPUnit_Framework_MockObject_MockObject | CalDavBackend $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); + $backend->expects($this->once())->method('updateShares'); + $backend->expects($this->any())->method('getShares')->willReturn([ + ['href' => 'principal:user2'] + ]); + $calendarInfo = [ + '{http://owncloud.org/ns}owner-principal' => 'user1', + 'principaluri' => 'user2', + 'id' => 666, + 'uri' => 'cal', + ]; + $c = new Calendar($backend, $calendarInfo, $this->l10n); + $c->delete(); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDeleteFromGroup() { + /** @var \PHPUnit_Framework_MockObject_MockObject | CalDavBackend $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); + $backend->expects($this->never())->method('updateShares'); + $backend->expects($this->any())->method('getShares')->willReturn([ + ['href' => 'principal:group2'] + ]); + $calendarInfo = [ + '{http://owncloud.org/ns}owner-principal' => 'user1', + 'principaluri' => 'user2', + 'id' => 666, + 'uri' => 'cal', + ]; + $c = new Calendar($backend, $calendarInfo, $this->l10n); + $c->delete(); + } + + public function dataPropPatch() { + return [ + [[], true], + [[ + '{http://owncloud.org/ns}calendar-enabled' => true, + ], false], + [[ + '{DAV:}displayname' => true, + ], true], + [[ + '{DAV:}displayname' => true, + '{http://owncloud.org/ns}calendar-enabled' => true, + ], true], + ]; + } + + /** + * @dataProvider dataPropPatch + */ + public function testPropPatch($mutations, $throws) { + /** @var \PHPUnit_Framework_MockObject_MockObject | CalDavBackend $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); + $calendarInfo = [ + '{http://owncloud.org/ns}owner-principal' => 'user1', + 'principaluri' => 'user2', + 'id' => 666, + 'uri' => 'default' + ]; + $c = new Calendar($backend, $calendarInfo, $this->l10n); + + if ($throws) { + $this->setExpectedException('\Sabre\DAV\Exception\Forbidden'); + } + $c->propPatch(new PropPatch($mutations)); + if (!$throws) { + $this->assertTrue(true); + } + } + + /** + * @dataProvider providesReadOnlyInfo + */ + public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet, $uri = 'default') { + /** @var \PHPUnit_Framework_MockObject_MockObject | CalDavBackend $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); + $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1); + $calendarInfo = [ + 'principaluri' => 'user2', + 'id' => 666, + 'uri' => $uri + ]; + if (!is_null($readOnlyValue)) { + $calendarInfo['{http://owncloud.org/ns}read-only'] = $readOnlyValue; + } + if ($hasOwnerSet) { + $calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1'; + } + $c = new Calendar($backend, $calendarInfo, $this->l10n); + $acl = $c->getACL(); + $childAcl = $c->getChildACL(); + + $expectedAcl = [[ + 'privilege' => '{DAV:}read', + 'principal' => $hasOwnerSet ? 'user1' : 'user2', + 'protected' => true + ], [ + 'privilege' => '{DAV:}write', + 'principal' => $hasOwnerSet ? 'user1' : 'user2', + 'protected' => true + ]]; + if ($uri === BirthdayService::BIRTHDAY_CALENDAR_URI) { + $expectedAcl = [[ + 'privilege' => '{DAV:}read', + 'principal' => $hasOwnerSet ? 'user1' : 'user2', + 'protected' => true + ]]; + } + if ($hasOwnerSet) { + $expectedAcl[] = [ + 'privilege' => '{DAV:}read', + 'principal' => 'user2', + 'protected' => true + ]; + if ($expectsWrite) { + $expectedAcl[] = [ + 'privilege' => '{DAV:}write', + 'principal' => 'user2', + 'protected' => true + ]; + } + } + $this->assertEquals($expectedAcl, $acl); + $this->assertEquals($expectedAcl, $childAcl); + } + + public function providesReadOnlyInfo() { + return [ + 'read-only property not set' => [true, null, true], + 'read-only property is false' => [true, false, true], + 'read-only property is true' => [false, true, true], + 'read-only property not set and no owner' => [true, null, false], + 'read-only property is false and no owner' => [true, false, false], + 'read-only property is true and no owner' => [false, true, false], + 'birthday calendar' => [false, false, false, BirthdayService::BIRTHDAY_CALENDAR_URI] + ]; + } +} diff --git a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php new file mode 100644 index 00000000000..addb585e41b --- /dev/null +++ b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php @@ -0,0 +1,91 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CalDAV\Schedule; + +use OC\Mail\Mailer; +use OCA\DAV\CalDAV\Schedule\IMipPlugin; +use OCP\ILogger; +use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\ITip\Message; +use Test\TestCase; + +class IMipPluginTest extends TestCase { + + public function testDelivery() { + $mailMessage = new \OC\Mail\Message(new \Swift_Message()); + /** @var Mailer | \PHPUnit_Framework_MockObject_MockObject $mailer */ + $mailer = $this->getMockBuilder('OC\Mail\Mailer')->disableOriginalConstructor()->getMock(); + $mailer->method('createMessage')->willReturn($mailMessage); + $mailer->expects($this->once())->method('send'); + /** @var ILogger | \PHPUnit_Framework_MockObject_MockObject $logger */ + $logger = $this->getMockBuilder('OC\Log')->disableOriginalConstructor()->getMock(); + + $plugin = new IMipPlugin($mailer, $logger); + $message = new Message(); + $message->method = 'REQUEST'; + $message->message = new VCalendar(); + $message->message->add('VEVENT', [ + 'UID' => $message->uid, + 'SEQUENCE' => $message->sequence, + 'SUMMARY' => 'Fellowship meeting', + ]); + $message->sender = 'mailto:gandalf@wiz.ard'; + $message->recipient = 'mailto:frodo@hobb.it'; + + $plugin->schedule($message); + $this->assertEquals('1.1', $message->getScheduleStatus()); + $this->assertEquals('Fellowship meeting', $mailMessage->getSubject()); + $this->assertEquals(['frodo@hobb.it' => null], $mailMessage->getTo()); + $this->assertEquals(['gandalf@wiz.ard' => null], $mailMessage->getReplyTo()); + $this->assertEquals('text/calendar; charset=UTF-8; method=REQUEST', $mailMessage->getSwiftMessage()->getContentType()); + } + + public function testFailedDelivery() { + $mailMessage = new \OC\Mail\Message(new \Swift_Message()); + /** @var Mailer | \PHPUnit_Framework_MockObject_MockObject $mailer */ + $mailer = $this->getMockBuilder('OC\Mail\Mailer')->disableOriginalConstructor()->getMock(); + $mailer->method('createMessage')->willReturn($mailMessage); + $mailer->method('send')->willThrowException(new \Exception()); + /** @var ILogger | \PHPUnit_Framework_MockObject_MockObject $logger */ + $logger = $this->getMockBuilder('OC\Log')->disableOriginalConstructor()->getMock(); + + $plugin = new IMipPlugin($mailer, $logger); + $message = new Message(); + $message->method = 'REQUEST'; + $message->message = new VCalendar(); + $message->message->add('VEVENT', [ + 'UID' => $message->uid, + 'SEQUENCE' => $message->sequence, + 'SUMMARY' => 'Fellowship meeting', + ]); + $message->sender = 'mailto:gandalf@wiz.ard'; + $message->recipient = 'mailto:frodo@hobb.it'; + + $plugin->schedule($message); + $this->assertEquals('5.0', $message->getScheduleStatus()); + $this->assertEquals('Fellowship meeting', $mailMessage->getSubject()); + $this->assertEquals(['frodo@hobb.it' => null], $mailMessage->getTo()); + $this->assertEquals(['gandalf@wiz.ard' => null], $mailMessage->getReplyTo()); + $this->assertEquals('text/calendar; charset=UTF-8; method=REQUEST', $mailMessage->getSwiftMessage()->getContentType()); + } + +} diff --git a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php new file mode 100644 index 00000000000..25da92bbf23 --- /dev/null +++ b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php @@ -0,0 +1,288 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + + +namespace OCA\DAV\Tests\unit\CardDAV; + + +use OCA\DAV\CardDAV\AddressBook; +use OCA\DAV\CardDAV\AddressBookImpl; +use OCA\DAV\CardDAV\CardDavBackend; +use Sabre\VObject\Component\VCard; +use Sabre\VObject\Property\Text; +use Test\TestCase; + +class AddressBookImplTest extends TestCase { + + /** @var AddressBookImpl */ + private $addressBookImpl; + + /** @var array */ + private $addressBookInfo; + + /** @var AddressBook | \PHPUnit_Framework_MockObject_MockObject */ + private $addressBook; + + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject */ + private $backend; + + /** @var VCard | \PHPUnit_Framework_MockObject_MockObject */ + private $vCard; + + public function setUp() { + parent::setUp(); + + $this->addressBookInfo = [ + 'id' => 42, + '{DAV:}displayname' => 'display name' + ]; + $this->addressBook = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBook') + ->disableOriginalConstructor()->getMock(); + $this->backend = $this->getMockBuilder('\OCA\DAV\CardDAV\CardDavBackend') + ->disableOriginalConstructor()->getMock(); + $this->vCard = $this->getMock('Sabre\VObject\Component\VCard'); + + $this->addressBookImpl = new AddressBookImpl( + $this->addressBook, + $this->addressBookInfo, + $this->backend + ); + } + + public function testGetKey() { + $this->assertSame($this->addressBookInfo['id'], + $this->addressBookImpl->getKey()); + } + + public function testGetDisplayName() { + $this->assertSame($this->addressBookInfo['{DAV:}displayname'], + $this->addressBookImpl->getDisplayName()); + } + + public function testSearch() { + + /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ + $addressBookImpl = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBookImpl') + ->setConstructorArgs( + [ + $this->addressBook, + $this->addressBookInfo, + $this->backend + ] + ) + ->setMethods(['vCard2Array', 'readCard']) + ->getMock(); + + $pattern = 'pattern'; + $searchProperties = 'properties'; + + $this->backend->expects($this->once())->method('search') + ->with($this->addressBookInfo['id'], $pattern, $searchProperties) + ->willReturn( + [ + 'cardData1', + 'cardData2' + ] + ); + + $addressBookImpl->expects($this->exactly(2))->method('readCard') + ->willReturn($this->vCard); + $addressBookImpl->expects($this->exactly(2))->method('vCard2Array') + ->with($this->vCard)->willReturn('vCard'); + + $result = $addressBookImpl->search($pattern, $searchProperties, []); + $this->assertTrue((is_array($result))); + $this->assertSame(2, count($result)); + } + + /** + * @dataProvider dataTestCreate + * + * @param array $properties + */ + public function testCreate($properties) { + + $uid = 'uid'; + + /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ + $addressBookImpl = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBookImpl') + ->setConstructorArgs( + [ + $this->addressBook, + $this->addressBookInfo, + $this->backend + ] + ) + ->setMethods(['vCard2Array', 'createUid', 'createEmptyVCard']) + ->getMock(); + + $addressBookImpl->expects($this->once())->method('createUid') + ->willReturn($uid); + $addressBookImpl->expects($this->once())->method('createEmptyVCard') + ->with($uid)->willReturn($this->vCard); + $this->vCard->expects($this->exactly(count($properties))) + ->method('createProperty'); + $this->backend->expects($this->once())->method('createCard'); + $this->backend->expects($this->never())->method('updateCard'); + $this->backend->expects($this->never())->method('getCard'); + $addressBookImpl->expects($this->once())->method('vCard2Array') + ->with($this->vCard)->willReturn(true); + + $this->assertTrue($addressBookImpl->createOrUpdate($properties)); + } + + public function dataTestCreate() { + return [ + [[]], + [['FN' => 'John Doe']] + ]; + } + + public function testUpdate() { + + $uid = 'uid'; + $properties = ['UID' => $uid, 'FN' => 'John Doe']; + + /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ + $addressBookImpl = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBookImpl') + ->setConstructorArgs( + [ + $this->addressBook, + $this->addressBookInfo, + $this->backend + ] + ) + ->setMethods(['vCard2Array', 'createUid', 'createEmptyVCard', 'readCard']) + ->getMock(); + + $addressBookImpl->expects($this->never())->method('createUid'); + $addressBookImpl->expects($this->never())->method('createEmptyVCard'); + $this->backend->expects($this->once())->method('getCard') + ->with($this->addressBookInfo['id'], $uid . '.vcf') + ->willReturn(['carddata' => 'data']); + $addressBookImpl->expects($this->once())->method('readCard') + ->with('data')->willReturn($this->vCard); + $this->vCard->expects($this->exactly(count($properties))) + ->method('createProperty'); + $this->backend->expects($this->never())->method('createCard'); + $this->backend->expects($this->once())->method('updateCard'); + $addressBookImpl->expects($this->once())->method('vCard2Array') + ->with($this->vCard)->willReturn(true); + + $this->assertTrue($addressBookImpl->createOrUpdate($properties)); + } + + /** + * @dataProvider dataTestGetPermissions + * + * @param array $permissions + * @param int $expected + */ + public function testGetPermissions($permissions, $expected) { + $this->addressBook->expects($this->once())->method('getACL') + ->willReturn($permissions); + + $this->assertSame($expected, + $this->addressBookImpl->getPermissions() + ); + } + + public function dataTestGetPermissions() { + return [ + [[], 0], + [[['privilege' => '{DAV:}read']], 1], + [[['privilege' => '{DAV:}write']], 6], + [[['privilege' => '{DAV:}all']], 31], + [[['privilege' => '{DAV:}read'],['privilege' => '{DAV:}write']], 7], + [[['privilege' => '{DAV:}read'],['privilege' => '{DAV:}all']], 31], + [[['privilege' => '{DAV:}all'],['privilege' => '{DAV:}write']], 31], + [[['privilege' => '{DAV:}read'],['privilege' => '{DAV:}write'],['privilege' => '{DAV:}all']], 31], + [[['privilege' => '{DAV:}all'],['privilege' => '{DAV:}read'],['privilege' => '{DAV:}write']], 31], + ]; + } + + public function testDelete() { + $cardId = 1; + $cardUri = 'cardUri'; + $this->backend->expects($this->once())->method('getCardUri') + ->with($cardId)->willReturn($cardUri); + $this->backend->expects($this->once())->method('deleteCard') + ->with($this->addressBookInfo['id'], $cardUri) + ->willReturn(true); + + $this->assertTrue($this->addressBookImpl->delete($cardId)); + } + + public function testReadCard() { + $vCard = new VCard(); + $vCard->add(new Text($vCard, 'UID', 'uid')); + $vCardSerialized = $vCard->serialize(); + + $result = $this->invokePrivate($this->addressBookImpl, 'readCard', [$vCardSerialized]); + $resultSerialized = $result->serialize(); + + $this->assertSame($vCardSerialized, $resultSerialized); + } + + public function testCreateUid() { + /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ + $addressBookImpl = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBookImpl') + ->setConstructorArgs( + [ + $this->addressBook, + $this->addressBookInfo, + $this->backend + ] + ) + ->setMethods(['getUid']) + ->getMock(); + + $addressBookImpl->expects($this->at(0))->method('getUid')->willReturn('uid0'); + $addressBookImpl->expects($this->at(1))->method('getUid')->willReturn('uid1'); + + // simulate that 'uid0' already exists, so the second uid will be returned + $this->backend->expects($this->exactly(2))->method('getContact') + ->willReturnCallback( + function($id, $uid) { + return ($uid === 'uid0.vcf'); + } + ); + + $this->assertSame('uid1', + $this->invokePrivate($addressBookImpl, 'createUid', []) + ); + + } + + public function testCreateEmptyVCard() { + $uid = 'uid'; + $expectedVCard = new VCard(); + $expectedVCard->add(new Text($expectedVCard, 'UID', $uid)); + $expectedVCardSerialized = $expectedVCard->serialize(); + + $result = $this->invokePrivate($this->addressBookImpl, 'createEmptyVCard', [$uid]); + $resultSerialized = $result->serialize(); + + $this->assertSame($expectedVCardSerialized, $resultSerialized); + } + +} diff --git a/apps/dav/tests/unit/CardDAV/AddressBookTest.php b/apps/dav/tests/unit/CardDAV/AddressBookTest.php new file mode 100644 index 00000000000..7144c36140c --- /dev/null +++ b/apps/dav/tests/unit/CardDAV/AddressBookTest.php @@ -0,0 +1,139 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CardDAV; + +use OCA\DAV\CardDAV\AddressBook; +use OCA\DAV\CardDAV\CardDavBackend; +use Sabre\DAV\PropPatch; +use Test\TestCase; + +class AddressBookTest extends TestCase { + + public function testDelete() { + /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backend->expects($this->once())->method('updateShares'); + $backend->expects($this->any())->method('getShares')->willReturn([ + ['href' => 'principal:user2'] + ]); + $calendarInfo = [ + '{http://owncloud.org/ns}owner-principal' => 'user1', + 'principaluri' => 'user2', + 'id' => 666 + ]; + $c = new AddressBook($backend, $calendarInfo); + $c->delete(); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDeleteFromGroup() { + /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backend->expects($this->never())->method('updateShares'); + $backend->expects($this->any())->method('getShares')->willReturn([ + ['href' => 'principal:group2'] + ]); + $calendarInfo = [ + '{http://owncloud.org/ns}owner-principal' => 'user1', + 'principaluri' => 'user2', + 'id' => 666 + ]; + $c = new AddressBook($backend, $calendarInfo); + $c->delete(); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testPropPatch() { + /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $calendarInfo = [ + '{http://owncloud.org/ns}owner-principal' => 'user1', + 'principaluri' => 'user2', + 'id' => 666 + ]; + $c = new AddressBook($backend, $calendarInfo); + $c->propPatch(new PropPatch([])); + } + + /** + * @dataProvider providesReadOnlyInfo + */ + public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet) { + /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1); + $calendarInfo = [ + 'principaluri' => 'user2', + 'id' => 666, + 'uri' => 'default' + ]; + if (!is_null($readOnlyValue)) { + $calendarInfo['{http://owncloud.org/ns}read-only'] = $readOnlyValue; + } + if ($hasOwnerSet) { + $calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1'; + } + $c = new AddressBook($backend, $calendarInfo); + $acl = $c->getACL(); + $childAcl = $c->getChildACL(); + + $expectedAcl = [[ + 'privilege' => '{DAV:}read', + 'principal' => $hasOwnerSet ? 'user1' : 'user2', + 'protected' => true + ], [ + 'privilege' => '{DAV:}write', + 'principal' => $hasOwnerSet ? 'user1' : 'user2', + 'protected' => true + ]]; + if ($hasOwnerSet) { + $expectedAcl[] = [ + 'privilege' => '{DAV:}read', + 'principal' => 'user2', + 'protected' => true + ]; + if ($expectsWrite) { + $expectedAcl[] = [ + 'privilege' => '{DAV:}write', + 'principal' => 'user2', + 'protected' => true + ]; + } + } + $this->assertEquals($expectedAcl, $acl); + $this->assertEquals($expectedAcl, $childAcl); + } + + public function providesReadOnlyInfo() { + return [ + 'read-only property not set' => [true, null, true], + 'read-only property is false' => [true, false, true], + 'read-only property is true' => [false, true, true], + 'read-only property not set and no owner' => [true, null, false], + 'read-only property is false and no owner' => [true, false, false], + 'read-only property is true and no owner' => [false, true, false], + ]; + }} diff --git a/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php b/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php new file mode 100644 index 00000000000..0162924064d --- /dev/null +++ b/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php @@ -0,0 +1,216 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CardDAV; + +use OCA\DAV\CalDAV\BirthdayService; +use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\CardDAV\CardDavBackend; +use OCA\DAV\DAV\GroupPrincipalBackend; +use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\Reader; +use Test\TestCase; + +class BirthdayServiceTest extends TestCase { + + /** @var BirthdayService */ + private $service; + /** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject */ + private $calDav; + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject */ + private $cardDav; + /** @var GroupPrincipalBackend | \PHPUnit_Framework_MockObject_MockObject */ + private $groupPrincialBackend; + + public function setUp() { + parent::setUp(); + + $this->calDav = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); + $this->cardDav = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $this->groupPrincialBackend = $this->getMockBuilder('OCA\DAV\DAV\GroupPrincipalBackend')->disableOriginalConstructor()->getMock(); + + $this->service = new BirthdayService($this->calDav, $this->cardDav, $this->groupPrincialBackend); + } + + /** + * @dataProvider providesVCards + * @param boolean $nullExpected + * @param string | null $data + */ + public function testBuildBirthdayFromContact($nullExpected, $data) { + $cal = $this->service->buildBirthdayFromContact($data); + if ($nullExpected) { + $this->assertNull($cal); + } else { + $this->assertInstanceOf('Sabre\VObject\Component\VCalendar', $cal); + $this->assertTrue(isset($cal->VEVENT)); + $this->assertEquals('FREQ=YEARLY', $cal->VEVENT->RRULE->getValue()); + $this->assertEquals('12345 (*1900)', $cal->VEVENT->SUMMARY->getValue()); + $this->assertEquals('TRANSPARENT', $cal->VEVENT->TRANSP->getValue()); + } + } + + public function testOnCardDeleted() { + $this->cardDav->expects($this->once())->method('getAddressBookById') + ->with(666) + ->willReturn([ + 'principaluri' => 'principals/users/user01', + 'uri' => 'default' + ]); + $this->calDav->expects($this->once())->method('getCalendarByUri') + ->with('principals/users/user01', 'contact_birthdays') + ->willReturn([ + 'id' => 1234 + ]); + $this->calDav->expects($this->once())->method('deleteCalendarObject')->with(1234, 'default-gump.vcf.ics'); + $this->cardDav->expects($this->once())->method('getShares')->willReturn([]); + + $this->service->onCardDeleted(666, 'gump.vcf'); + } + + /** + * @dataProvider providesCardChanges + */ + public function testOnCardChanged($expectedOp) { + $this->cardDav->expects($this->once())->method('getAddressBookById') + ->with(666) + ->willReturn([ + 'principaluri' => 'principals/users/user01', + 'uri' => 'default' + ]); + $this->calDav->expects($this->once())->method('getCalendarByUri') + ->with('principals/users/user01', 'contact_birthdays') + ->willReturn([ + 'id' => 1234 + ]); + $this->cardDav->expects($this->once())->method('getShares')->willReturn([]); + + /** @var BirthdayService | \PHPUnit_Framework_MockObject_MockObject $service */ + $service = $this->getMock('\OCA\DAV\CalDAV\BirthdayService', + ['buildBirthdayFromContact', 'birthdayEvenChanged'], [$this->calDav, $this->cardDav, $this->groupPrincialBackend]); + + if ($expectedOp === 'delete') { + $this->calDav->expects($this->once())->method('getCalendarObject')->willReturn(''); + $service->expects($this->once())->method('buildBirthdayFromContact')->willReturn(null); + $this->calDav->expects($this->once())->method('deleteCalendarObject')->with(1234, 'default-gump.vcf.ics'); + } + if ($expectedOp === 'create') { + $service->expects($this->once())->method('buildBirthdayFromContact')->willReturn(new VCalendar()); + $this->calDav->expects($this->once())->method('createCalendarObject')->with(1234, 'default-gump.vcf.ics', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nEND:VCALENDAR\r\n"); + } + if ($expectedOp === 'update') { + $service->expects($this->once())->method('buildBirthdayFromContact')->willReturn(new VCalendar()); + $service->expects($this->once())->method('birthdayEvenChanged')->willReturn(true); + $this->calDav->expects($this->once())->method('getCalendarObject')->willReturn([ + 'calendardata' => '']); + $this->calDav->expects($this->once())->method('updateCalendarObject')->with(1234, 'default-gump.vcf.ics', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nEND:VCALENDAR\r\n"); + } + + $service->onCardChanged(666, 'gump.vcf', ''); + } + + /** + * @dataProvider providesBirthday + * @param $expected + * @param $old + * @param $new + */ + public function testBirthdayEvenChanged($expected, $old, $new) { + $new = Reader::read($new); + $this->assertEquals($expected, $this->service->birthdayEvenChanged($old, $new)); + } + + public function testGetAllAffectedPrincipals() { + $this->cardDav->expects($this->once())->method('getShares')->willReturn([ + [ + '{http://owncloud.org/ns}group-share' => false, + '{http://owncloud.org/ns}principal' => 'principals/users/user01' + ], + [ + '{http://owncloud.org/ns}group-share' => false, + '{http://owncloud.org/ns}principal' => 'principals/users/user01' + ], + [ + '{http://owncloud.org/ns}group-share' => false, + '{http://owncloud.org/ns}principal' => 'principals/users/user02' + ], + [ + '{http://owncloud.org/ns}group-share' => true, + '{http://owncloud.org/ns}principal' => 'principals/groups/users' + ], + ]); + $this->groupPrincialBackend->expects($this->once())->method('getGroupMemberSet') + ->willReturn([ + [ + 'uri' => 'principals/users/user01', + ], + [ + 'uri' => 'principals/users/user02', + ], + [ + 'uri' => 'principals/users/user03', + ], + ]); + $users = $this->invokePrivate($this->service, 'getAllAffectedPrincipals', [6666]); + $this->assertEquals([ + 'principals/users/user01', + 'principals/users/user02', + 'principals/users/user03' + ], $users); + } + + public function providesBirthday() { + return [ + [true, + '', + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], + [false, + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], + [true, + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:4567's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], + [true, + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", + "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000102\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"] + ]; + } + + public function providesCardChanges(){ + return[ + ['delete'], + ['create'], + ['update'] + ]; + } + + public function providesVCards() { + return [ + [true, null], + [true, ''], + [true, 'yasfewf'], + [true, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nEND:VCARD\r\n", "Dr. Foo Bar"], + [true, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nBDAY:\r\nEND:VCARD\r\n", "Dr. Foo Bar"], + [true, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nBDAY:someday\r\nEND:VCARD\r\n", "Dr. Foo Bar"], + [false, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nBDAY:1900-01-01\r\nEND:VCARD\r\n", "Dr. Foo Bar"], + ]; + } +} diff --git a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php new file mode 100644 index 00000000000..7cae76ae62b --- /dev/null +++ b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php @@ -0,0 +1,632 @@ + + * @author Björn Schießle + * @author Joas Schilling + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CardDAV; + +use InvalidArgumentException; +use OCA\DAV\CardDAV\AddressBook; +use OCA\DAV\CardDAV\CardDavBackend; +use OCA\DAV\Connector\Sabre\Principal; +use OCP\DB\QueryBuilder\IQueryBuilder; +use OCP\IDBConnection; +use Sabre\DAV\PropPatch; +use Sabre\VObject\Component\VCard; +use Sabre\VObject\Property\Text; +use Test\TestCase; + +/** + * Class CardDavBackendTest + * + * @group DB + * + * @package OCA\DAV\Tests\unit\CardDAV + */ +class CardDavBackendTest extends TestCase { + + /** @var CardDavBackend */ + private $backend; + + /** @var Principal | \PHPUnit_Framework_MockObject_MockObject */ + private $principal; + + /** @var IDBConnection */ + private $db; + + /** @var string */ + private $dbCardsTable = 'cards'; + + /** @var string */ + private $dbCardsPropertiesTable = 'cards_properties'; + + const UNIT_TEST_USER = 'principals/users/carddav-unit-test'; + const UNIT_TEST_USER1 = 'principals/users/carddav-unit-test1'; + const UNIT_TEST_GROUP = 'principals/groups/carddav-unit-test-group'; + + public function setUp() { + parent::setUp(); + + $this->principal = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Principal') + ->disableOriginalConstructor() + ->setMethods(['getPrincipalByPath', 'getGroupMembership']) + ->getMock(); + $this->principal->method('getPrincipalByPath') + ->willReturn([ + 'uri' => 'principals/best-friend' + ]); + $this->principal->method('getGroupMembership') + ->withAnyParameters() + ->willReturn([self::UNIT_TEST_GROUP]); + + $this->db = \OC::$server->getDatabaseConnection(); + + $this->backend = new CardDavBackend($this->db, $this->principal, null); + + // start every test with a empty cards_properties and cards table + $query = $this->db->getQueryBuilder(); + $query->delete('cards_properties')->execute(); + $query = $this->db->getQueryBuilder(); + $query->delete('cards')->execute(); + + + $this->tearDown(); + } + + public function tearDown() { + parent::tearDown(); + + if (is_null($this->backend)) { + return; + } + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + foreach ($books as $book) { + $this->backend->deleteAddressBook($book['id']); + } + } + + public function testAddressBookOperations() { + + // create a new address book + $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + $this->assertEquals('Example', $books[0]['{DAV:}displayname']); + + // update it's display name + $patch = new PropPatch([ + '{DAV:}displayname' => 'Unit test', + '{urn:ietf:params:xml:ns:carddav}addressbook-description' => 'Addressbook used for unit testing' + ]); + $this->backend->updateAddressBook($books[0]['id'], $patch); + $patch->commit(); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + $this->assertEquals('Unit test', $books[0]['{DAV:}displayname']); + $this->assertEquals('Addressbook used for unit testing', $books[0]['{urn:ietf:params:xml:ns:carddav}addressbook-description']); + + // delete the address book + $this->backend->deleteAddressBook($books[0]['id']); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(0, count($books)); + } + + public function testAddressBookSharing() { + + $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + $addressBook = new AddressBook($this->backend, $books[0]); + $this->backend->updateShares($addressBook, [ + [ + 'href' => 'principal:' . self::UNIT_TEST_USER1, + ], + [ + 'href' => 'principal:' . self::UNIT_TEST_GROUP, + ] + ], []); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1); + $this->assertEquals(1, count($books)); + + // delete the address book + $this->backend->deleteAddressBook($books[0]['id']); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(0, count($books)); + } + + public function testCardOperations() { + + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') + ->setConstructorArgs([$this->db, $this->principal, null]) + ->setMethods(['updateProperties', 'purgeProperties'])->getMock(); + + // create a new address book + $backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + $books = $backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + $bookId = $books[0]['id']; + + $uri = $this->getUniqueID('card'); + // updateProperties is expected twice, once for createCard and once for updateCard + $backend->expects($this->at(0))->method('updateProperties')->with($bookId, $uri, ''); + $backend->expects($this->at(1))->method('updateProperties')->with($bookId, $uri, '***'); + // create a card + $backend->createCard($bookId, $uri, ''); + + // get all the cards + $cards = $backend->getCards($bookId); + $this->assertEquals(1, count($cards)); + $this->assertEquals('', $cards[0]['carddata']); + + // get the cards + $card = $backend->getCard($bookId, $uri); + $this->assertNotNull($card); + $this->assertArrayHasKey('id', $card); + $this->assertArrayHasKey('uri', $card); + $this->assertArrayHasKey('lastmodified', $card); + $this->assertArrayHasKey('etag', $card); + $this->assertArrayHasKey('size', $card); + $this->assertEquals('', $card['carddata']); + + // update the card + $backend->updateCard($bookId, $uri, '***'); + $card = $backend->getCard($bookId, $uri); + $this->assertEquals('***', $card['carddata']); + + // delete the card + $backend->expects($this->once())->method('purgeProperties')->with($bookId, $card['id']); + $backend->deleteCard($bookId, $uri); + $cards = $backend->getCards($bookId); + $this->assertEquals(0, count($cards)); + } + + public function testMultiCard() { + + $this->backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') + ->setConstructorArgs([$this->db, $this->principal, null]) + ->setMethods(['updateProperties'])->getMock(); + + // create a new address book + $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + $bookId = $books[0]['id']; + + // create a card + $uri0 = $this->getUniqueID('card'); + $this->backend->createCard($bookId, $uri0, ''); + $uri1 = $this->getUniqueID('card'); + $this->backend->createCard($bookId, $uri1, ''); + $uri2 = $this->getUniqueID('card'); + $this->backend->createCard($bookId, $uri2, ''); + + // get all the cards + $cards = $this->backend->getCards($bookId); + $this->assertEquals(3, count($cards)); + $this->assertEquals('', $cards[0]['carddata']); + $this->assertEquals('', $cards[1]['carddata']); + $this->assertEquals('', $cards[2]['carddata']); + + // get the cards + $cards = $this->backend->getMultipleCards($bookId, [$uri1, $uri2]); + $this->assertEquals(2, count($cards)); + foreach($cards as $card) { + $this->assertArrayHasKey('id', $card); + $this->assertArrayHasKey('uri', $card); + $this->assertArrayHasKey('lastmodified', $card); + $this->assertArrayHasKey('etag', $card); + $this->assertArrayHasKey('size', $card); + $this->assertEquals('', $card['carddata']); + } + + // delete the card + $this->backend->deleteCard($bookId, $uri0); + $this->backend->deleteCard($bookId, $uri1); + $this->backend->deleteCard($bookId, $uri2); + $cards = $this->backend->getCards($bookId); + $this->assertEquals(0, count($cards)); + } + + public function testDeleteWithoutCard() { + + $this->backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') + ->setConstructorArgs([$this->db, $this->principal, null]) + ->setMethods([ + 'getCardId', + 'addChange', + 'purgeProperties', + 'updateProperties', + ]) + ->getMock(); + + // create a new address book + $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + + $bookId = $books[0]['id']; + $uri = $this->getUniqueID('card'); + + // create a new address book + $this->backend->expects($this->once()) + ->method('getCardId') + ->with($bookId, $uri) + ->willThrowException(new \InvalidArgumentException()); + $this->backend->expects($this->exactly(2)) + ->method('addChange') + ->withConsecutive( + [$bookId, $uri, 1], + [$bookId, $uri, 3] + ); + $this->backend->expects($this->never()) + ->method('purgeProperties'); + + // create a card + $this->backend->createCard($bookId, $uri, ''); + + // delete the card + $this->assertTrue($this->backend->deleteCard($bookId, $uri)); + } + + public function testSyncSupport() { + + $this->backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') + ->setConstructorArgs([$this->db, $this->principal, null]) + ->setMethods(['updateProperties'])->getMock(); + + // create a new address book + $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + $bookId = $books[0]['id']; + + // fist call without synctoken + $changes = $this->backend->getChangesForAddressBook($bookId, '', 1); + $syncToken = $changes['syncToken']; + + // add a change + $uri0 = $this->getUniqueID('card'); + $this->backend->createCard($bookId, $uri0, ''); + + // look for changes + $changes = $this->backend->getChangesForAddressBook($bookId, $syncToken, 1); + $this->assertEquals($uri0, $changes['added'][0]); + } + + public function testSharing() { + $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertEquals(1, count($books)); + + $exampleBook = new AddressBook($this->backend, $books[0]); + $this->backend->updateShares($exampleBook, [['href' => 'principal:principals/best-friend']], []); + + $shares = $this->backend->getShares($exampleBook->getResourceId()); + $this->assertEquals(1, count($shares)); + + // adding the same sharee again has no effect + $this->backend->updateShares($exampleBook, [['href' => 'principal:principals/best-friend']], []); + + $shares = $this->backend->getShares($exampleBook->getResourceId()); + $this->assertEquals(1, count($shares)); + + $books = $this->backend->getAddressBooksForUser('principals/best-friend'); + $this->assertEquals(1, count($books)); + + $this->backend->updateShares($exampleBook, [], ['principal:principals/best-friend']); + + $shares = $this->backend->getShares($exampleBook->getResourceId()); + $this->assertEquals(0, count($shares)); + + $books = $this->backend->getAddressBooksForUser('principals/best-friend'); + $this->assertEquals(0, count($books)); + } + + public function testUpdateProperties() { + + $bookId = 42; + $cardUri = 'card-uri'; + $cardId = 2; + + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') + ->setConstructorArgs([$this->db, $this->principal, null]) + ->setMethods(['getCardId'])->getMock(); + + $backend->expects($this->any())->method('getCardId')->willReturn($cardId); + + // add properties for new vCard + $vCard = new VCard(); + $vCard->add(new Text($vCard, 'UID', $cardUri)); + $vCard->add(new Text($vCard, 'FN', 'John Doe')); + $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]); + + $query = $this->db->getQueryBuilder(); + $result = $query->select('*')->from('cards_properties')->execute()->fetchAll(); + + $this->assertSame(2, count($result)); + + $this->assertSame('UID', $result[0]['name']); + $this->assertSame($cardUri, $result[0]['value']); + $this->assertSame($bookId, (int)$result[0]['addressbookid']); + $this->assertSame($cardId, (int)$result[0]['cardid']); + + $this->assertSame('FN', $result[1]['name']); + $this->assertSame('John Doe', $result[1]['value']); + $this->assertSame($bookId, (int)$result[1]['addressbookid']); + $this->assertSame($cardId, (int)$result[1]['cardid']); + + // update properties for existing vCard + $vCard = new VCard(); + $vCard->add(new Text($vCard, 'FN', 'John Doe')); + $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]); + + $query = $this->db->getQueryBuilder(); + $result = $query->select('*')->from('cards_properties')->execute()->fetchAll(); + + $this->assertSame(1, count($result)); + + $this->assertSame('FN', $result[0]['name']); + $this->assertSame('John Doe', $result[0]['value']); + $this->assertSame($bookId, (int)$result[0]['addressbookid']); + $this->assertSame($cardId, (int)$result[0]['cardid']); + } + + public function testPurgeProperties() { + + $query = $this->db->getQueryBuilder(); + $query->insert('cards_properties') + ->values( + [ + 'addressbookid' => $query->createNamedParameter(1), + 'cardid' => $query->createNamedParameter(1), + 'name' => $query->createNamedParameter('name1'), + 'value' => $query->createNamedParameter('value1'), + 'preferred' => $query->createNamedParameter(0) + ] + ); + $query->execute(); + + $query = $this->db->getQueryBuilder(); + $query->insert('cards_properties') + ->values( + [ + 'addressbookid' => $query->createNamedParameter(1), + 'cardid' => $query->createNamedParameter(2), + 'name' => $query->createNamedParameter('name2'), + 'value' => $query->createNamedParameter('value2'), + 'preferred' => $query->createNamedParameter(0) + ] + ); + $query->execute(); + + $this->invokePrivate($this->backend, 'purgeProperties', [1, 1]); + + $query = $this->db->getQueryBuilder(); + $result = $query->select('*')->from('cards_properties')->execute()->fetchAll(); + $this->assertSame(1, count($result)); + $this->assertSame(1 ,(int)$result[0]['addressbookid']); + $this->assertSame(2 ,(int)$result[0]['cardid']); + + } + + public function testGetCardId() { + $query = $this->db->getQueryBuilder(); + + $query->insert('cards') + ->values( + [ + 'addressbookid' => $query->createNamedParameter(1), + 'carddata' => $query->createNamedParameter(''), + 'uri' => $query->createNamedParameter('uri'), + 'lastmodified' => $query->createNamedParameter(4738743), + 'etag' => $query->createNamedParameter('etag'), + 'size' => $query->createNamedParameter(120) + ] + ); + $query->execute(); + $id = $query->getLastInsertId(); + + $this->assertSame($id, + $this->invokePrivate($this->backend, 'getCardId', [1, 'uri'])); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testGetCardIdFailed() { + $this->invokePrivate($this->backend, 'getCardId', [1, 'uri']); + } + + /** + * @dataProvider dataTestSearch + * + * @param string $pattern + * @param array $properties + * @param array $expected + */ + public function testSearch($pattern, $properties, $expected) { + /** @var VCard $vCards */ + $vCards = []; + $vCards[0] = new VCard(); + $vCards[0]->add(new Text($vCards[0], 'UID', 'uid')); + $vCards[0]->add(new Text($vCards[0], 'FN', 'John Doe')); + $vCards[0]->add(new Text($vCards[0], 'CLOUD', 'john@owncloud.org')); + $vCards[1] = new VCard(); + $vCards[1]->add(new Text($vCards[1], 'UID', 'uid')); + $vCards[1]->add(new Text($vCards[1], 'FN', 'John M. Doe')); + + $vCardIds = []; + $query = $this->db->getQueryBuilder(); + for($i=0; $i<2; $i++) { + $query->insert($this->dbCardsTable) + ->values( + [ + 'addressbookid' => $query->createNamedParameter(0), + 'carddata' => $query->createNamedParameter($vCards[$i]->serialize(), IQueryBuilder::PARAM_LOB), + 'uri' => $query->createNamedParameter('uri' . $i), + 'lastmodified' => $query->createNamedParameter(time()), + 'etag' => $query->createNamedParameter('etag' . $i), + 'size' => $query->createNamedParameter(120), + ] + ); + $query->execute(); + $vCardIds[] = $query->getLastInsertId(); + } + + $query->insert($this->dbCardsPropertiesTable) + ->values( + [ + 'addressbookid' => $query->createNamedParameter(0), + 'cardid' => $query->createNamedParameter($vCardIds[0]), + 'name' => $query->createNamedParameter('FN'), + 'value' => $query->createNamedParameter('John Doe'), + 'preferred' => $query->createNamedParameter(0) + ] + ); + $query->execute(); + $query->insert($this->dbCardsPropertiesTable) + ->values( + [ + 'addressbookid' => $query->createNamedParameter(0), + 'cardid' => $query->createNamedParameter($vCardIds[0]), + 'name' => $query->createNamedParameter('CLOUD'), + 'value' => $query->createNamedParameter('John@owncloud.org'), + 'preferred' => $query->createNamedParameter(0) + ] + ); + $query->execute(); + $query->insert($this->dbCardsPropertiesTable) + ->values( + [ + 'addressbookid' => $query->createNamedParameter(0), + 'cardid' => $query->createNamedParameter($vCardIds[1]), + 'name' => $query->createNamedParameter('FN'), + 'value' => $query->createNamedParameter('John M. Doe'), + 'preferred' => $query->createNamedParameter(0) + ] + ); + $query->execute(); + + $result = $this->backend->search(0, $pattern, $properties); + + // check result + $this->assertSame(count($expected), count($result)); + $found = []; + foreach ($result as $r) { + foreach ($expected as $exp) { + if (strpos($r, $exp) > 0) { + $found[$exp] = true; + break; + } + } + } + + $this->assertSame(count($expected), count($found)); + } + + public function dataTestSearch() { + return [ + ['John', ['FN'], ['John Doe', 'John M. Doe']], + ['M. Doe', ['FN'], ['John M. Doe']], + ['Do', ['FN'], ['John Doe', 'John M. Doe']], + 'check if duplicates are handled correctly' => ['John', ['FN', 'CLOUD'], ['John Doe', 'John M. Doe']], + 'case insensitive' => ['john', ['FN'], ['John Doe', 'John M. Doe']] + ]; + } + + public function testGetCardUri() { + $query = $this->db->getQueryBuilder(); + $query->insert($this->dbCardsTable) + ->values( + [ + 'addressbookid' => $query->createNamedParameter(1), + 'carddata' => $query->createNamedParameter('carddata', IQueryBuilder::PARAM_LOB), + 'uri' => $query->createNamedParameter('uri'), + 'lastmodified' => $query->createNamedParameter(5489543), + 'etag' => $query->createNamedParameter('etag'), + 'size' => $query->createNamedParameter(120), + ] + ); + $query->execute(); + + $id = $query->getLastInsertId(); + + $this->assertSame('uri', $this->backend->getCardUri($id)); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testGetCardUriFailed() { + $this->backend->getCardUri(1); + } + + public function testGetContact() { + $query = $this->db->getQueryBuilder(); + for($i=0; $i<2; $i++) { + $query->insert($this->dbCardsTable) + ->values( + [ + 'addressbookid' => $query->createNamedParameter($i), + 'carddata' => $query->createNamedParameter('carddata' . $i, IQueryBuilder::PARAM_LOB), + 'uri' => $query->createNamedParameter('uri' . $i), + 'lastmodified' => $query->createNamedParameter(5489543), + 'etag' => $query->createNamedParameter('etag' . $i), + 'size' => $query->createNamedParameter(120), + ] + ); + $query->execute(); + } + + $result = $this->backend->getContact(0, 'uri0'); + $this->assertSame(7, count($result)); + $this->assertSame(0, (int)$result['addressbookid']); + $this->assertSame('uri0', $result['uri']); + $this->assertSame(5489543, (int)$result['lastmodified']); + $this->assertSame('etag0', $result['etag']); + $this->assertSame(120, (int)$result['size']); + } + + public function testGetContactFail() { + $this->assertEmpty($this->backend->getContact(0, 'uri')); + } + + public function testCollectCardProperties() { + $query = $this->db->getQueryBuilder(); + $query->insert($this->dbCardsPropertiesTable) + ->values( + [ + 'addressbookid' => $query->createNamedParameter(666), + 'cardid' => $query->createNamedParameter(777), + 'name' => $query->createNamedParameter('FN'), + 'value' => $query->createNamedParameter('John Doe'), + 'preferred' => $query->createNamedParameter(0) + ] + ) + ->execute(); + + $result = $this->backend->collectCardProperties(666, 'FN'); + $this->assertEquals(['John Doe'], $result); + } +} diff --git a/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php b/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php new file mode 100644 index 00000000000..775dc5d18a5 --- /dev/null +++ b/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php @@ -0,0 +1,43 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CardDAV; + +use OCA\DAV\CardDAV\CardDavBackend; +use OCA\DAV\CardDAV\ContactsManager; +use OCP\Contacts\IManager; +use Test\TestCase; + +class ContactsManagerTest extends TestCase { + public function test() { + /** @var IManager | \PHPUnit_Framework_MockObject_MockObject $cm */ + $cm = $this->getMockBuilder('OCP\Contacts\IManager')->disableOriginalConstructor()->getMock(); + $cm->expects($this->exactly(2))->method('registerAddressBook'); + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backEnd */ + $backEnd = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); + $backEnd->method('getAddressBooksForUser')->willReturn([ + [] + ]); + + $app = new ContactsManager($backEnd); + $app->setupContactsProvider($cm, 'user01'); + } +} diff --git a/apps/dav/tests/unit/CardDAV/ConverterTest.php b/apps/dav/tests/unit/CardDAV/ConverterTest.php new file mode 100644 index 00000000000..4b71d43cc43 --- /dev/null +++ b/apps/dav/tests/unit/CardDAV/ConverterTest.php @@ -0,0 +1,137 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CardDAV; + +use OCA\DAV\CardDAV\Converter; +use Test\TestCase; + +class ConverterTest extends TestCase { + + /** + * @dataProvider providesNewUsers + */ + public function testCreation($expectedVCard, $displayName = null, $eMailAddress = null, $cloudId = null) { + $user = $this->getUserMock($displayName, $eMailAddress, $cloudId); + + $converter = new Converter(); + $vCard = $converter->createCardFromUser($user); + $cardData = $vCard->serialize(); + + $this->assertEquals($expectedVCard, $cardData); + } + + public function providesNewUsers() { + return [ + ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nPHOTO;ENCODING=b;TYPE=JPEG:MTIzNDU2Nzg5\r\nEND:VCARD\r\n"], + ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:Dr. Foo Bar\r\nN:Bar;Dr.;Foo;;\r\nPHOTO;ENCODING=b;TYPE=JPEG:MTIzNDU2Nzg5\r\nEND:VCARD\r\n", "Dr. Foo Bar"], + ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:Dr. Foo Bar\r\nN:Bar;Dr.;Foo;;\r\nEMAIL;TYPE=OTHER:foo@bar.net\r\nPHOTO;ENCODING=b;TYPE=JPEG:MTIzNDU2Nzg5\r\nEND:VCARD\r\n", "Dr. Foo Bar", "foo@bar.net"], + ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:Dr. Foo Bar\r\nN:Bar;Dr.;Foo;;\r\nCLOUD:foo@bar.net\r\nPHOTO;ENCODING=b;TYPE=JPEG:MTIzNDU2Nzg5\r\nEND:VCARD\r\n", "Dr. Foo Bar", null, "foo@bar.net"], + ]; + } + + /** + * @dataProvider providesNewUsers + */ + public function testUpdateOfUnchangedUser($expectedVCard, $displayName = null, $eMailAddress = null, $cloudId = null) { + $user = $this->getUserMock($displayName, $eMailAddress, $cloudId); + + $converter = new Converter(); + $vCard = $converter->createCardFromUser($user); + $updated = $converter->updateCard($vCard, $user); + $this->assertFalse($updated); + $cardData = $vCard->serialize(); + + $this->assertEquals($expectedVCard, $cardData); + } + + /** + * @dataProvider providesUsersForUpdateOfRemovedElement + */ + public function testUpdateOfRemovedElement($expectedVCard, $displayName = null, $eMailAddress = null, $cloudId = null) { + $user = $this->getUserMock($displayName, $eMailAddress, $cloudId); + + $converter = new Converter(); + $vCard = $converter->createCardFromUser($user); + + $user1 = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); + $user1->method('getUID')->willReturn('12345'); + $user1->method('getDisplayName')->willReturn(null); + $user1->method('getEMailAddress')->willReturn(null); + $user1->method('getCloudId')->willReturn(null); + $user1->method('getAvatarImage')->willReturn(null); + + $updated = $converter->updateCard($vCard, $user1); + $this->assertTrue($updated); + $cardData = $vCard->serialize(); + + $this->assertEquals($expectedVCard, $cardData); + } + + public function providesUsersForUpdateOfRemovedElement() { + return [ + ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nEND:VCARD\r\n", "Dr. Foo Bar"], + ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nEND:VCARD\r\n", "Dr. Foo Bar", "foo@bar.net"], + ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nEND:VCARD\r\n", "Dr. Foo Bar", null, "foo@bar.net"], + ]; + } + + /** + * @dataProvider providesNames + * @param $expected + * @param $fullName + */ + public function testNameSplitter($expected, $fullName) { + + $converter = new Converter(); + $r = $converter->splitFullName($fullName); + $r = implode(';', $r); + $this->assertEquals($expected, $r); + } + + public function providesNames() { + return [ + ['Sauron;;;;', 'Sauron'], + ['Baggins;Bilbo;;;', 'Bilbo Baggins'], + ['Tolkien;John;Ronald Reuel;;', 'John Ronald Reuel Tolkien'], + ]; + } + + /** + * @param $displayName + * @param $eMailAddress + * @param $cloudId + * @return \PHPUnit_Framework_MockObject_MockObject + */ + protected function getUserMock($displayName, $eMailAddress, $cloudId) { + $image0 = $this->getMockBuilder('OCP\IImage')->disableOriginalConstructor()->getMock(); + $image0->method('mimeType')->willReturn('JPEG'); + $image0->method('data')->willReturn('123456789'); + $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); + $user->method('getUID')->willReturn('12345'); + $user->method('getDisplayName')->willReturn($displayName); + $user->method('getEMailAddress')->willReturn($eMailAddress); + $user->method('getCloudId')->willReturn($cloudId); + $user->method('getAvatarImage')->willReturn($image0); + return $user; + } +} diff --git a/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php b/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php new file mode 100644 index 00000000000..1cbececdb33 --- /dev/null +++ b/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php @@ -0,0 +1,81 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CardDAV\Sharing; + + +use OCA\DAV\DAV\Sharing\IShareable; +use OCA\DAV\DAV\Sharing\Plugin; +use OCA\DAV\Connector\Sabre\Auth; +use OCP\IRequest; +use Sabre\DAV\Server; +use Sabre\DAV\SimpleCollection; +use Sabre\HTTP\Request; +use Sabre\HTTP\Response; +use Test\TestCase; + +class PluginTest extends TestCase { + + /** @var Plugin */ + private $plugin; + /** @var Server */ + private $server; + /** @var IShareable | \PHPUnit_Framework_MockObject_MockObject */ + private $book; + + public function setUp() { + parent::setUp(); + + /** @var Auth | \PHPUnit_Framework_MockObject_MockObject $authBackend */ + $authBackend = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Auth')->disableOriginalConstructor()->getMock(); + $authBackend->method('isDavAuthenticated')->willReturn(true); + + /** @var IRequest $request */ + $request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); + $this->plugin = new Plugin($authBackend, $request); + + $root = new SimpleCollection('root'); + $this->server = new \Sabre\DAV\Server($root); + /** @var SimpleCollection $node */ + $this->book = $this->getMockBuilder('OCA\DAV\DAV\Sharing\IShareable')->disableOriginalConstructor()->getMock(); + $this->book->method('getName')->willReturn('addressbook1.vcf'); + $root->addChild($this->book); + $this->plugin->initialize($this->server); + } + + public function testSharing() { + + $this->book->expects($this->once())->method('updateShares')->with([[ + 'href' => 'principal:principals/admin', + 'commonName' => null, + 'summary' => null, + 'readOnly' => false + ]], ['mailto:wilfredo@example.com']); + + // setup request + $request = new Request(); + $request->addHeader('Content-Type', 'application/xml'); + $request->setUrl('addressbook1.vcf'); + $request->setBody('principal:principals/admin mailto:wilfredo@example.com'); + $response = new Response(); + $this->plugin->httpPost($request, $response); + } +} diff --git a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php new file mode 100644 index 00000000000..e5a2603c77a --- /dev/null +++ b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php @@ -0,0 +1,145 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\CardDAV; + +use OCA\DAV\CardDAV\CardDavBackend; +use OCA\DAV\CardDAV\SyncService; +use OCP\IUser; +use OCP\IUserManager; +use Test\TestCase; + +class SyncServiceTest extends TestCase { + public function testEmptySync() { + $backend = $this->getBackendMock(0, 0, 0); + + $ss = $this->getSyncServiceMock($backend, []); + $return = $ss->syncRemoteAddressBook('', 'system', '1234567890', null, '1', 'principals/system/system', []); + $this->assertEquals('sync-token-1', $return); + } + + public function testSyncWithNewElement() { + $backend = $this->getBackendMock(1, 0, 0); + $backend->method('getCard')->willReturn(false); + + $ss = $this->getSyncServiceMock($backend, ['0' => [200 => '']]); + $return = $ss->syncRemoteAddressBook('', 'system', '1234567890', null, '1', 'principals/system/system', []); + $this->assertEquals('sync-token-1', $return); + } + + public function testSyncWithUpdatedElement() { + $backend = $this->getBackendMock(0, 1, 0); + $backend->method('getCard')->willReturn(true); + + $ss = $this->getSyncServiceMock($backend, ['0' => [200 => '']]); + $return = $ss->syncRemoteAddressBook('', 'system', '1234567890', null, '1', 'principals/system/system', []); + $this->assertEquals('sync-token-1', $return); + } + + public function testSyncWithDeletedElement() { + $backend = $this->getBackendMock(0, 0, 1); + + $ss = $this->getSyncServiceMock($backend, ['0' => [404 => '']]); + $return = $ss->syncRemoteAddressBook('', 'system', '1234567890', null, '1', 'principals/system/system', []); + $this->assertEquals('sync-token-1', $return); + } + + public function testEnsureSystemAddressBookExists() { + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDAVBackend')->disableOriginalConstructor()->getMock(); + $backend->expects($this->exactly(1))->method('createAddressBook'); + $backend->expects($this->at(0))->method('getAddressBooksByUri')->willReturn(null); + $backend->expects($this->at(1))->method('getAddressBooksByUri')->willReturn([]); + + /** @var IUserManager $userManager */ + $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); + $ss = new SyncService($backend, $userManager, $logger); + $book = $ss->ensureSystemAddressBookExists('principals/users/adam', 'contacts', []); + } + + public function testUpdateAndDeleteUser() { + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backend */ + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDAVBackend')->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); + + $backend->expects($this->once())->method('createCard'); + $backend->expects($this->once())->method('updateCard'); + $backend->expects($this->once())->method('deleteCard'); + + $backend->method('getCard')->willReturnOnConsecutiveCalls(false, [ + 'carddata' => "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.4.8//EN\r\nUID:test-user\r\nFN:test-user\r\nN:test-user;;;;\r\nEND:VCARD\r\n\r\n" + ]); + + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ + $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); + + /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ + $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); + $user->method('getBackendClassName')->willReturn('unittest'); + $user->method('getUID')->willReturn('test-user'); + + $ss = new SyncService($backend, $userManager, $logger); + $ss->updateUser($user); + + $user->method('getDisplayName')->willReturn('A test user for unit testing'); + + $ss->updateUser($user); + + $ss->deleteUser($user); + } + + /** + * @param int $createCount + * @param int $updateCount + * @param int $deleteCount + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function getBackendMock($createCount, $updateCount, $deleteCount) { + $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDAVBackend')->disableOriginalConstructor()->getMock(); + $backend->expects($this->exactly($createCount))->method('createCard'); + $backend->expects($this->exactly($updateCount))->method('updateCard'); + $backend->expects($this->exactly($deleteCount))->method('deleteCard'); + return $backend; + } + + /** + * @param $backend + * @param $response + * @return SyncService|\PHPUnit_Framework_MockObject_MockObject + */ + private function getSyncServiceMock($backend, $response) { + $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); + /** @var SyncService | \PHPUnit_Framework_MockObject_MockObject $ss */ + $ss = $this->getMock('OCA\DAV\CardDAV\SyncService', ['ensureSystemAddressBookExists', 'requestSyncReport', 'download'], [$backend, $userManager, $logger]); + $ss->method('requestSyncReport')->withAnyParameters()->willReturn(['response' => $response, 'token' => 'sync-token-1']); + $ss->method('ensureSystemAddressBookExists')->willReturn(['id' => 1]); + $ss->method('download')->willReturn([ + 'body' => '', + 'statusCode' => 200, + 'headers' => [] + ]); + return $ss; + } + +} diff --git a/apps/dav/tests/unit/Comments/CommentsNodeTest.php b/apps/dav/tests/unit/Comments/CommentsNodeTest.php new file mode 100644 index 00000000000..d812ad62cb1 --- /dev/null +++ b/apps/dav/tests/unit/Comments/CommentsNodeTest.php @@ -0,0 +1,459 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Comments; + +use OCA\DAV\Comments\CommentNode; +use OCP\Comments\IComment; +use OCP\Comments\MessageTooLongException; + +class CommentsNodeTest extends \Test\TestCase { + + protected $commentsManager; + protected $comment; + protected $node; + protected $userManager; + protected $logger; + protected $userSession; + + public function setUp() { + parent::setUp(); + + $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); + $this->comment = $this->getMock('\OCP\Comments\IComment'); + $this->userManager = $this->getMock('\OCP\IUserManager'); + $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->logger = $this->getMock('\OCP\ILogger'); + + $this->node = new CommentNode( + $this->commentsManager, + $this->comment, + $this->userManager, + $this->userSession, + $this->logger + ); + } + + public function testDelete() { + $user = $this->getMock('\OCP\IUser'); + + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('alice')); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->comment->expects($this->once()) + ->method('getId') + ->will($this->returnValue('19')); + + $this->comment->expects($this->any()) + ->method('getActorType') + ->will($this->returnValue('users')); + + $this->comment->expects($this->any()) + ->method('getActorId') + ->will($this->returnValue('alice')); + + $this->commentsManager->expects($this->once()) + ->method('delete') + ->with('19'); + + $this->node->delete(); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDeleteForbidden() { + $user = $this->getMock('\OCP\IUser'); + + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('mallory')); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->comment->expects($this->never()) + ->method('getId'); + + $this->comment->expects($this->any()) + ->method('getActorType') + ->will($this->returnValue('users')); + + $this->comment->expects($this->any()) + ->method('getActorId') + ->will($this->returnValue('alice')); + + $this->commentsManager->expects($this->never()) + ->method('delete'); + + $this->node->delete(); + } + + public function testGetName() { + $id = '19'; + $this->comment->expects($this->once()) + ->method('getId') + ->will($this->returnValue($id)); + + $this->assertSame($this->node->getName(), $id); + } + + /** + * @expectedException \Sabre\DAV\Exception\MethodNotAllowed + */ + public function testSetName() { + $this->node->setName('666'); + } + + public function testGetLastModified() { + $this->assertSame($this->node->getLastModified(), null); + } + + public function testUpdateComment() { + $msg = 'Hello Earth'; + + $user = $this->getMock('\OCP\IUser'); + + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('alice')); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->comment->expects($this->once()) + ->method('setMessage') + ->with($msg); + + $this->comment->expects($this->any()) + ->method('getActorType') + ->will($this->returnValue('users')); + + $this->comment->expects($this->any()) + ->method('getActorId') + ->will($this->returnValue('alice')); + + $this->commentsManager->expects($this->once()) + ->method('save') + ->with($this->comment); + + $this->assertTrue($this->node->updateComment($msg)); + } + + public function testUpdateCommentLogException() { + $msg = null; + + $user = $this->getMock('\OCP\IUser'); + + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('alice')); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->comment->expects($this->once()) + ->method('setMessage') + ->with($msg) + ->will($this->throwException(new \Exception('buh!'))); + + $this->comment->expects($this->any()) + ->method('getActorType') + ->will($this->returnValue('users')); + + $this->comment->expects($this->any()) + ->method('getActorId') + ->will($this->returnValue('alice')); + + $this->commentsManager->expects($this->never()) + ->method('save'); + + $this->logger->expects($this->once()) + ->method('logException'); + + $this->assertFalse($this->node->updateComment($msg)); + } + + /** + * @expectedException \Sabre\DAV\Exception\BadRequest + * @expectedExceptionMessage Message exceeds allowed character limit of + */ + public function testUpdateCommentMessageTooLongException() { + $user = $this->getMock('\OCP\IUser'); + + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('alice')); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->comment->expects($this->once()) + ->method('setMessage') + ->will($this->throwException(new MessageTooLongException())); + + $this->comment->expects($this->any()) + ->method('getActorType') + ->will($this->returnValue('users')); + + $this->comment->expects($this->any()) + ->method('getActorId') + ->will($this->returnValue('alice')); + + $this->commentsManager->expects($this->never()) + ->method('save'); + + $this->logger->expects($this->once()) + ->method('logException'); + + // imagine 'foo' has >1k characters. comment is mocked anyway. + $this->node->updateComment('foo'); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testUpdateForbiddenByUser() { + $msg = 'HaXX0r'; + + $user = $this->getMock('\OCP\IUser'); + + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('mallory')); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->comment->expects($this->never()) + ->method('setMessage'); + + $this->comment->expects($this->any()) + ->method('getActorType') + ->will($this->returnValue('users')); + + $this->comment->expects($this->any()) + ->method('getActorId') + ->will($this->returnValue('alice')); + + $this->commentsManager->expects($this->never()) + ->method('save'); + + $this->node->updateComment($msg); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testUpdateForbiddenByType() { + $msg = 'HaXX0r'; + + $user = $this->getMock('\OCP\IUser'); + + $user->expects($this->never()) + ->method('getUID'); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->comment->expects($this->never()) + ->method('setMessage'); + + $this->comment->expects($this->any()) + ->method('getActorType') + ->will($this->returnValue('bots')); + + $this->commentsManager->expects($this->never()) + ->method('save'); + + $this->node->updateComment($msg); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testUpdateForbiddenByNotLoggedIn() { + $msg = 'HaXX0r'; + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue(null)); + + $this->comment->expects($this->never()) + ->method('setMessage'); + + $this->comment->expects($this->any()) + ->method('getActorType') + ->will($this->returnValue('users')); + + $this->commentsManager->expects($this->never()) + ->method('save'); + + $this->node->updateComment($msg); + } + + public function testPropPatch() { + $propPatch = $this->getMockBuilder('Sabre\DAV\PropPatch') + ->disableOriginalConstructor() + ->getMock(); + + $propPatch->expects($this->once()) + ->method('handle') + ->with('{http://owncloud.org/ns}message'); + + $this->node->propPatch($propPatch); + } + + public function testGetProperties() { + $ns = '{http://owncloud.org/ns}'; + $expected = [ + $ns . 'id' => '123', + $ns . 'parentId' => '12', + $ns . 'topmostParentId' => '2', + $ns . 'childrenCount' => 3, + $ns . 'message' => 'such a nice file you have…', + $ns . 'verb' => 'comment', + $ns . 'actorType' => 'users', + $ns . 'actorId' => 'alice', + $ns . 'actorDisplayName' => 'Alice of Wonderland', + $ns . 'creationDateTime' => new \DateTime('2016-01-10 18:48:00'), + $ns . 'latestChildDateTime' => new \DateTime('2016-01-12 18:48:00'), + $ns . 'objectType' => 'files', + $ns . 'objectId' => '1848', + $ns . 'isUnread' => null, + ]; + + $this->comment->expects($this->once()) + ->method('getId') + ->will($this->returnValue($expected[$ns . 'id'])); + + $this->comment->expects($this->once()) + ->method('getParentId') + ->will($this->returnValue($expected[$ns . 'parentId'])); + + $this->comment->expects($this->once()) + ->method('getTopmostParentId') + ->will($this->returnValue($expected[$ns . 'topmostParentId'])); + + $this->comment->expects($this->once()) + ->method('getChildrenCount') + ->will($this->returnValue($expected[$ns . 'childrenCount'])); + + $this->comment->expects($this->once()) + ->method('getMessage') + ->will($this->returnValue($expected[$ns . 'message'])); + + $this->comment->expects($this->once()) + ->method('getVerb') + ->will($this->returnValue($expected[$ns . 'verb'])); + + $this->comment->expects($this->exactly(2)) + ->method('getActorType') + ->will($this->returnValue($expected[$ns . 'actorType'])); + + $this->comment->expects($this->exactly(2)) + ->method('getActorId') + ->will($this->returnValue($expected[$ns . 'actorId'])); + + $this->comment->expects($this->once()) + ->method('getCreationDateTime') + ->will($this->returnValue($expected[$ns . 'creationDateTime'])); + + $this->comment->expects($this->once()) + ->method('getLatestChildDateTime') + ->will($this->returnValue($expected[$ns . 'latestChildDateTime'])); + + $this->comment->expects($this->once()) + ->method('getObjectType') + ->will($this->returnValue($expected[$ns . 'objectType'])); + + $this->comment->expects($this->once()) + ->method('getObjectId') + ->will($this->returnValue($expected[$ns . 'objectId'])); + + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->once()) + ->method('getDisplayName') + ->will($this->returnValue($expected[$ns . 'actorDisplayName'])); + + $this->userManager->expects($this->once()) + ->method('get') + ->with('alice') + ->will($this->returnValue($user)); + + $properties = $this->node->getProperties(null); + + foreach($properties as $name => $value) { + $this->assertTrue(array_key_exists($name, $expected)); + $this->assertSame($expected[$name], $value); + unset($expected[$name]); + } + $this->assertTrue(empty($expected)); + } + + public function readCommentProvider() { + $creationDT = new \DateTime('2016-01-19 18:48:00'); + $diff = new \DateInterval('PT2H'); + $readDT1 = clone $creationDT; $readDT1->sub($diff); + $readDT2 = clone $creationDT; $readDT2->add($diff); + return [ + [$creationDT, $readDT1, 'true'], + [$creationDT, $readDT2, 'false'], + [$creationDT, null, 'true'], + ]; + } + + /** + * @dataProvider readCommentProvider + * @param $expected + */ + public function testGetPropertiesUnreadProperty($creationDT, $readDT, $expected) { + $this->comment->expects($this->any()) + ->method('getCreationDateTime') + ->will($this->returnValue($creationDT)); + + $this->commentsManager->expects($this->once()) + ->method('getReadMark') + ->will($this->returnValue($readDT)); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($this->getMock('\OCP\IUser'))); + + $properties = $this->node->getProperties(null); + + $this->assertTrue(array_key_exists(CommentNode::PROPERTY_NAME_UNREAD, $properties)); + $this->assertSame($properties[CommentNode::PROPERTY_NAME_UNREAD], $expected); + } +} diff --git a/apps/dav/tests/unit/Comments/CommentsPluginTest.php b/apps/dav/tests/unit/Comments/CommentsPluginTest.php new file mode 100644 index 00000000000..608717bd0af --- /dev/null +++ b/apps/dav/tests/unit/Comments/CommentsPluginTest.php @@ -0,0 +1,742 @@ + + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Comments; + +use OC\Comments\Comment; +use OCA\DAV\Comments\CommentsPlugin as CommentsPluginImplementation; +use OCP\Comments\IComment; +use Sabre\DAV\Exception\NotFound; + +class CommentsPluginTest extends \Test\TestCase { + /** @var \Sabre\DAV\Server */ + private $server; + + /** @var \Sabre\DAV\Tree */ + private $tree; + + /** @var \OCP\Comments\ICommentsManager */ + private $commentsManager; + + /** @var \OCP\IUserSession */ + private $userSession; + + /** @var CommentsPluginImplementation */ + private $plugin; + + public function setUp() { + parent::setUp(); + $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + ->disableOriginalConstructor() + ->getMock(); + + $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + ->setConstructorArgs([$this->tree]) + ->setMethods(['getRequestUri']) + ->getMock(); + + $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); + $this->userSession = $this->getMock('\OCP\IUserSession'); + + $this->plugin = new CommentsPluginImplementation($this->commentsManager, $this->userSession); + } + + public function testCreateComment() { + $commentData = [ + 'actorType' => 'users', + 'verb' => 'comment', + 'message' => 'my first comment', + ]; + + $comment = new Comment([ + 'objectType' => 'files', + 'objectId' => '42', + 'actorType' => 'users', + 'actorId' => 'alice' + ] + $commentData); + $comment->setId('23'); + + $path = 'comments/files/42'; + + $requestData = json_encode($commentData); + + $user = $this->getMock('OCP\IUser'); + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('alice')); + + $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->once()) + ->method('getName') + ->will($this->returnValue('files')); + $node->expects($this->once()) + ->method('getId') + ->will($this->returnValue('42')); + + $node->expects($this->once()) + ->method('setReadMarker') + ->with(null); + + $this->commentsManager->expects($this->once()) + ->method('create') + ->with('users', 'alice', 'files', '42') + ->will($this->returnValue($comment)); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + // technically, this is a shortcut. Inbetween EntityTypeCollection would + // be returned, but doing it exactly right would not be really + // unit-testing like, as it would require to haul in a lot of other + // things. + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/' . $path)); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $request->expects($this->once()) + ->method('getUrl') + ->will($this->returnValue('http://example.com/dav/' . $path)); + + $response->expects($this->once()) + ->method('setHeader') + ->with('Content-Location', 'http://example.com/dav/' . $path . '/23'); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->httpPost($request, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotFound + */ + public function testCreateCommentInvalidObject() { + $commentData = [ + 'actorType' => 'users', + 'verb' => 'comment', + 'message' => 'my first comment', + ]; + + $comment = new Comment([ + 'objectType' => 'files', + 'objectId' => '666', + 'actorType' => 'users', + 'actorId' => 'alice' + ] + $commentData); + $comment->setId('23'); + + $path = 'comments/files/666'; + + $user = $this->getMock('OCP\IUser'); + $user->expects($this->never()) + ->method('getUID'); + + $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->never()) + ->method('getName'); + $node->expects($this->never()) + ->method('getId'); + + $this->commentsManager->expects($this->never()) + ->method('create'); + + $this->userSession->expects($this->never()) + ->method('getUser'); + + // technically, this is a shortcut. Inbetween EntityTypeCollection would + // be returned, but doing it exactly right would not be really + // unit-testing like, as it would require to haul in a lot of other + // things. + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/' . $path)); + + $request->expects($this->never()) + ->method('getBodyAsString'); + + $request->expects($this->never()) + ->method('getHeader') + ->with('Content-Type'); + + $request->expects($this->never()) + ->method('getUrl'); + + $response->expects($this->never()) + ->method('setHeader'); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->httpPost($request, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\BadRequest + */ + public function testCreateCommentInvalidActor() { + $commentData = [ + 'actorType' => 'robots', + 'verb' => 'comment', + 'message' => 'my first comment', + ]; + + $comment = new Comment([ + 'objectType' => 'files', + 'objectId' => '42', + 'actorType' => 'users', + 'actorId' => 'alice' + ] + $commentData); + $comment->setId('23'); + + $path = 'comments/files/42'; + + $requestData = json_encode($commentData); + + $user = $this->getMock('OCP\IUser'); + $user->expects($this->never()) + ->method('getUID'); + + $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->once()) + ->method('getName') + ->will($this->returnValue('files')); + $node->expects($this->once()) + ->method('getId') + ->will($this->returnValue('42')); + + $this->commentsManager->expects($this->never()) + ->method('create'); + + $this->userSession->expects($this->never()) + ->method('getUser'); + + // technically, this is a shortcut. Inbetween EntityTypeCollection would + // be returned, but doing it exactly right would not be really + // unit-testing like, as it would require to haul in a lot of other + // things. + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/' . $path)); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $request->expects($this->never()) + ->method('getUrl'); + + $response->expects($this->never()) + ->method('setHeader'); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->httpPost($request, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\UnsupportedMediaType + */ + public function testCreateCommentUnsupportedMediaType() { + $commentData = [ + 'actorType' => 'users', + 'verb' => 'comment', + 'message' => 'my first comment', + ]; + + $comment = new Comment([ + 'objectType' => 'files', + 'objectId' => '42', + 'actorType' => 'users', + 'actorId' => 'alice' + ] + $commentData); + $comment->setId('23'); + + $path = 'comments/files/42'; + + $requestData = json_encode($commentData); + + $user = $this->getMock('OCP\IUser'); + $user->expects($this->never()) + ->method('getUID'); + + $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->once()) + ->method('getName') + ->will($this->returnValue('files')); + $node->expects($this->once()) + ->method('getId') + ->will($this->returnValue('42')); + + $this->commentsManager->expects($this->never()) + ->method('create'); + + $this->userSession->expects($this->never()) + ->method('getUser'); + + // technically, this is a shortcut. Inbetween EntityTypeCollection would + // be returned, but doing it exactly right would not be really + // unit-testing like, as it would require to haul in a lot of other + // things. + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/' . $path)); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/trumpscript')); + + $request->expects($this->never()) + ->method('getUrl'); + + $response->expects($this->never()) + ->method('setHeader'); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->httpPost($request, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\BadRequest + */ + public function testCreateCommentInvalidPayload() { + $commentData = [ + 'actorType' => 'users', + 'verb' => '', + 'message' => '', + ]; + + $comment = new Comment([ + 'objectType' => 'files', + 'objectId' => '42', + 'actorType' => 'users', + 'actorId' => 'alice', + 'message' => 'dummy', + 'verb' => 'dummy' + ]); + $comment->setId('23'); + + $path = 'comments/files/42'; + + $requestData = json_encode($commentData); + + $user = $this->getMock('OCP\IUser'); + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('alice')); + + $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->once()) + ->method('getName') + ->will($this->returnValue('files')); + $node->expects($this->once()) + ->method('getId') + ->will($this->returnValue('42')); + + $this->commentsManager->expects($this->once()) + ->method('create') + ->with('users', 'alice', 'files', '42') + ->will($this->returnValue($comment)); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + // technically, this is a shortcut. Inbetween EntityTypeCollection would + // be returned, but doing it exactly right would not be really + // unit-testing like, as it would require to haul in a lot of other + // things. + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/' . $path)); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $request->expects($this->never()) + ->method('getUrl'); + + $response->expects($this->never()) + ->method('setHeader'); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->httpPost($request, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\BadRequest + * @expectedExceptionMessage Message exceeds allowed character limit of + */ + public function testCreateCommentMessageTooLong() { + $commentData = [ + 'actorType' => 'users', + 'verb' => 'comment', + 'message' => str_pad('', IComment::MAX_MESSAGE_LENGTH + 1, 'x'), + ]; + + $comment = new Comment([ + 'objectType' => 'files', + 'objectId' => '42', + 'actorType' => 'users', + 'actorId' => 'alice', + 'verb' => 'comment', + ]); + $comment->setId('23'); + + $path = 'comments/files/42'; + + $requestData = json_encode($commentData); + + $user = $this->getMock('OCP\IUser'); + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('alice')); + + $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->once()) + ->method('getName') + ->will($this->returnValue('files')); + $node->expects($this->once()) + ->method('getId') + ->will($this->returnValue('42')); + + $node->expects($this->never()) + ->method('setReadMarker'); + + $this->commentsManager->expects($this->once()) + ->method('create') + ->with('users', 'alice', 'files', '42') + ->will($this->returnValue($comment)); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + // technically, this is a shortcut. Inbetween EntityTypeCollection would + // be returned, but doing it exactly right would not be really + // unit-testing like, as it would require to haul in a lot of other + // things. + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/' . $path)); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $response->expects($this->never()) + ->method('setHeader'); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->httpPost($request, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\ReportNotSupported + */ + public function testOnReportInvalidNode() { + $path = 'totally/unrelated/13'; + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($this->getMock('\Sabre\DAV\INode'))); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, [], '/' . $path); + } + + /** + * @expectedException \Sabre\DAV\Exception\ReportNotSupported + */ + public function testOnReportInvalidReportName() { + $path = 'comments/files/42'; + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($this->getMock('\Sabre\DAV\INode'))); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->onReport('{whoever}whatever', [], '/' . $path); + } + + public function testOnReportDateTimeEmpty() { + $path = 'comments/files/42'; + + $parameters = [ + [ + 'name' => '{http://owncloud.org/ns}limit', + 'value' => 5, + ], + [ + 'name' => '{http://owncloud.org/ns}offset', + 'value' => 10, + ], + [ + 'name' => '{http://owncloud.org/ns}datetime', + 'value' => '', + ] + ]; + + $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->once()) + ->method('findChildren') + ->with(5, 10, null) + ->will($this->returnValue([])); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response->expects($this->once()) + ->method('setHeader') + ->with('Content-Type', 'application/xml; charset=utf-8'); + + $response->expects($this->once()) + ->method('setStatus') + ->with(207); + + $response->expects($this->once()) + ->method('setBody'); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($node)); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->server->httpResponse = $response; + $this->plugin->initialize($this->server); + + $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, $parameters, '/' . $path); + } + + public function testOnReport() { + $path = 'comments/files/42'; + + $parameters = [ + [ + 'name' => '{http://owncloud.org/ns}limit', + 'value' => 5, + ], + [ + 'name' => '{http://owncloud.org/ns}offset', + 'value' => 10, + ], + [ + 'name' => '{http://owncloud.org/ns}datetime', + 'value' => '2016-01-10 18:48:00', + ] + ]; + + $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->once()) + ->method('findChildren') + ->with(5, 10, new \DateTime($parameters[2]['value'])) + ->will($this->returnValue([])); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response->expects($this->once()) + ->method('setHeader') + ->with('Content-Type', 'application/xml; charset=utf-8'); + + $response->expects($this->once()) + ->method('setStatus') + ->with(207); + + $response->expects($this->once()) + ->method('setBody'); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($node)); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->server->httpResponse = $response; + $this->plugin->initialize($this->server); + + $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, $parameters, '/' . $path); + } + + + +} diff --git a/apps/dav/tests/unit/Comments/EntityCollectionTest.php b/apps/dav/tests/unit/Comments/EntityCollectionTest.php new file mode 100644 index 00000000000..157d58c9eca --- /dev/null +++ b/apps/dav/tests/unit/Comments/EntityCollectionTest.php @@ -0,0 +1,118 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Comments; + +class EntityCollectionTest extends \Test\TestCase { + + /** @var \OCP\Comments\ICommentsManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $commentsManager; + /** @var \OCP\IUserManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $userManager; + /** @var \OCP\ILogger|\PHPUnit_Framework_MockObject_MockObject */ + protected $logger; + /** @var \OCA\DAV\Comments\EntityCollection */ + protected $collection; + /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject */ + protected $userSession; + + public function setUp() { + parent::setUp(); + + $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); + $this->userManager = $this->getMock('\OCP\IUserManager'); + $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->logger = $this->getMock('\OCP\ILogger'); + + $this->collection = new \OCA\DAV\Comments\EntityCollection( + '19', + 'files', + $this->commentsManager, + $this->userManager, + $this->userSession, + $this->logger + ); + } + + public function testGetId() { + $this->assertSame($this->collection->getId(), '19'); + } + + public function testGetChild() { + $this->commentsManager->expects($this->once()) + ->method('get') + ->with('55') + ->will($this->returnValue($this->getMock('\OCP\Comments\IComment'))); + + $node = $this->collection->getChild('55'); + $this->assertTrue($node instanceof \OCA\DAV\Comments\CommentNode); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotFound + */ + public function testGetChildException() { + $this->commentsManager->expects($this->once()) + ->method('get') + ->with('55') + ->will($this->throwException(new \OCP\Comments\NotFoundException())); + + $this->collection->getChild('55'); + } + + public function testGetChildren() { + $this->commentsManager->expects($this->once()) + ->method('getForObject') + ->with('files', '19') + ->will($this->returnValue([$this->getMock('\OCP\Comments\IComment')])); + + $result = $this->collection->getChildren(); + + $this->assertSame(count($result), 1); + $this->assertTrue($result[0] instanceof \OCA\DAV\Comments\CommentNode); + } + + public function testFindChildren() { + $dt = new \DateTime('2016-01-10 18:48:00'); + $this->commentsManager->expects($this->once()) + ->method('getForObject') + ->with('files', '19', 5, 15, $dt) + ->will($this->returnValue([$this->getMock('\OCP\Comments\IComment')])); + + $result = $this->collection->findChildren(5, 15, $dt); + + $this->assertSame(count($result), 1); + $this->assertTrue($result[0] instanceof \OCA\DAV\Comments\CommentNode); + } + + public function testChildExistsTrue() { + $this->assertTrue($this->collection->childExists('44')); + } + + public function testChildExistsFalse() { + $this->commentsManager->expects($this->once()) + ->method('get') + ->with('44') + ->will($this->throwException(new \OCP\Comments\NotFoundException())); + + $this->assertFalse($this->collection->childExists('44')); + } +} diff --git a/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php b/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php new file mode 100644 index 00000000000..51db44380fa --- /dev/null +++ b/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php @@ -0,0 +1,92 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Comments; + +use OCA\DAV\Comments\EntityCollection as EntityCollectionImplemantation; + +class EntityTypeCollectionTest extends \Test\TestCase { + + /** @var \OCP\Comments\ICommentsManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $commentsManager; + /** @var \OCP\IUserManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $userManager; + /** @var \OCP\ILogger|\PHPUnit_Framework_MockObject_MockObject */ + protected $logger; + /** @var \OCA\DAV\Comments\EntityTypeCollection */ + protected $collection; + /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject */ + protected $userSession; + + protected $childMap = []; + + public function setUp() { + parent::setUp(); + + $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); + $this->userManager = $this->getMock('\OCP\IUserManager'); + $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->logger = $this->getMock('\OCP\ILogger'); + + $instance = $this; + + $this->collection = new \OCA\DAV\Comments\EntityTypeCollection( + 'files', + $this->commentsManager, + $this->userManager, + $this->userSession, + $this->logger, + function ($child) use ($instance) { + return !empty($instance->childMap[$child]); + } + ); + } + + public function testChildExistsYes() { + $this->childMap[17] = true; + $this->assertTrue($this->collection->childExists('17')); + } + + public function testChildExistsNo() { + $this->assertFalse($this->collection->childExists('17')); + } + + public function testGetChild() { + $this->childMap[17] = true; + + $ec = $this->collection->getChild('17'); + $this->assertTrue($ec instanceof EntityCollectionImplemantation); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotFound + */ + public function testGetChildException() { + $this->collection->getChild('17'); + } + + /** + * @expectedException \Sabre\DAV\Exception\MethodNotAllowed + */ + public function testGetChildren() { + $this->collection->getChildren(); + } +} diff --git a/apps/dav/tests/unit/Comments/RootCollectionTest.php b/apps/dav/tests/unit/Comments/RootCollectionTest.php new file mode 100644 index 00000000000..8f3b83e4264 --- /dev/null +++ b/apps/dav/tests/unit/Comments/RootCollectionTest.php @@ -0,0 +1,170 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Comments; + +use OCA\DAV\Comments\EntityTypeCollection as EntityTypeCollectionImplementation; +use OCP\Comments\CommentsEntityEvent; +use Symfony\Component\EventDispatcher\EventDispatcher; + +class RootCollectionTest extends \Test\TestCase { + + /** @var \OCP\Comments\ICommentsManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $commentsManager; + /** @var \OCP\IUserManager|\PHPUnit_Framework_MockObject_MockObject */ + protected $userManager; + /** @var \OCP\ILogger|\PHPUnit_Framework_MockObject_MockObject */ + protected $logger; + /** @var \OCA\DAV\Comments\RootCollection */ + protected $collection; + /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject */ + protected $userSession; + /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ + protected $dispatcher; + /** @var \OCP\IUser|\PHPUnit_Framework_MockObject_MockObject */ + protected $user; + + public function setUp() { + parent::setUp(); + + $this->user = $this->getMock('\OCP\IUser'); + + $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); + $this->userManager = $this->getMock('\OCP\IUserManager'); + $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->dispatcher = new EventDispatcher(); + $this->logger = $this->getMock('\OCP\ILogger'); + + $this->collection = new \OCA\DAV\Comments\RootCollection( + $this->commentsManager, + $this->userManager, + $this->userSession, + $this->dispatcher, + $this->logger + ); + } + + protected function prepareForInitCollections() { + $this->user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('alice')); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($this->user)); + + $this->dispatcher->addListener(CommentsEntityEvent::EVENT_ENTITY, function(CommentsEntityEvent $event) { + $event->addEntityCollection('files', function() { + return true; + }); + }); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testCreateFile() { + $this->collection->createFile('foo'); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testCreateDirectory() { + $this->collection->createDirectory('foo'); + } + + public function testGetChild() { + $this->prepareForInitCollections(); + $etc = $this->collection->getChild('files'); + $this->assertTrue($etc instanceof EntityTypeCollectionImplementation); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotFound + */ + public function testGetChildInvalid() { + $this->prepareForInitCollections(); + $this->collection->getChild('robots'); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotAuthenticated + */ + public function testGetChildNoAuth() { + $this->collection->getChild('files'); + } + + public function testGetChildren() { + $this->prepareForInitCollections(); + $children = $this->collection->getChildren(); + $this->assertFalse(empty($children)); + foreach($children as $child) { + $this->assertTrue($child instanceof EntityTypeCollectionImplementation); + } + } + + /** + * @expectedException \Sabre\DAV\Exception\NotAuthenticated + */ + public function testGetChildrenNoAuth() { + $this->collection->getChildren(); + } + + public function testChildExistsYes() { + $this->prepareForInitCollections(); + $this->assertTrue($this->collection->childExists('files')); + } + + public function testChildExistsNo() { + $this->prepareForInitCollections(); + $this->assertFalse($this->collection->childExists('robots')); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotAuthenticated + */ + public function testChildExistsNoAuth() { + $this->collection->childExists('files'); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDelete() { + $this->collection->delete(); + } + + public function testGetName() { + $this->assertSame('comments', $this->collection->getName()); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testSetName() { + $this->collection->setName('foobar'); + } + + public function testGetLastModified() { + $this->assertSame(null, $this->collection->getLastModified()); + } +} diff --git a/apps/dav/tests/unit/Connector/PublicAuthTest.php b/apps/dav/tests/unit/Connector/PublicAuthTest.php new file mode 100644 index 00000000000..f8d6e1b5d12 --- /dev/null +++ b/apps/dav/tests/unit/Connector/PublicAuthTest.php @@ -0,0 +1,177 @@ +session = $this->getMock('\OCP\ISession'); + $this->request = $this->getMock('\OCP\IRequest'); + $this->shareManager = $this->getMock('\OCP\Share\IManager'); + + $this->auth = new \OCA\DAV\Connector\PublicAuth( + $this->request, + $this->shareManager, + $this->session + ); + + // Store current user + $this->oldUser = \OC_User::getUser(); + } + + protected function tearDown() { + \OC_User::setIncognitoMode(false); + + // Set old user + \OC_User::setUserId($this->oldUser); + \OC_Util::setupFS($this->oldUser); + + parent::tearDown(); + } + + public function testNoShare() { + $this->shareManager->expects($this->once()) + ->method('getShareByToken') + ->willThrowException(new ShareNotFound()); + + $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); + + $this->assertFalse($result); + } + + public function testShareNoPassword() { + $share = $this->getMock('OCP\Share\IShare'); + $share->method('getPassword')->willReturn(null); + + $this->shareManager->expects($this->once()) + ->method('getShareByToken') + ->willReturn($share); + + $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); + + $this->assertTrue($result); + } + + public function testSharePasswordFancyShareType() { + $share = $this->getMock('OCP\Share\IShare'); + $share->method('getPassword')->willReturn('password'); + $share->method('getShareType')->willReturn(42); + + $this->shareManager->expects($this->once()) + ->method('getShareByToken') + ->willReturn($share); + + $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); + + $this->assertFalse($result); + } + + + public function testSharePasswordRemote() { + $share = $this->getMock('OCP\Share\IShare'); + $share->method('getPassword')->willReturn('password'); + $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_REMOTE); + + $this->shareManager->expects($this->once()) + ->method('getShareByToken') + ->willReturn($share); + + $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); + + $this->assertTrue($result); + } + + public function testSharePasswordLinkValidPassword() { + $share = $this->getMock('OCP\Share\IShare'); + $share->method('getPassword')->willReturn('password'); + $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); + + $this->shareManager->expects($this->once()) + ->method('getShareByToken') + ->willReturn($share); + + $this->shareManager->expects($this->once()) + ->method('checkPassword')->with( + $this->equalTo($share), + $this->equalTo('password') + )->willReturn(true); + + $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); + + $this->assertTrue($result); + } + + public function testSharePasswordLinkValidSession() { + $share = $this->getMock('OCP\Share\IShare'); + $share->method('getPassword')->willReturn('password'); + $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); + $share->method('getId')->willReturn('42'); + + $this->shareManager->expects($this->once()) + ->method('getShareByToken') + ->willReturn($share); + + $this->shareManager->method('checkPassword') + ->with( + $this->equalTo($share), + $this->equalTo('password') + )->willReturn(false); + + $this->session->method('exists')->with('public_link_authenticated')->willReturn(true); + $this->session->method('get')->with('public_link_authenticated')->willReturn('42'); + + $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); + + $this->assertTrue($result); + } + + public function testSharePasswordLinkInvalidSession() { + $share = $this->getMock('OCP\Share\IShare'); + $share->method('getPassword')->willReturn('password'); + $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); + $share->method('getId')->willReturn('42'); + + $this->shareManager->expects($this->once()) + ->method('getShareByToken') + ->willReturn($share); + + $this->shareManager->method('checkPassword') + ->with( + $this->equalTo($share), + $this->equalTo('password') + )->willReturn(false); + + $this->session->method('exists')->with('public_link_authenticated')->willReturn(true); + $this->session->method('get')->with('public_link_authenticated')->willReturn('43'); + + $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); + + $this->assertFalse($result); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/AuthTest.php b/apps/dav/tests/unit/Connector/Sabre/AuthTest.php new file mode 100644 index 00000000000..1c29d2dbd6f --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/AuthTest.php @@ -0,0 +1,611 @@ + + * @author Roeland Jago Douma + * @author Thomas Müller + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCP\IRequest; +use OCP\IUser; +use Test\TestCase; +use OCP\ISession; +use OC\User\Session; + +/** + * Class AuthTest + * + * @package OCA\DAV\Tests\unit\Connector\Sabre + * @group DB + */ +class AuthTest extends TestCase { + /** @var ISession */ + private $session; + /** @var \OCA\DAV\Connector\Sabre\Auth */ + private $auth; + /** @var Session */ + private $userSession; + /** @var IRequest */ + private $request; + + public function setUp() { + parent::setUp(); + $this->session = $this->getMockBuilder('\OCP\ISession') + ->disableOriginalConstructor()->getMock(); + $this->userSession = $this->getMockBuilder('\OC\User\Session') + ->disableOriginalConstructor()->getMock(); + $this->request = $this->getMockBuilder('\OCP\IRequest') + ->disableOriginalConstructor()->getMock(); + $this->auth = new \OCA\DAV\Connector\Sabre\Auth( + $this->session, + $this->userSession, + $this->request + ); + } + + public function testIsDavAuthenticatedWithoutDavSession() { + $this->session + ->expects($this->once()) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue(null)); + + $this->assertFalse($this->invokePrivate($this->auth, 'isDavAuthenticated', ['MyTestUser'])); + } + + public function testIsDavAuthenticatedWithWrongDavSession() { + $this->session + ->expects($this->exactly(2)) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue('AnotherUser')); + + $this->assertFalse($this->invokePrivate($this->auth, 'isDavAuthenticated', ['MyTestUser'])); + } + + public function testIsDavAuthenticatedWithCorrectDavSession() { + $this->session + ->expects($this->exactly(2)) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue('MyTestUser')); + + $this->assertTrue($this->invokePrivate($this->auth, 'isDavAuthenticated', ['MyTestUser'])); + } + + public function testValidateUserPassOfAlreadyDAVAuthenticatedUser() { + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->exactly(2)) + ->method('getUID') + ->will($this->returnValue('MyTestUser')); + $this->userSession + ->expects($this->once()) + ->method('isLoggedIn') + ->will($this->returnValue(true)); + $this->userSession + ->expects($this->exactly(2)) + ->method('getUser') + ->will($this->returnValue($user)); + $this->session + ->expects($this->exactly(2)) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue('MyTestUser')); + $this->session + ->expects($this->once()) + ->method('close'); + + $this->assertTrue($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); + } + + public function testValidateUserPassOfInvalidDAVAuthenticatedUser() { + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('MyTestUser')); + $this->userSession + ->expects($this->once()) + ->method('isLoggedIn') + ->will($this->returnValue(true)); + $this->userSession + ->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + $this->session + ->expects($this->exactly(2)) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue('AnotherUser')); + $this->session + ->expects($this->once()) + ->method('close'); + + $this->assertFalse($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); + } + + public function testValidateUserPassOfInvalidDAVAuthenticatedUserWithValidPassword() { + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->exactly(4)) + ->method('getUID') + ->will($this->returnValue('MyTestUser')); + $this->userSession + ->expects($this->once()) + ->method('isLoggedIn') + ->will($this->returnValue(true)); + $this->userSession + ->expects($this->exactly(4)) + ->method('getUser') + ->will($this->returnValue($user)); + $this->session + ->expects($this->exactly(2)) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue('AnotherUser')); + $this->userSession + ->expects($this->once()) + ->method('logClientIn') + ->with('MyTestUser', 'MyTestPassword') + ->will($this->returnValue(true)); + $this->userSession + ->expects($this->once()) + ->method('createSessionToken') + ->with($this->request, 'MyTestUser', 'MyTestUser', 'MyTestPassword'); + $this->session + ->expects($this->once()) + ->method('set') + ->with('AUTHENTICATED_TO_DAV_BACKEND', 'MyTestUser'); + $this->session + ->expects($this->once()) + ->method('close'); + + $this->assertTrue($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); + } + + public function testValidateUserPassWithInvalidPassword() { + $this->userSession + ->expects($this->once()) + ->method('isLoggedIn') + ->will($this->returnValue(false)); + $this->userSession + ->expects($this->once()) + ->method('logClientIn') + ->with('MyTestUser', 'MyTestPassword') + ->will($this->returnValue(false)); + $this->session + ->expects($this->once()) + ->method('close'); + + $this->assertFalse($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); + } + + + public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGet() { + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->will($this->returnValue(true)); + $this->request + ->expects($this->any()) + ->method('getMethod') + ->willReturn('POST'); + $this->session + ->expects($this->any()) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue(null)); + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('MyWrongDavUser')); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(false); + + $expectedResponse = [ + false, + "No 'Authorization: Basic' header found. Either the client didn't send one, or the server is mis-configured", + ]; + $response = $this->auth->check($request, $response); + $this->assertSame($expectedResponse, $response); + } + + public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndCorrectlyDavAuthenticated() { + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->willReturn(true); + $this->request + ->expects($this->any()) + ->method('getMethod') + ->willReturn('PROPFIND'); + $this->request + ->expects($this->any()) + ->method('isUserAgent') + ->with([ + '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/', + '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/', + '/^Mozilla\/5\.0 \(iOS\) ownCloud\-iOS.*$/', + ]) + ->willReturn(false); + $this->session + ->expects($this->any()) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue('LoggedInUser')); + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('LoggedInUser')); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(false); + $this->auth->check($request, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotAuthenticated + * @expectedExceptionMessage CSRF check not passed. + */ + public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndIncorrectlyDavAuthenticated() { + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->willReturn(true); + $this->request + ->expects($this->any()) + ->method('getMethod') + ->willReturn('PROPFIND'); + $this->request + ->expects($this->any()) + ->method('isUserAgent') + ->with([ + '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/', + '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/', + '/^Mozilla\/5\.0 \(iOS\) ownCloud\-iOS.*$/', + ]) + ->willReturn(false); + $this->session + ->expects($this->any()) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue('AnotherUser')); + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('LoggedInUser')); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(false); + $this->auth->check($request, $response); + } + + public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGetAndDesktopClient() { + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->will($this->returnValue(true)); + $this->request + ->expects($this->any()) + ->method('getMethod') + ->willReturn('POST'); + $this->request + ->expects($this->any()) + ->method('isUserAgent') + ->with([ + '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/', + '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/', + '/^Mozilla\/5\.0 \(iOS\) ownCloud\-iOS.*$/', + ]) + ->willReturn(true); + $this->session + ->expects($this->any()) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue(null)); + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('MyWrongDavUser')); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(false); + + $this->auth->check($request, $response); + } + + public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForGet() { + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->will($this->returnValue(true)); + $this->session + ->expects($this->any()) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue(null)); + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('MyWrongDavUser')); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)); + $this->request + ->expects($this->any()) + ->method('getMethod') + ->willReturn('GET'); + + $response = $this->auth->check($request, $response); + $this->assertEquals([true, 'principals/users/MyWrongDavUser'], $response); + } + + public function testAuthenticateAlreadyLoggedInWithCsrfTokenForGet() { + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->will($this->returnValue(true)); + $this->session + ->expects($this->any()) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue(null)); + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('MyWrongDavUser')); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)); + $this->request + ->expects($this->once()) + ->method('passesCSRFCheck') + ->willReturn(true); + + $response = $this->auth->check($request, $response); + $this->assertEquals([true, 'principals/users/MyWrongDavUser'], $response); + } + + public function testAuthenticateNoBasicAuthenticateHeadersProvided() { + $server = $this->getMockBuilder('\Sabre\DAV\Server') + ->disableOriginalConstructor() + ->getMock(); + $server->httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $server->httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->auth->check($server->httpRequest, $server->httpResponse); + $this->assertEquals([false, 'No \'Authorization: Basic\' header found. Either the client didn\'t send one, or the server is mis-configured'], $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotAuthenticated + * @expectedExceptionMessage Cannot authenticate over ajax calls + */ + public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjax() { + /** @var \Sabre\HTTP\RequestInterface $httpRequest */ + $httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + /** @var \Sabre\HTTP\ResponseInterface $httpResponse */ + $httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->will($this->returnValue(false)); + $httpRequest + ->expects($this->once()) + ->method('getHeader') + ->with('X-Requested-With') + ->will($this->returnValue('XMLHttpRequest')); + $this->auth->check($httpRequest, $httpResponse); + } + + public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjaxButUserIsStillLoggedIn() { + /** @var \Sabre\HTTP\RequestInterface $httpRequest */ + $httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + /** @var \Sabre\HTTP\ResponseInterface $httpResponse */ + $httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + /** @var IUser */ + $user = $this->getMock('OCP\IUser'); + $user->method('getUID')->willReturn('MyTestUser'); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->will($this->returnValue(true)); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->willReturn($user); + $this->session + ->expects($this->atLeastOnce()) + ->method('get') + ->with('AUTHENTICATED_TO_DAV_BACKEND') + ->will($this->returnValue('MyTestUser')); + $this->request + ->expects($this->once()) + ->method('getMethod') + ->willReturn('GET'); + $httpRequest + ->expects($this->atLeastOnce()) + ->method('getHeader') + ->with('Authorization') + ->will($this->returnValue(null)); + $this->assertEquals( + [true, 'principals/users/MyTestUser'], + $this->auth->check($httpRequest, $httpResponse) + ); + } + + public function testAuthenticateValidCredentials() { + $server = $this->getMockBuilder('\Sabre\DAV\Server') + ->disableOriginalConstructor() + ->getMock(); + $server->httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $server->httpRequest + ->expects($this->at(0)) + ->method('getHeader') + ->with('X-Requested-With') + ->will($this->returnValue(null)); + $server->httpRequest + ->expects($this->at(1)) + ->method('getHeader') + ->with('Authorization') + ->will($this->returnValue('basic dXNlcm5hbWU6cGFzc3dvcmQ=')); + $server->httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->once()) + ->method('logClientIn') + ->with('username', 'password') + ->will($this->returnValue(true)); + $this->userSession + ->expects($this->once()) + ->method('createSessionToken'); + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->exactly(4)) + ->method('getUID') + ->will($this->returnValue('MyTestUser')); + $this->userSession + ->expects($this->exactly(4)) + ->method('getUser') + ->will($this->returnValue($user)); + $response = $this->auth->check($server->httpRequest, $server->httpResponse); + $this->assertEquals([true, 'principals/users/MyTestUser'], $response); + } + + public function testAuthenticateInvalidCredentials() { + $server = $this->getMockBuilder('\Sabre\DAV\Server') + ->disableOriginalConstructor() + ->getMock(); + $server->httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $server->httpRequest + ->expects($this->at(0)) + ->method('getHeader') + ->with('X-Requested-With') + ->will($this->returnValue(null)); + $server->httpRequest + ->expects($this->at(1)) + ->method('getHeader') + ->with('Authorization') + ->will($this->returnValue('basic dXNlcm5hbWU6cGFzc3dvcmQ=')); + $server->httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + $this->userSession + ->expects($this->once()) + ->method('logClientIn') + ->with('username', 'password') + ->will($this->returnValue(false)); + $response = $this->auth->check($server->httpRequest, $server->httpResponse); + $this->assertEquals([false, 'Username or password was incorrect'], $response); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php new file mode 100644 index 00000000000..00378fd4139 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php @@ -0,0 +1,130 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin; +use Test\TestCase; +use OCP\IConfig; + +/** + * Class BlockLegacyClientPluginTest + * + * @package OCA\DAV\Tests\unit\Connector\Sabre + */ +class BlockLegacyClientPluginTest extends TestCase { + /** @var IConfig */ + private $config; + /** @var BlockLegacyClientPlugin */ + private $blockLegacyClientVersionPlugin; + + public function setUp() { + parent::setUp(); + + $this->config = $this->getMock('\OCP\IConfig'); + $this->blockLegacyClientVersionPlugin = new BlockLegacyClientPlugin($this->config); + } + + /** + * @return array + */ + public function oldDesktopClientProvider() { + return [ + ['Mozilla/5.0 (1.5.0) mirall/1.5.0'], + ['mirall/1.5.0'], + ['mirall/1.5.4'], + ['mirall/1.6.0'], + ['Mozilla/5.0 (Bogus Text) mirall/1.6.9'], + ]; + } + + /** + * @dataProvider oldDesktopClientProvider + * @param string $userAgent + * @expectedException \Sabre\DAV\Exception\Forbidden + * @expectedExceptionMessage Unsupported client version. + */ + public function testBeforeHandlerException($userAgent) { + /** @var \Sabre\HTTP\RequestInterface $request */ + $request = $this->getMock('\Sabre\HTTP\RequestInterface'); + $request + ->expects($this->once()) + ->method('getHeader') + ->with('User-Agent') + ->will($this->returnValue($userAgent)); + + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('minimum.supported.desktop.version', '1.7.0') + ->will($this->returnValue('1.7.0')); + + $this->blockLegacyClientVersionPlugin->beforeHandler($request); + } + + /** + * @return array + */ + public function newAndAlternateDesktopClientProvider() { + return [ + ['Mozilla/5.0 (1.7.0) mirall/1.7.0'], + ['mirall/1.8.3'], + ['mirall/1.7.2'], + ['mirall/1.7.0'], + ['Mozilla/5.0 (Bogus Text) mirall/1.9.3'], + ]; + } + + /** + * @dataProvider newAndAlternateDesktopClientProvider + * @param string $userAgent + */ + public function testBeforeHandlerSuccess($userAgent) { + /** @var \Sabre\HTTP\RequestInterface $request */ + $request = $this->getMock('\Sabre\HTTP\RequestInterface'); + $request + ->expects($this->once()) + ->method('getHeader') + ->with('User-Agent') + ->will($this->returnValue($userAgent)); + + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('minimum.supported.desktop.version', '1.7.0') + ->will($this->returnValue('1.7.0')); + + $this->blockLegacyClientVersionPlugin->beforeHandler($request); + } + + public function testBeforeHandlerNoUserAgent() { + /** @var \Sabre\HTTP\RequestInterface $request */ + $request = $this->getMock('\Sabre\HTTP\RequestInterface'); + $request + ->expects($this->once()) + ->method('getHeader') + ->with('User-Agent') + ->will($this->returnValue(null)); + $this->blockLegacyClientVersionPlugin->beforeHandler($request); + } + +} diff --git a/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php new file mode 100644 index 00000000000..d98c2228ebd --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php @@ -0,0 +1,149 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin as CommentPropertiesPluginImplementation; + +class CommentsPropertiesPluginTest extends \Test\TestCase { + + /** @var CommentPropertiesPluginImplementation */ + protected $plugin; + protected $commentsManager; + protected $userSession; + protected $server; + + public function setUp() { + parent::setUp(); + + $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); + $this->userSession = $this->getMock('\OCP\IUserSession'); + + $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + ->disableOriginalConstructor() + ->getMock(); + + $this->plugin = new CommentPropertiesPluginImplementation($this->commentsManager, $this->userSession); + $this->plugin->initialize($this->server); + } + + public function nodeProvider() { + $mocks = []; + foreach(['\OCA\DAV\Connector\Sabre\File', '\OCA\DAV\Connector\Sabre\Directory', '\Sabre\DAV\INode'] as $class) { + $mocks[] = $this->getMockBuilder($class) + ->disableOriginalConstructor() + ->getMock(); + } + + return [ + [$mocks[0], true], + [$mocks[1], true], + [$mocks[2], false] + ]; + } + + /** + * @dataProvider nodeProvider + * @param $node + * @param $expectedSuccessful + */ + public function testHandleGetProperties($node, $expectedSuccessful) { + $propFind = $this->getMockBuilder('\Sabre\DAV\PropFind') + ->disableOriginalConstructor() + ->getMock(); + + if($expectedSuccessful) { + $propFind->expects($this->exactly(3)) + ->method('handle'); + } else { + $propFind->expects($this->never()) + ->method('handle'); + } + + $this->plugin->handleGetProperties($propFind, $node); + } + + public function baseUriProvider() { + return [ + ['owncloud/remote.php/webdav/', '4567', 'owncloud/remote.php/dav/comments/files/4567'], + ['owncloud/remote.php/files/', '4567', 'owncloud/remote.php/dav/comments/files/4567'], + ['owncloud/wicked.php/files/', '4567', null] + ]; + } + + /** + * @dataProvider baseUriProvider + * @param $baseUri + * @param $fid + * @param $expectedHref + */ + public function testGetCommentsLink($baseUri, $fid, $expectedHref) { + $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue($fid)); + + $this->server->expects($this->once()) + ->method('getBaseUri') + ->will($this->returnValue($baseUri)); + + $href = $this->plugin->getCommentsLink($node); + $this->assertSame($expectedHref, $href); + } + + public function userProvider() { + return [ + [$this->getMock('\OCP\IUser')], + [null] + ]; + } + + /** + * @dataProvider userProvider + * @param $user + */ + public function testGetUnreadCount($user) { + $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue('4567')); + + $this->userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->commentsManager->expects($this->any()) + ->method('getNumberOfCommentsForObject') + ->will($this->returnValue(42)); + + $unread = $this->plugin->getUnreadCount($node); + if(is_null($user)) { + $this->assertNull($unread); + } else { + $this->assertSame($unread, 42); + } + } + +} diff --git a/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php new file mode 100644 index 00000000000..b8695e0a5d5 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php @@ -0,0 +1,62 @@ + + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +/** + * Copyright (c) 2015 Vincent Petry + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +class CopyEtagHeaderPluginTest extends \Test\TestCase { + + /** + * @var \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin + */ + private $plugin; + + public function setUp() { + parent::setUp(); + $this->server = new \Sabre\DAV\Server(); + $this->plugin = new \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin(); + $this->plugin->initialize($this->server); + } + + public function testCopyEtag() { + $request = new \Sabre\Http\Request(); + $response = new \Sabre\Http\Response(); + $response->setHeader('Etag', 'abcd'); + + $this->plugin->afterMethod($request, $response); + + $this->assertEquals('abcd', $response->getHeader('OC-Etag')); + } + + public function testNoopWhenEmpty() { + $request = new \Sabre\Http\Request(); + $response = new \Sabre\Http\Response(); + + $this->plugin->afterMethod($request, $response); + + $this->assertNull($response->getHeader('OC-Etag')); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php b/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php new file mode 100644 index 00000000000..0ae6bb014ad --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php @@ -0,0 +1,313 @@ + + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +/** + * Copyright (c) 2015 Vincent Petry + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +/** + * Class CustomPropertiesBackend + * + * @group DB + * + * @package OCA\DAV\Tests\unit\Connector\Sabre + */ +class CustomPropertiesBackendTest extends \Test\TestCase { + + /** + * @var \Sabre\DAV\Server + */ + private $server; + + /** + * @var \Sabre\DAV\Tree + */ + private $tree; + + /** + * @var \OCA\DAV\Connector\Sabre\CustomPropertiesBackend + */ + private $plugin; + + /** + * @var \OCP\IUser + */ + private $user; + + public function setUp() { + parent::setUp(); + $this->server = new \Sabre\DAV\Server(); + $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + ->disableOriginalConstructor() + ->getMock(); + + $userId = $this->getUniqueID('testcustompropertiesuser'); + + $this->user = $this->getMock('\OCP\IUser'); + $this->user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue($userId)); + + $this->plugin = new \OCA\DAV\Connector\Sabre\CustomPropertiesBackend( + $this->tree, + \OC::$server->getDatabaseConnection(), + $this->user + ); + } + + public function tearDown() { + $connection = \OC::$server->getDatabaseConnection(); + $deleteStatement = $connection->prepare( + 'DELETE FROM `*PREFIX*properties`' . + ' WHERE `userid` = ?' + ); + $deleteStatement->execute( + array( + $this->user->getUID(), + ) + ); + $deleteStatement->closeCursor(); + } + + private function createTestNode($class) { + $node = $this->getMockBuilder($class) + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + + $node->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/dummypath')); + + return $node; + } + + private function applyDefaultProps($path = '/dummypath') { + // properties to set + $propPatch = new \Sabre\DAV\PropPatch(array( + 'customprop' => 'value1', + 'customprop2' => 'value2', + )); + + $this->plugin->propPatch( + $path, + $propPatch + ); + + $propPatch->commit(); + + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertEquals(200, $result['customprop']); + $this->assertEquals(200, $result['customprop2']); + } + + /** + * Test that propFind on a missing file soft fails + */ + public function testPropFindMissingFileSoftFail() { + $this->tree->expects($this->at(0)) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); + + $this->tree->expects($this->at(1)) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->throwException(new \Sabre\DAV\Exception\ServiceUnavailable())); + + $propFind = new \Sabre\DAV\PropFind( + '/dummypath', + array( + 'customprop', + 'customprop2', + 'unsetprop', + ), + 0 + ); + + $this->plugin->propFind( + '/dummypath', + $propFind + ); + + $this->plugin->propFind( + '/dummypath', + $propFind + ); + + // no exception, soft fail + $this->assertTrue(true); + } + + /** + * Test setting/getting properties + */ + public function testSetGetPropertiesForFile() { + $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->returnValue($node)); + + $this->applyDefaultProps(); + + $propFind = new \Sabre\DAV\PropFind( + '/dummypath', + array( + 'customprop', + 'customprop2', + 'unsetprop', + ), + 0 + ); + + $this->plugin->propFind( + '/dummypath', + $propFind + ); + + $this->assertEquals('value1', $propFind->get('customprop')); + $this->assertEquals('value2', $propFind->get('customprop2')); + $this->assertEquals(array('unsetprop'), $propFind->get404Properties()); + } + + /** + * Test getting properties from directory + */ + public function testGetPropertiesForDirectory() { + $rootNode = $this->createTestNode('\OCA\DAV\Connector\Sabre\Directory'); + + $nodeSub = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + ->disableOriginalConstructor() + ->getMock(); + $nodeSub->expects($this->any()) + ->method('getId') + ->will($this->returnValue(456)); + + $nodeSub->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/dummypath/test.txt')); + + $rootNode->expects($this->once()) + ->method('getChildren') + ->will($this->returnValue(array($nodeSub))); + + $this->tree->expects($this->at(0)) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->returnValue($rootNode)); + + $this->tree->expects($this->at(1)) + ->method('getNodeForPath') + ->with('/dummypath/test.txt') + ->will($this->returnValue($nodeSub)); + + $this->tree->expects($this->at(2)) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->returnValue($rootNode)); + + $this->tree->expects($this->at(3)) + ->method('getNodeForPath') + ->with('/dummypath/test.txt') + ->will($this->returnValue($nodeSub)); + + $this->applyDefaultProps('/dummypath'); + $this->applyDefaultProps('/dummypath/test.txt'); + + $propNames = array( + 'customprop', + 'customprop2', + 'unsetprop', + ); + + $propFindRoot = new \Sabre\DAV\PropFind( + '/dummypath', + $propNames, + 1 + ); + + $propFindSub = new \Sabre\DAV\PropFind( + '/dummypath/test.txt', + $propNames, + 0 + ); + + $this->plugin->propFind( + '/dummypath', + $propFindRoot + ); + + $this->plugin->propFind( + '/dummypath/test.txt', + $propFindSub + ); + + // TODO: find a way to assert that no additional SQL queries were + // run while doing the second propFind + + $this->assertEquals('value1', $propFindRoot->get('customprop')); + $this->assertEquals('value2', $propFindRoot->get('customprop2')); + $this->assertEquals(array('unsetprop'), $propFindRoot->get404Properties()); + + $this->assertEquals('value1', $propFindSub->get('customprop')); + $this->assertEquals('value2', $propFindSub->get('customprop2')); + $this->assertEquals(array('unsetprop'), $propFindSub->get404Properties()); + } + + /** + * Test delete property + */ + public function testDeleteProperty() { + $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->returnValue($node)); + + $this->applyDefaultProps(); + + $propPatch = new \Sabre\DAV\PropPatch(array( + 'customprop' => null, + )); + + $this->plugin->propPatch( + '/dummypath', + $propPatch + ); + + $propPatch->commit(); + + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertEquals(204, $result['customprop']); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php b/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php new file mode 100644 index 00000000000..66f0a803807 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php @@ -0,0 +1,267 @@ + + * @author Robin Appelman + * @author Thomas Müller + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\Unit\Connector\Sabre; + +use OCP\Files\ForbiddenException; + +/** + * @group DB + */ +class DirectoryTest extends \Test\TestCase { + + /** @var \OC\Files\View | \PHPUnit_Framework_MockObject_MockObject */ + private $view; + /** @var \OC\Files\FileInfo | \PHPUnit_Framework_MockObject_MockObject */ + private $info; + + protected function setUp() { + parent::setUp(); + + $this->view = $this->getMock('OC\Files\View', array(), array(), '', false); + $this->info = $this->getMock('OC\Files\FileInfo', array(), array(), '', false); + } + + private function getDir($path = '/') { + $this->view->expects($this->once()) + ->method('getRelativePath') + ->will($this->returnValue($path)); + + $this->info->expects($this->once()) + ->method('getPath') + ->will($this->returnValue($path)); + + return new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDeleteRootFolderFails() { + $this->info->expects($this->any()) + ->method('isDeletable') + ->will($this->returnValue(true)); + $this->view->expects($this->never()) + ->method('rmdir'); + $dir = $this->getDir(); + $dir->delete(); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\Forbidden + */ + public function testDeleteForbidden() { + // deletion allowed + $this->info->expects($this->once()) + ->method('isDeletable') + ->will($this->returnValue(true)); + + // but fails + $this->view->expects($this->once()) + ->method('rmdir') + ->with('sub') + ->willThrowException(new ForbiddenException('', true)); + + $dir = $this->getDir('sub'); + $dir->delete(); + } + + /** + * + */ + public function testDeleteFolderWhenAllowed() { + // deletion allowed + $this->info->expects($this->once()) + ->method('isDeletable') + ->will($this->returnValue(true)); + + // but fails + $this->view->expects($this->once()) + ->method('rmdir') + ->with('sub') + ->will($this->returnValue(true)); + + $dir = $this->getDir('sub'); + $dir->delete(); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDeleteFolderFailsWhenNotAllowed() { + $this->info->expects($this->once()) + ->method('isDeletable') + ->will($this->returnValue(false)); + + $dir = $this->getDir('sub'); + $dir->delete(); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDeleteFolderThrowsWhenDeletionFailed() { + // deletion allowed + $this->info->expects($this->once()) + ->method('isDeletable') + ->will($this->returnValue(true)); + + // but fails + $this->view->expects($this->once()) + ->method('rmdir') + ->with('sub') + ->will($this->returnValue(false)); + + $dir = $this->getDir('sub'); + $dir->delete(); + } + + public function testGetChildren() { + $info1 = $this->getMockBuilder('OC\Files\FileInfo') + ->disableOriginalConstructor() + ->getMock(); + $info2 = $this->getMockBuilder('OC\Files\FileInfo') + ->disableOriginalConstructor() + ->getMock(); + $info1->expects($this->any()) + ->method('getName') + ->will($this->returnValue('first')); + $info1->expects($this->any()) + ->method('getEtag') + ->will($this->returnValue('abc')); + $info2->expects($this->any()) + ->method('getName') + ->will($this->returnValue('second')); + $info2->expects($this->any()) + ->method('getEtag') + ->will($this->returnValue('def')); + + $this->view->expects($this->once()) + ->method('getDirectoryContent') + ->with('') + ->will($this->returnValue(array($info1, $info2))); + + $this->view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnValue('')); + + $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); + $nodes = $dir->getChildren(); + + $this->assertEquals(2, count($nodes)); + + // calling a second time just returns the cached values, + // does not call getDirectoryContents again + $dir->getChildren(); + } + + /** + * @expectedException \Sabre\DAV\Exception\ServiceUnavailable + */ + public function testGetChildThrowStorageNotAvailableException() { + $this->view->expects($this->once()) + ->method('getFileInfo') + ->willThrowException(new \OCP\Files\StorageNotAvailableException()); + + $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); + $dir->getChild('.'); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\InvalidPath + */ + public function testGetChildThrowInvalidPath() { + $this->view->expects($this->once()) + ->method('verifyPath') + ->willThrowException(new \OCP\Files\InvalidPathException()); + $this->view->expects($this->never()) + ->method('getFileInfo'); + + $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); + $dir->getChild('.'); + } + + public function testGetQuotaInfoUnlimited() { + $storage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Quota') + ->disableOriginalConstructor() + ->getMock(); + + $storage->expects($this->any()) + ->method('instanceOfStorage') + ->will($this->returnValueMap([ + '\OC\Files\Storage\Shared' => false, + '\OC\Files\Storage\Wrapper\Quota' => false, + ])); + + $storage->expects($this->never()) + ->method('getQuota'); + + $storage->expects($this->once()) + ->method('free_space') + ->will($this->returnValue(800)); + + $this->info->expects($this->once()) + ->method('getSize') + ->will($this->returnValue(200)); + + $this->info->expects($this->once()) + ->method('getStorage') + ->will($this->returnValue($storage)); + + $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); + $this->assertEquals([200, -3], $dir->getQuotaInfo()); //200 used, unlimited + } + + public function testGetQuotaInfoSpecific() { + $storage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Quota') + ->disableOriginalConstructor() + ->getMock(); + + $storage->expects($this->any()) + ->method('instanceOfStorage') + ->will($this->returnValueMap([ + ['\OC\Files\Storage\Shared', false], + ['\OC\Files\Storage\Wrapper\Quota', true], + ])); + + $storage->expects($this->once()) + ->method('getQuota') + ->will($this->returnValue(1000)); + + $storage->expects($this->once()) + ->method('free_space') + ->will($this->returnValue(800)); + + $this->info->expects($this->once()) + ->method('getSize') + ->will($this->returnValue(200)); + + $this->info->expects($this->once()) + ->method('getStorage') + ->will($this->returnValue($storage)); + + $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); + $this->assertEquals([200, 800], $dir->getQuotaInfo()); //200 used, 800 free + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php b/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php new file mode 100644 index 00000000000..125cb174c58 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php @@ -0,0 +1,70 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCA\DAV\Connector\Sabre\DummyGetResponsePlugin; +use Test\TestCase; + +/** + * Class DummyGetResponsePluginTest + * + * @package OCA\DAV\Tests\unit\Connector\Sabre + */ +class DummyGetResponsePluginTest extends TestCase { + /** @var DummyGetResponsePlugin */ + private $dummyGetResponsePlugin; + + public function setUp() { + parent::setUp(); + + $this->dummyGetResponsePlugin = new DummyGetResponsePlugin(); + } + + public function testInitialize() { + /** @var \Sabre\DAV\Server $server */ + $server = $this->getMock('\Sabre\DAV\Server'); + $server + ->expects($this->once()) + ->method('on') + ->with('method:GET', [$this->dummyGetResponsePlugin, 'httpGet'], 200); + + $this->dummyGetResponsePlugin->initialize($server); + } + + + public function testHttpGet() { + /** @var \Sabre\HTTP\RequestInterface $request */ + $request = $this->getMock('\Sabre\HTTP\RequestInterface'); + /** @var \Sabre\HTTP\ResponseInterface $response */ + $response = $server = $this->getMock('\Sabre\HTTP\ResponseInterface'); + $response + ->expects($this->once()) + ->method('setBody'); + $response + ->expects($this->once()) + ->method('setStatus') + ->with(200); + + $this->assertSame(false, $this->dummyGetResponsePlugin->httpGet($request, $response)); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php new file mode 100644 index 00000000000..44e9e17b695 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php @@ -0,0 +1,57 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\Exception; + +use OCA\DAV\Connector\Sabre\Exception\Forbidden; + +class ForbiddenTest extends \Test\TestCase { + + public function testSerialization() { + + // create xml doc + $DOM = new \DOMDocument('1.0','utf-8'); + $DOM->formatOutput = true; + $error = $DOM->createElementNS('DAV:','d:error'); + $error->setAttribute('xmlns:s', \Sabre\DAV\Server::NS_SABREDAV); + $DOM->appendChild($error); + + // serialize the exception + $message = "1234567890"; + $retry = false; + $expectedXml = << + + false + 1234567890 + + +EOD; + + $ex = new Forbidden($message, $retry); + $server = $this->getMock('Sabre\DAV\Server'); + $ex->serialize($server, $error); + + // assert + $xml = $DOM->saveXML(); + $this->assertEquals($expectedXml, $xml); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php new file mode 100644 index 00000000000..0e1224f596a --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php @@ -0,0 +1,58 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\Exception; + +use OCA\DAV\Connector\Sabre\Exception\InvalidPath; + +class InvalidPathTest extends \Test\TestCase { + + public function testSerialization() { + + // create xml doc + $DOM = new \DOMDocument('1.0','utf-8'); + $DOM->formatOutput = true; + $error = $DOM->createElementNS('DAV:','d:error'); + $error->setAttribute('xmlns:s', \Sabre\DAV\Server::NS_SABREDAV); + $DOM->appendChild($error); + + // serialize the exception + $message = "1234567890"; + $retry = false; + $expectedXml = << + + false + 1234567890 + + +EOD; + + $ex = new InvalidPath($message, $retry); + $server = $this->getMock('Sabre\DAV\Server'); + $ex->serialize($server, $error); + + // assert + $xml = $DOM->saveXML(); + $this->assertEquals($expectedXml, $xml); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php new file mode 100644 index 00000000000..f6102fa4e9b --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php @@ -0,0 +1,83 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCA\DAV\Connector\Sabre\Exception\InvalidPath; +use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin as PluginToTest; +use OC\Log; +use OCP\ILogger; +use PHPUnit_Framework_MockObject_MockObject; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Server; +use Test\TestCase; + +class TestLogger extends Log { + public $message; + public $level; + + public function __construct($logger = null) { + //disable original constructor + } + + public function log($level, $message, array $context = array()) { + $this->level = $level; + $this->message = $message; + } +} + +class ExceptionLoggerPluginTest extends TestCase { + + /** @var Server */ + private $server; + + /** @var PluginToTest */ + private $plugin; + + /** @var TestLogger | PHPUnit_Framework_MockObject_MockObject */ + private $logger; + + private function init() { + $this->server = new Server(); + $this->logger = new TestLogger(); + $this->plugin = new PluginToTest('unit-test', $this->logger); + $this->plugin->initialize($this->server); + } + + /** + * @dataProvider providesExceptions + */ + public function testLogging($expectedLogLevel, $expectedMessage, $exception) { + $this->init(); + $this->plugin->logException($exception); + + $this->assertEquals($expectedLogLevel, $this->logger->level); + $this->assertStringStartsWith('Exception: {"Message":"' . $expectedMessage, $this->logger->message); + } + + public function providesExceptions() { + return [ + [0, 'HTTP\/1.1 404 Not Found', new NotFound()], + [4, 'HTTP\/1.1 400 This path leads to nowhere', new InvalidPath('This path leads to nowhere')] + ]; + } + +} diff --git a/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php new file mode 100644 index 00000000000..98edfb3c5b4 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php @@ -0,0 +1,174 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCA\DAV\Connector\Sabre\FakeLockerPlugin; +use Sabre\HTTP\Response; +use Test\TestCase; + +/** + * Class FakeLockerPluginTest + * + * @package OCA\DAV\Tests\unit\Connector\Sabre + */ +class FakeLockerPluginTest extends TestCase { + /** @var FakeLockerPlugin */ + private $fakeLockerPlugin; + + public function setUp() { + parent::setUp(); + $this->fakeLockerPlugin = new FakeLockerPlugin(); + } + + public function testInitialize() { + /** @var \Sabre\DAV\Server $server */ + $server = $this->getMock('\Sabre\DAV\Server'); + $server + ->expects($this->at(0)) + ->method('on') + ->with('method:LOCK', [$this->fakeLockerPlugin, 'fakeLockProvider'], 1); + $server + ->expects($this->at(1)) + ->method('on') + ->with('method:UNLOCK', [$this->fakeLockerPlugin, 'fakeUnlockProvider'], 1); + $server + ->expects($this->at(2)) + ->method('on') + ->with('propFind', [$this->fakeLockerPlugin, 'propFind']); + $server + ->expects($this->at(3)) + ->method('on') + ->with('validateTokens', [$this->fakeLockerPlugin, 'validateTokens']); + + $this->fakeLockerPlugin->initialize($server); + } + + public function testGetHTTPMethods() { + $expected = [ + 'LOCK', + 'UNLOCK', + ]; + $this->assertSame($expected, $this->fakeLockerPlugin->getHTTPMethods('Test')); + } + + public function testGetFeatures() { + $expected = [ + 2, + ]; + $this->assertSame($expected, $this->fakeLockerPlugin->getFeatures()); + } + + public function testPropFind() { + $propFind = $this->getMockBuilder('\Sabre\DAV\PropFind') + ->disableOriginalConstructor() + ->getMock(); + $node = $this->getMock('\Sabre\DAV\INode'); + + $propFind->expects($this->at(0)) + ->method('handle') + ->with('{DAV:}supportedlock'); + $propFind->expects($this->at(1)) + ->method('handle') + ->with('{DAV:}lockdiscovery'); + + $this->fakeLockerPlugin->propFind($propFind, $node); + } + + public function tokenDataProvider() { + return [ + [ + [ + [ + 'tokens' => [ + [ + 'token' => 'aToken', + 'validToken' => false, + ], + [], + [ + 'token' => 'opaquelocktoken:asdf', + 'validToken' => false, + ] + ], + ] + ], + [ + [ + 'tokens' => [ + [ + 'token' => 'aToken', + 'validToken' => false, + ], + [], + [ + 'token' => 'opaquelocktoken:asdf', + 'validToken' => true, + ] + ], + ] + ], + ] + ]; + } + + /** + * @dataProvider tokenDataProvider + * @param array $input + * @param array $expected + */ + public function testValidateTokens(array $input, array $expected) { + $request = $this->getMock('\Sabre\HTTP\RequestInterface'); + $this->fakeLockerPlugin->validateTokens($request, $input); + $this->assertSame($expected, $input); + } + + public function testFakeLockProvider() { + $request = $this->getMock('\Sabre\HTTP\RequestInterface'); + $response = new Response(); + $server = $this->getMock('\Sabre\DAV\Server'); + $this->fakeLockerPlugin->initialize($server); + + $request->expects($this->exactly(2)) + ->method('getPath') + ->will($this->returnValue('MyPath')); + + $this->assertSame(false, $this->fakeLockerPlugin->fakeLockProvider($request, $response)); + + $expectedXml = 'MyPathinfinitySecond-1800opaquelocktoken:fe4f7f2437b151fbcb4e9f5c8118c6b1'; + + $this->assertXmlStringEqualsXmlString($expectedXml, $response->getBody()); + } + + public function testFakeUnlockProvider() { + $request = $this->getMock('\Sabre\HTTP\RequestInterface'); + $response = $this->getMock('\Sabre\HTTP\ResponseInterface'); + + $response->expects($this->once()) + ->method('setStatus') + ->with('204'); + $response->expects($this->once()) + ->method('setHeader') + ->with('Content-Length', '0'); + + $this->assertSame(false, $this->fakeLockerPlugin->fakeUnlockProvider($request, $response)); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/FileTest.php b/apps/dav/tests/unit/Connector/Sabre/FileTest.php new file mode 100644 index 00000000000..0f404a6a16c --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/FileTest.php @@ -0,0 +1,987 @@ + + * @author Robin Appelman + * @author Thomas Müller + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OC\Files\Storage\Local; +use OCP\Files\ForbiddenException; +use Test\HookHelper; +use OC\Files\Filesystem; +use OCP\Lock\ILockingProvider; + +/** + * Class File + * + * @group DB + * + * @package OCA\DAV\Tests\unit\Connector\Sabre + */ +class FileTest extends \Test\TestCase { + + /** + * @var string + */ + private $user; + + public function setUp() { + parent::setUp(); + + \OC_Hook::clear(); + + $this->user = $this->getUniqueID('user_'); + $userManager = \OC::$server->getUserManager(); + $userManager->createUser($this->user, 'pass'); + + $this->loginAsUser($this->user); + } + + public function tearDown() { + $userManager = \OC::$server->getUserManager(); + $userManager->get($this->user)->delete(); + unset($_SERVER['HTTP_OC_CHUNKED']); + + parent::tearDown(); + } + + private function getMockStorage() { + $storage = $this->getMock('\OCP\Files\Storage'); + $storage->expects($this->any()) + ->method('getId') + ->will($this->returnValue('home::someuser')); + return $storage; + } + + /** + * @param string $string + */ + private function getStream($string) { + $stream = fopen('php://temp', 'r+'); + fwrite($stream, $string); + fseek($stream, 0); + return $stream; + } + + + public function fopenFailuresProvider() { + return [ + [ + // return false + null, + '\Sabre\Dav\Exception', + false + ], + [ + new \OCP\Files\NotPermittedException(), + 'Sabre\DAV\Exception\Forbidden' + ], + [ + new \OCP\Files\EntityTooLargeException(), + 'OCA\DAV\Connector\Sabre\Exception\EntityTooLarge' + ], + [ + new \OCP\Files\InvalidContentException(), + 'OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType' + ], + [ + new \OCP\Files\InvalidPathException(), + 'Sabre\DAV\Exception\Forbidden' + ], + [ + new \OCP\Files\ForbiddenException('', true), + 'OCA\DAV\Connector\Sabre\Exception\Forbidden' + ], + [ + new \OCP\Files\LockNotAcquiredException('/test.txt', 1), + 'OCA\DAV\Connector\Sabre\Exception\FileLocked' + ], + [ + new \OCP\Lock\LockedException('/test.txt'), + 'OCA\DAV\Connector\Sabre\Exception\FileLocked' + ], + [ + new \OCP\Encryption\Exceptions\GenericEncryptionException(), + 'Sabre\DAV\Exception\ServiceUnavailable' + ], + [ + new \OCP\Files\StorageNotAvailableException(), + 'Sabre\DAV\Exception\ServiceUnavailable' + ], + [ + new \Sabre\DAV\Exception('Generic sabre exception'), + 'Sabre\DAV\Exception', + false + ], + [ + new \Exception('Generic exception'), + 'Sabre\DAV\Exception' + ], + ]; + } + + /** + * @dataProvider fopenFailuresProvider + */ + public function testSimplePutFails($thrownException, $expectedException, $checkPreviousClass = true) { + // setup + $storage = $this->getMock( + '\OC\Files\Storage\Local', + ['fopen'], + [['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]] + ); + \OC\Files\Filesystem::mount($storage, [], $this->user . '/'); + $view = $this->getMock('\OC\Files\View', array('getRelativePath', 'resolvePath'), array()); + $view->expects($this->atLeastOnce()) + ->method('resolvePath') + ->will($this->returnCallback( + function ($path) use ($storage) { + return [$storage, $path]; + } + )); + + if ($thrownException !== null) { + $storage->expects($this->once()) + ->method('fopen') + ->will($this->throwException($thrownException)); + } else { + $storage->expects($this->once()) + ->method('fopen') + ->will($this->returnValue(false)); + } + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnArgument(0)); + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $caughtException = null; + try { + $file->put('test data'); + } catch (\Exception $e) { + $caughtException = $e; + } + + $this->assertInstanceOf($expectedException, $caughtException); + if ($checkPreviousClass) { + $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious()); + } + + $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + } + + /** + * Test putting a file using chunking + * + * @dataProvider fopenFailuresProvider + */ + public function testChunkedPutFails($thrownException, $expectedException, $checkPreviousClass = false) { + // setup + $storage = $this->getMock( + '\OC\Files\Storage\Local', + ['fopen'], + [['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]] + ); + \OC\Files\Filesystem::mount($storage, [], $this->user . '/'); + $view = $this->getMock('\OC\Files\View', ['getRelativePath', 'resolvePath'], []); + $view->expects($this->atLeastOnce()) + ->method('resolvePath') + ->will($this->returnCallback( + function ($path) use ($storage) { + return [$storage, $path]; + } + )); + + if ($thrownException !== null) { + $storage->expects($this->once()) + ->method('fopen') + ->will($this->throwException($thrownException)); + } else { + $storage->expects($this->once()) + ->method('fopen') + ->will($this->returnValue(false)); + } + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnArgument(0)); + + $_SERVER['HTTP_OC_CHUNKED'] = true; + + $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [ + 'permissions' => \OCP\Constants::PERMISSION_ALL + ], null); + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // put first chunk + $file->acquireLock(ILockingProvider::LOCK_SHARED); + $this->assertNull($file->put('test data one')); + $file->releaseLock(ILockingProvider::LOCK_SHARED); + + $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [ + 'permissions' => \OCP\Constants::PERMISSION_ALL + ], null); + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $caughtException = null; + try { + // last chunk + $file->acquireLock(ILockingProvider::LOCK_SHARED); + $file->put('test data two'); + $file->releaseLock(ILockingProvider::LOCK_SHARED); + } catch (\Exception $e) { + $caughtException = $e; + } + + $this->assertInstanceOf($expectedException, $caughtException); + if ($checkPreviousClass) { + $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious()); + } + + $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + } + + /** + * Simulate putting a file to the given path. + * + * @param string $path path to put the file into + * @param string $viewRoot root to use for the view + * + * @return null|string of the PUT operaiton which is usually the etag + */ + private function doPut($path, $viewRoot = null) { + $view = \OC\Files\Filesystem::getView(); + if (!is_null($viewRoot)) { + $view = new \OC\Files\View($viewRoot); + } else { + $viewRoot = '/' . $this->user . '/files'; + } + + $info = new \OC\Files\FileInfo( + $viewRoot . '/' . ltrim($path, '/'), + $this->getMockStorage(), + null, + ['permissions' => \OCP\Constants::PERMISSION_ALL], + null + ); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // beforeMethod locks + $view->lockFile($path, ILockingProvider::LOCK_SHARED); + + $result = $file->put($this->getStream('test data')); + + // afterMethod unlocks + $view->unlockFile($path, ILockingProvider::LOCK_SHARED); + + return $result; + } + + /** + * Test putting a single file + */ + public function testPutSingleFile() { + $this->assertNotEmpty($this->doPut('/foo.txt')); + } + + /** + * Test putting a file using chunking + */ + public function testChunkedPut() { + $_SERVER['HTTP_OC_CHUNKED'] = true; + $this->assertNull($this->doPut('/test.txt-chunking-12345-2-0')); + $this->assertNotEmpty($this->doPut('/test.txt-chunking-12345-2-1')); + } + + /** + * Test that putting a file triggers create hooks + */ + public function testPutSingleFileTriggersHooks() { + HookHelper::setUpHooks(); + + $this->assertNotEmpty($this->doPut('/foo.txt')); + + $this->assertCount(4, HookHelper::$hookCalls); + $this->assertHookCall( + HookHelper::$hookCalls[0], + Filesystem::signal_create, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[1], + Filesystem::signal_write, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[2], + Filesystem::signal_post_create, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[3], + Filesystem::signal_post_write, + '/foo.txt' + ); + } + + /** + * Test that putting a file triggers update hooks + */ + public function testPutOverwriteFileTriggersHooks() { + $view = \OC\Files\Filesystem::getView(); + $view->file_put_contents('/foo.txt', 'some content that will be replaced'); + + HookHelper::setUpHooks(); + + $this->assertNotEmpty($this->doPut('/foo.txt')); + + $this->assertCount(4, HookHelper::$hookCalls); + $this->assertHookCall( + HookHelper::$hookCalls[0], + Filesystem::signal_update, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[1], + Filesystem::signal_write, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[2], + Filesystem::signal_post_update, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[3], + Filesystem::signal_post_write, + '/foo.txt' + ); + } + + /** + * Test that putting a file triggers hooks with the correct path + * if the passed view was chrooted (can happen with public webdav + * where the root is the share root) + */ + public function testPutSingleFileTriggersHooksDifferentRoot() { + $view = \OC\Files\Filesystem::getView(); + $view->mkdir('noderoot'); + + HookHelper::setUpHooks(); + + // happens with public webdav where the view root is the share root + $this->assertNotEmpty($this->doPut('/foo.txt', '/' . $this->user . '/files/noderoot')); + + $this->assertCount(4, HookHelper::$hookCalls); + $this->assertHookCall( + HookHelper::$hookCalls[0], + Filesystem::signal_create, + '/noderoot/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[1], + Filesystem::signal_write, + '/noderoot/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[2], + Filesystem::signal_post_create, + '/noderoot/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[3], + Filesystem::signal_post_write, + '/noderoot/foo.txt' + ); + } + + /** + * Test that putting a file with chunks triggers create hooks + */ + public function testPutChunkedFileTriggersHooks() { + HookHelper::setUpHooks(); + + $_SERVER['HTTP_OC_CHUNKED'] = true; + $this->assertNull($this->doPut('/foo.txt-chunking-12345-2-0')); + $this->assertNotEmpty($this->doPut('/foo.txt-chunking-12345-2-1')); + + $this->assertCount(4, HookHelper::$hookCalls); + $this->assertHookCall( + HookHelper::$hookCalls[0], + Filesystem::signal_create, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[1], + Filesystem::signal_write, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[2], + Filesystem::signal_post_create, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[3], + Filesystem::signal_post_write, + '/foo.txt' + ); + } + + /** + * Test that putting a chunked file triggers update hooks + */ + public function testPutOverwriteChunkedFileTriggersHooks() { + $view = \OC\Files\Filesystem::getView(); + $view->file_put_contents('/foo.txt', 'some content that will be replaced'); + + HookHelper::setUpHooks(); + + $_SERVER['HTTP_OC_CHUNKED'] = true; + $this->assertNull($this->doPut('/foo.txt-chunking-12345-2-0')); + $this->assertNotEmpty($this->doPut('/foo.txt-chunking-12345-2-1')); + + $this->assertCount(4, HookHelper::$hookCalls); + $this->assertHookCall( + HookHelper::$hookCalls[0], + Filesystem::signal_update, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[1], + Filesystem::signal_write, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[2], + Filesystem::signal_post_update, + '/foo.txt' + ); + $this->assertHookCall( + HookHelper::$hookCalls[3], + Filesystem::signal_post_write, + '/foo.txt' + ); + } + + public static function cancellingHook($params) { + self::$hookCalls[] = array( + 'signal' => Filesystem::signal_post_create, + 'params' => $params + ); + } + + /** + * Test put file with cancelled hook + */ + public function testPutSingleFileCancelPreHook() { + \OCP\Util::connectHook( + Filesystem::CLASSNAME, + Filesystem::signal_create, + '\Test\HookHelper', + 'cancellingCallback' + ); + + // action + $thrown = false; + try { + $this->doPut('/foo.txt'); + } catch (\Sabre\DAV\Exception $e) { + $thrown = true; + } + + $this->assertTrue($thrown); + $this->assertEmpty($this->listPartFiles(), 'No stray part files'); + } + + /** + * Test exception when the uploaded size did not match + */ + public function testSimplePutFailsSizeCheck() { + // setup + $view = $this->getMock('\OC\Files\View', + array('rename', 'getRelativePath', 'filesize')); + $view->expects($this->any()) + ->method('rename') + ->withAnyParameters() + ->will($this->returnValue(false)); + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnArgument(0)); + + $view->expects($this->any()) + ->method('filesize') + ->will($this->returnValue(123456)); + + $_SERVER['CONTENT_LENGTH'] = 123456; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $thrown = false; + try { + // beforeMethod locks + $file->acquireLock(ILockingProvider::LOCK_SHARED); + + $file->put($this->getStream('test data')); + + // afterMethod unlocks + $file->releaseLock(ILockingProvider::LOCK_SHARED); + } catch (\Sabre\DAV\Exception\BadRequest $e) { + $thrown = true; + } + + $this->assertTrue($thrown); + $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + } + + /** + * Test exception during final rename in simple upload mode + */ + public function testSimplePutFailsMoveFromStorage() { + $view = new \OC\Files\View('/' . $this->user . '/files'); + + // simulate situation where the target file is locked + $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE); + + $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $thrown = false; + try { + // beforeMethod locks + $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED); + + $file->put($this->getStream('test data')); + + // afterMethod unlocks + $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); + } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { + $thrown = true; + } + + $this->assertTrue($thrown); + $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + } + + /** + * Test exception during final rename in chunk upload mode + */ + public function testChunkedPutFailsFinalRename() { + $view = new \OC\Files\View('/' . $this->user . '/files'); + + // simulate situation where the target file is locked + $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE); + + $_SERVER['HTTP_OC_CHUNKED'] = true; + + $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [ + 'permissions' => \OCP\Constants::PERMISSION_ALL + ], null); + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file->acquireLock(ILockingProvider::LOCK_SHARED); + $this->assertNull($file->put('test data one')); + $file->releaseLock(ILockingProvider::LOCK_SHARED); + + $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [ + 'permissions' => \OCP\Constants::PERMISSION_ALL + ], null); + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $thrown = false; + try { + $file->acquireLock(ILockingProvider::LOCK_SHARED); + $file->put($this->getStream('test data')); + $file->releaseLock(ILockingProvider::LOCK_SHARED); + } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { + $thrown = true; + } + + $this->assertTrue($thrown); + $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + } + + /** + * Test put file with invalid chars + */ + public function testSimplePutInvalidChars() { + // setup + $view = $this->getMock('\OC\Files\View', array('getRelativePath')); + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnArgument(0)); + + $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $thrown = false; + try { + // beforeMethod locks + $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED); + + $file->put($this->getStream('test data')); + + // afterMethod unlocks + $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); + } catch (\OCA\DAV\Connector\Sabre\Exception\InvalidPath $e) { + $thrown = true; + } + + $this->assertTrue($thrown); + $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + } + + /** + * Test setting name with setName() with invalid chars + * + * @expectedException \OCA\DAV\Connector\Sabre\Exception\InvalidPath + */ + public function testSetNameInvalidChars() { + // setup + $view = $this->getMock('\OC\Files\View', array('getRelativePath')); + + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnArgument(0)); + + $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file->setName('/super*star.txt'); + } + + /** + */ + public function testUploadAbort() { + // setup + $view = $this->getMock('\OC\Files\View', + array('rename', 'getRelativePath', 'filesize')); + $view->expects($this->any()) + ->method('rename') + ->withAnyParameters() + ->will($this->returnValue(false)); + $view->expects($this->any()) + ->method('getRelativePath') + ->will($this->returnArgument(0)); + $view->expects($this->any()) + ->method('filesize') + ->will($this->returnValue(123456)); + + $_SERVER['CONTENT_LENGTH'] = 12345; + $_SERVER['REQUEST_METHOD'] = 'PUT'; + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $thrown = false; + try { + // beforeMethod locks + $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED); + + $file->put($this->getStream('test data')); + + // afterMethod unlocks + $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); + } catch (\Sabre\DAV\Exception\BadRequest $e) { + $thrown = true; + } + + $this->assertTrue($thrown); + $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + } + + /** + * + */ + public function testDeleteWhenAllowed() { + // setup + $view = $this->getMock('\OC\Files\View', + array()); + + $view->expects($this->once()) + ->method('unlink') + ->will($this->returnValue(true)); + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $file->delete(); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDeleteThrowsWhenDeletionNotAllowed() { + // setup + $view = $this->getMock('\OC\Files\View', + array()); + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => 0 + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $file->delete(); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testDeleteThrowsWhenDeletionFailed() { + // setup + $view = $this->getMock('\OC\Files\View', + array()); + + // but fails + $view->expects($this->once()) + ->method('unlink') + ->will($this->returnValue(false)); + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $file->delete(); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\Forbidden + */ + public function testDeleteThrowsWhenDeletionThrows() { + // setup + $view = $this->getMock('\OC\Files\View', + array()); + + // but fails + $view->expects($this->once()) + ->method('unlink') + ->willThrowException(new ForbiddenException('', true)); + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + // action + $file->delete(); + } + + /** + * Asserts hook call + * + * @param array $callData hook call data to check + * @param string $signal signal name + * @param string $hookPath hook path + */ + protected function assertHookCall($callData, $signal, $hookPath) { + $this->assertEquals($signal, $callData['signal']); + $params = $callData['params']; + $this->assertEquals( + $hookPath, + $params[Filesystem::signal_param_path] + ); + } + + /** + * Test whether locks are set before and after the operation + */ + public function testPutLocking() { + $view = new \OC\Files\View('/' . $this->user . '/files/'); + + $path = 'test-locking.txt'; + $info = new \OC\Files\FileInfo( + '/' . $this->user . '/files/' . $path, + $this->getMockStorage(), + null, + ['permissions' => \OCP\Constants::PERMISSION_ALL], + null + ); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + $this->assertFalse( + $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED), + 'File unlocked before put' + ); + $this->assertFalse( + $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE), + 'File unlocked before put' + ); + + $wasLockedPre = false; + $wasLockedPost = false; + $eventHandler = $this->getMockBuilder('\stdclass') + ->setMethods(['writeCallback', 'postWriteCallback']) + ->getMock(); + + // both pre and post hooks might need access to the file, + // so only shared lock is acceptable + $eventHandler->expects($this->once()) + ->method('writeCallback') + ->will($this->returnCallback( + function () use ($view, $path, &$wasLockedPre) { + $wasLockedPre = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED); + $wasLockedPre = $wasLockedPre && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE); + } + )); + $eventHandler->expects($this->once()) + ->method('postWriteCallback') + ->will($this->returnCallback( + function () use ($view, $path, &$wasLockedPost) { + $wasLockedPost = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED); + $wasLockedPost = $wasLockedPost && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE); + } + )); + + \OCP\Util::connectHook( + Filesystem::CLASSNAME, + Filesystem::signal_write, + $eventHandler, + 'writeCallback' + ); + \OCP\Util::connectHook( + Filesystem::CLASSNAME, + Filesystem::signal_post_write, + $eventHandler, + 'postWriteCallback' + ); + + // beforeMethod locks + $view->lockFile($path, ILockingProvider::LOCK_SHARED); + + $this->assertNotEmpty($file->put($this->getStream('test data'))); + + // afterMethod unlocks + $view->unlockFile($path, ILockingProvider::LOCK_SHARED); + + $this->assertTrue($wasLockedPre, 'File was locked during pre-hooks'); + $this->assertTrue($wasLockedPost, 'File was locked during post-hooks'); + + $this->assertFalse( + $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED), + 'File unlocked after put' + ); + $this->assertFalse( + $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE), + 'File unlocked after put' + ); + } + + /** + * Returns part files in the given path + * + * @param \OC\Files\View view which root is the current user's "files" folder + * @param string $path path for which to list part files + * + * @return array list of part files + */ + private function listPartFiles(\OC\Files\View $userView = null, $path = '') { + if ($userView === null) { + $userView = \OC\Files\Filesystem::getView(); + } + $files = []; + list($storage, $internalPath) = $userView->resolvePath($path); + if($storage instanceof Local) { + $realPath = $storage->getSourcePath($internalPath); + $dh = opendir($realPath); + while (($file = readdir($dh)) !== false) { + if (substr($file, strlen($file) - 5, 5) === '.part') { + $files[] = $file; + } + } + closedir($dh); + } + return $files; + } + + /** + * @expectedException \Sabre\DAV\Exception\ServiceUnavailable + */ + public function testGetFopenFails() { + $view = $this->getMock('\OC\Files\View', ['fopen'], array()); + $view->expects($this->atLeastOnce()) + ->method('fopen') + ->will($this->returnValue(false)); + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + $file->get(); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\Forbidden + */ + public function testGetFopenThrows() { + $view = $this->getMock('\OC\Files\View', ['fopen'], array()); + $view->expects($this->atLeastOnce()) + ->method('fopen') + ->willThrowException(new ForbiddenException('', true)); + + $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( + 'permissions' => \OCP\Constants::PERMISSION_ALL + ), null); + + $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + + $file->get(); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php new file mode 100644 index 00000000000..5a944e74fca --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php @@ -0,0 +1,469 @@ + + * @author Thomas Müller + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCP\Files\StorageNotAvailableException; +use Sabre\DAV\PropFind; +use Sabre\DAV\PropPatch; +use Test\TestCase; + +/** + * Copyright (c) 2015 Vincent Petry + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +class FilesPluginTest extends TestCase { + const GETETAG_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::GETETAG_PROPERTYNAME; + const FILEID_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::FILEID_PROPERTYNAME; + const INTERNAL_FILEID_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::INTERNAL_FILEID_PROPERTYNAME; + const SIZE_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::SIZE_PROPERTYNAME; + const PERMISSIONS_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::PERMISSIONS_PROPERTYNAME; + const LASTMODIFIED_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::LASTMODIFIED_PROPERTYNAME; + const DOWNLOADURL_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::DOWNLOADURL_PROPERTYNAME; + const OWNER_ID_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::OWNER_ID_PROPERTYNAME; + const OWNER_DISPLAY_NAME_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::OWNER_DISPLAY_NAME_PROPERTYNAME; + const DATA_FINGERPRINT_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::DATA_FINGERPRINT_PROPERTYNAME; + + /** + * @var \Sabre\DAV\Server | \PHPUnit_Framework_MockObject_MockObject + */ + private $server; + + /** + * @var \Sabre\DAV\Tree | \PHPUnit_Framework_MockObject_MockObject + */ + private $tree; + + /** + * @var \OCA\DAV\Connector\Sabre\FilesPlugin + */ + private $plugin; + + /** + * @var \OC\Files\View | \PHPUnit_Framework_MockObject_MockObject + */ + private $view; + + /** + * @var \OCP\IConfig | \PHPUnit_Framework_MockObject_MockObject + */ + private $config; + + public function setUp() { + parent::setUp(); + $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + ->disableOriginalConstructor() + ->getMock(); + $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + ->disableOriginalConstructor() + ->getMock(); + $this->view = $this->getMockBuilder('\OC\Files\View') + ->disableOriginalConstructor() + ->getMock(); + $this->config = $this->getMock('\OCP\IConfig'); + $this->config->method('getSystemValue') + ->with($this->equalTo('data-fingerprint'), $this->equalTo('')) + ->willReturn('my_fingerprint'); + + $this->plugin = new \OCA\DAV\Connector\Sabre\FilesPlugin( + $this->tree, + $this->view, + $this->config + ); + $this->plugin->initialize($this->server); + } + + /** + * @param string $class + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function createTestNode($class) { + $node = $this->getMockBuilder($class) + ->disableOriginalConstructor() + ->getMock(); + + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->returnValue($node)); + + $node->expects($this->any()) + ->method('getFileId') + ->will($this->returnValue('00000123instanceid')); + $node->expects($this->any()) + ->method('getInternalFileId') + ->will($this->returnValue('123')); + $node->expects($this->any()) + ->method('getEtag') + ->will($this->returnValue('"abc"')); + $node->expects($this->any()) + ->method('getDavPermissions') + ->will($this->returnValue('DWCKMSR')); + + return $node; + } + + public function testGetPropertiesForFile() { + /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit_Framework_MockObject_MockObject $node */ + $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + + $propFind = new PropFind( + '/dummyPath', + array( + self::GETETAG_PROPERTYNAME, + self::FILEID_PROPERTYNAME, + self::INTERNAL_FILEID_PROPERTYNAME, + self::SIZE_PROPERTYNAME, + self::PERMISSIONS_PROPERTYNAME, + self::DOWNLOADURL_PROPERTYNAME, + self::OWNER_ID_PROPERTYNAME, + self::OWNER_DISPLAY_NAME_PROPERTYNAME, + self::DATA_FINGERPRINT_PROPERTYNAME, + ), + 0 + ); + + $user = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $user + ->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('foo')); + $user + ->expects($this->once()) + ->method('getDisplayName') + ->will($this->returnValue('M. Foo')); + + $node->expects($this->once()) + ->method('getDirectDownload') + ->will($this->returnValue(array('url' => 'http://example.com/'))); + $node->expects($this->exactly(2)) + ->method('getOwner') + ->will($this->returnValue($user)); + $node->expects($this->never()) + ->method('getSize'); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + + $this->assertEquals('"abc"', $propFind->get(self::GETETAG_PROPERTYNAME)); + $this->assertEquals('00000123instanceid', $propFind->get(self::FILEID_PROPERTYNAME)); + $this->assertEquals('123', $propFind->get(self::INTERNAL_FILEID_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::SIZE_PROPERTYNAME)); + $this->assertEquals('DWCKMSR', $propFind->get(self::PERMISSIONS_PROPERTYNAME)); + $this->assertEquals('http://example.com/', $propFind->get(self::DOWNLOADURL_PROPERTYNAME)); + $this->assertEquals('foo', $propFind->get(self::OWNER_ID_PROPERTYNAME)); + $this->assertEquals('M. Foo', $propFind->get(self::OWNER_DISPLAY_NAME_PROPERTYNAME)); + $this->assertEquals([self::SIZE_PROPERTYNAME, self::DATA_FINGERPRINT_PROPERTYNAME], $propFind->get404Properties()); + } + + public function testGetPropertiesForFileHome() { + /** @var \OCA\DAV\Files\FilesHome | \PHPUnit_Framework_MockObject_MockObject $node */ + $node = $this->getMockBuilder('\OCA\DAV\Files\FilesHome') + ->disableOriginalConstructor() + ->getMock(); + + $propFind = new PropFind( + '/dummyPath', + array( + self::GETETAG_PROPERTYNAME, + self::FILEID_PROPERTYNAME, + self::INTERNAL_FILEID_PROPERTYNAME, + self::SIZE_PROPERTYNAME, + self::PERMISSIONS_PROPERTYNAME, + self::DOWNLOADURL_PROPERTYNAME, + self::OWNER_ID_PROPERTYNAME, + self::OWNER_DISPLAY_NAME_PROPERTYNAME, + self::DATA_FINGERPRINT_PROPERTYNAME, + ), + 0 + ); + + $user = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $user->expects($this->never())->method('getUID'); + $user->expects($this->never())->method('getDisplayName'); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + + $this->assertEquals(null, $propFind->get(self::GETETAG_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::FILEID_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::INTERNAL_FILEID_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::SIZE_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::PERMISSIONS_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::DOWNLOADURL_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::OWNER_ID_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::OWNER_DISPLAY_NAME_PROPERTYNAME)); + $this->assertEquals(['{DAV:}getetag', + '{http://owncloud.org/ns}id', + '{http://owncloud.org/ns}fileid', + '{http://owncloud.org/ns}size', + '{http://owncloud.org/ns}permissions', + '{http://owncloud.org/ns}downloadURL', + '{http://owncloud.org/ns}owner-id', + '{http://owncloud.org/ns}owner-display-name' + ], $propFind->get404Properties()); + $this->assertEquals('my_fingerprint', $propFind->get(self::DATA_FINGERPRINT_PROPERTYNAME)); + } + + public function testGetPropertiesStorageNotAvailable() { + /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit_Framework_MockObject_MockObject $node */ + $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + + $propFind = new PropFind( + '/dummyPath', + array( + self::DOWNLOADURL_PROPERTYNAME, + ), + 0 + ); + + $node->expects($this->once()) + ->method('getDirectDownload') + ->will($this->throwException(new StorageNotAvailableException())); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + + $this->assertEquals(null, $propFind->get(self::DOWNLOADURL_PROPERTYNAME)); + } + + public function testGetPublicPermissions() { + $this->plugin = new \OCA\DAV\Connector\Sabre\FilesPlugin( + $this->tree, + $this->view, + $this->config, + true); + $this->plugin->initialize($this->server); + + $propFind = new PropFind( + '/dummyPath', + [ + self::PERMISSIONS_PROPERTYNAME, + ], + 0 + ); + + /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit_Framework_MockObject_MockObject $node */ + $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + $node->expects($this->any()) + ->method('getDavPermissions') + ->will($this->returnValue('DWCKMSR')); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + + $this->assertEquals('DWCKR', $propFind->get(self::PERMISSIONS_PROPERTYNAME)); + } + + public function testGetPropertiesForDirectory() { + /** @var \OCA\DAV\Connector\Sabre\Directory | \PHPUnit_Framework_MockObject_MockObject $node */ + $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\Directory'); + + $propFind = new PropFind( + '/dummyPath', + array( + self::GETETAG_PROPERTYNAME, + self::FILEID_PROPERTYNAME, + self::SIZE_PROPERTYNAME, + self::PERMISSIONS_PROPERTYNAME, + self::DOWNLOADURL_PROPERTYNAME, + self::DATA_FINGERPRINT_PROPERTYNAME, + ), + 0 + ); + + $node->expects($this->once()) + ->method('getSize') + ->will($this->returnValue(1025)); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + + $this->assertEquals('"abc"', $propFind->get(self::GETETAG_PROPERTYNAME)); + $this->assertEquals('00000123instanceid', $propFind->get(self::FILEID_PROPERTYNAME)); + $this->assertEquals(1025, $propFind->get(self::SIZE_PROPERTYNAME)); + $this->assertEquals('DWCKMSR', $propFind->get(self::PERMISSIONS_PROPERTYNAME)); + $this->assertEquals(null, $propFind->get(self::DOWNLOADURL_PROPERTYNAME)); + $this->assertEquals([self::DOWNLOADURL_PROPERTYNAME, self::DATA_FINGERPRINT_PROPERTYNAME], $propFind->get404Properties()); + } + + public function testGetPropertiesForRootDirectory() { + /** @var \OCA\DAV\Connector\Sabre\Directory | \PHPUnit_Framework_MockObject_MockObject $node */ + $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $node->method('getPath')->willReturn('/'); + + $propFind = new PropFind( + '/', + [ + self::DATA_FINGERPRINT_PROPERTYNAME, + ], + 0 + ); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + + $this->assertEquals('my_fingerprint', $propFind->get(self::DATA_FINGERPRINT_PROPERTYNAME)); + } + + public function testUpdateProps() { + $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + + $testDate = 'Fri, 13 Feb 2015 00:01:02 GMT'; + + $node->expects($this->once()) + ->method('touch') + ->with($testDate); + + $node->expects($this->once()) + ->method('setEtag') + ->with('newetag') + ->will($this->returnValue(true)); + + // properties to set + $propPatch = new PropPatch(array( + self::GETETAG_PROPERTYNAME => 'newetag', + self::LASTMODIFIED_PROPERTYNAME => $testDate + )); + + $this->plugin->handleUpdateProperties( + '/dummypath', + $propPatch + ); + + $propPatch->commit(); + + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertEquals(200, $result[self::LASTMODIFIED_PROPERTYNAME]); + $this->assertEquals(200, $result[self::GETETAG_PROPERTYNAME]); + } + + public function testUpdatePropsForbidden() { + $propPatch = new PropPatch(array( + self::OWNER_ID_PROPERTYNAME => 'user2', + self::OWNER_DISPLAY_NAME_PROPERTYNAME => 'User Two', + self::FILEID_PROPERTYNAME => 12345, + self::PERMISSIONS_PROPERTYNAME => 'C', + self::SIZE_PROPERTYNAME => 123, + self::DOWNLOADURL_PROPERTYNAME => 'http://example.com/', + )); + + $this->plugin->handleUpdateProperties( + '/dummypath', + $propPatch + ); + + $propPatch->commit(); + + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertEquals(403, $result[self::OWNER_ID_PROPERTYNAME]); + $this->assertEquals(403, $result[self::OWNER_DISPLAY_NAME_PROPERTYNAME]); + $this->assertEquals(403, $result[self::FILEID_PROPERTYNAME]); + $this->assertEquals(403, $result[self::PERMISSIONS_PROPERTYNAME]); + $this->assertEquals(403, $result[self::SIZE_PROPERTYNAME]); + $this->assertEquals(403, $result[self::DOWNLOADURL_PROPERTYNAME]); + } + + /** + * Testcase from https://github.com/owncloud/core/issues/5251 + * + * |-FolderA + * |-text.txt + * |-test.txt + * + * FolderA is an incoming shared folder and there are no delete permissions. + * Thus moving /FolderA/test.txt to /test.txt should fail already on that check + * + * @expectedException \Sabre\DAV\Exception\Forbidden + * @expectedExceptionMessage FolderA/test.txt cannot be deleted + */ + public function testMoveSrcNotDeletable() { + $fileInfoFolderATestTXT = $this->getMockBuilder('\OCP\Files\FileInfo') + ->disableOriginalConstructor() + ->getMock(); + $fileInfoFolderATestTXT->expects($this->once()) + ->method('isDeletable') + ->willReturn(false); + + $this->view->expects($this->once()) + ->method('getFileInfo') + ->with('FolderA/test.txt') + ->willReturn($fileInfoFolderATestTXT); + + $this->plugin->checkMove('FolderA/test.txt', 'test.txt'); + } + + public function testMoveSrcDeletable() { + $fileInfoFolderATestTXT = $this->getMockBuilder('\OCP\Files\FileInfo') + ->disableOriginalConstructor() + ->getMock(); + $fileInfoFolderATestTXT->expects($this->once()) + ->method('isDeletable') + ->willReturn(true); + + $this->view->expects($this->once()) + ->method('getFileInfo') + ->with('FolderA/test.txt') + ->willReturn($fileInfoFolderATestTXT); + + $this->plugin->checkMove('FolderA/test.txt', 'test.txt'); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotFound + * @expectedExceptionMessage FolderA/test.txt does not exist + */ + public function testMoveSrcNotExist() { + $this->view->expects($this->once()) + ->method('getFileInfo') + ->with('FolderA/test.txt') + ->willReturn(false); + + $this->plugin->checkMove('FolderA/test.txt', 'test.txt'); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php new file mode 100644 index 00000000000..d5bbbbcc99d --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php @@ -0,0 +1,611 @@ + + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCA\DAV\Connector\Sabre\FilesReportPlugin as FilesReportPluginImplementation; +use Sabre\DAV\Exception\NotFound; +use OCP\SystemTag\ISystemTagObjectMapper; +use OC\Files\View; +use OCP\Files\Folder; +use OCP\IGroupManager; +use OCP\SystemTag\ISystemTagManager; + +class FilesReportPluginTest extends \Test\TestCase { + /** @var \Sabre\DAV\Server|\PHPUnit_Framework_MockObject_MockObject */ + private $server; + + /** @var \Sabre\DAV\Tree|\PHPUnit_Framework_MockObject_MockObject */ + private $tree; + + /** @var ISystemTagObjectMapper|\PHPUnit_Framework_MockObject_MockObject */ + private $tagMapper; + + /** @var ISystemTagManager|\PHPUnit_Framework_MockObject_MockObject */ + private $tagManager; + + /** @var \OCP\IUserSession */ + private $userSession; + + /** @var FilesReportPluginImplementation */ + private $plugin; + + /** @var View|\PHPUnit_Framework_MockObject_MockObject **/ + private $view; + + /** @var IGroupManager|\PHPUnit_Framework_MockObject_MockObject **/ + private $groupManager; + + /** @var Folder|\PHPUnit_Framework_MockObject_MockObject **/ + private $userFolder; + + public function setUp() { + parent::setUp(); + $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + ->disableOriginalConstructor() + ->getMock(); + + $this->view = $this->getMockBuilder('\OC\Files\View') + ->disableOriginalConstructor() + ->getMock(); + + $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + ->setConstructorArgs([$this->tree]) + ->setMethods(['getRequestUri']) + ->getMock(); + + $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') + ->disableOriginalConstructor() + ->getMock(); + + $this->userFolder = $this->getMockBuilder('\OCP\Files\Folder') + ->disableOriginalConstructor() + ->getMock(); + + $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); + $this->tagMapper = $this->getMock('\OCP\SystemTag\ISystemTagObjectMapper'); + $this->userSession = $this->getMock('\OCP\IUserSession'); + + $user = $this->getMock('\OCP\IUser'); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('testuser')); + $this->userSession->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->plugin = new FilesReportPluginImplementation( + $this->tree, + $this->view, + $this->tagManager, + $this->tagMapper, + $this->userSession, + $this->groupManager, + $this->userFolder + ); + } + + /** + * @expectedException \Sabre\DAV\Exception\ReportNotSupported + */ + public function testOnReportInvalidNode() { + $path = 'totally/unrelated/13'; + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($this->getMock('\Sabre\DAV\INode'))); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->onReport(FilesReportPluginImplementation::REPORT_NAME, [], '/' . $path); + } + + /** + * @expectedException \Sabre\DAV\Exception\ReportNotSupported + */ + public function testOnReportInvalidReportName() { + $path = 'test'; + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($this->getMock('\Sabre\DAV\INode'))); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->plugin->initialize($this->server); + + $this->plugin->onReport('{whoever}whatever', [], '/' . $path); + } + + public function testOnReport() { + $path = 'test'; + + $parameters = [ + [ + 'name' => '{DAV:}prop', + 'value' => [ + ['name' => '{DAV:}getcontentlength', 'value' => ''], + ['name' => '{http://owncloud.org/ns}size', 'value' => ''], + ], + ], + [ + 'name' => '{http://owncloud.org/ns}filter-rules', + 'value' => [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], + ], + ], + ]; + + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(true)); + + $this->tagMapper->expects($this->at(0)) + ->method('getObjectIdsForTags') + ->with('123', 'files') + ->will($this->returnValue(['111', '222'])); + $this->tagMapper->expects($this->at(1)) + ->method('getObjectIdsForTags') + ->with('456', 'files') + ->will($this->returnValue(['111', '222', '333'])); + + $reportTargetNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $response->expects($this->once()) + ->method('setHeader') + ->with('Content-Type', 'application/xml; charset=utf-8'); + + $response->expects($this->once()) + ->method('setStatus') + ->with(207); + + $response->expects($this->once()) + ->method('setBody'); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/' . $path) + ->will($this->returnValue($reportTargetNode)); + + $filesNode1 = $this->getMockBuilder('\OCP\Files\Folder') + ->disableOriginalConstructor() + ->getMock(); + $filesNode2 = $this->getMockBuilder('\OCP\Files\File') + ->disableOriginalConstructor() + ->getMock(); + + $this->userFolder->expects($this->at(0)) + ->method('getById') + ->with('111') + ->will($this->returnValue([$filesNode1])); + $this->userFolder->expects($this->at(1)) + ->method('getById') + ->with('222') + ->will($this->returnValue([$filesNode2])); + + $this->server->expects($this->any()) + ->method('getRequestUri') + ->will($this->returnValue($path)); + $this->server->httpResponse = $response; + $this->plugin->initialize($this->server); + + $this->plugin->onReport(FilesReportPluginImplementation::REPORT_NAME, $parameters, '/' . $path); + } + + public function testFindNodesByFileIdsRoot() { + $filesNode1 = $this->getMockBuilder('\OCP\Files\Folder') + ->disableOriginalConstructor() + ->getMock(); + $filesNode1->expects($this->once()) + ->method('getName') + ->will($this->returnValue('first node')); + + $filesNode2 = $this->getMockBuilder('\OCP\Files\File') + ->disableOriginalConstructor() + ->getMock(); + $filesNode2->expects($this->once()) + ->method('getName') + ->will($this->returnValue('second node')); + + $reportTargetNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $reportTargetNode->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/')); + + $this->userFolder->expects($this->at(0)) + ->method('getById') + ->with('111') + ->will($this->returnValue([$filesNode1])); + $this->userFolder->expects($this->at(1)) + ->method('getById') + ->with('222') + ->will($this->returnValue([$filesNode2])); + + /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit_Framework_MockObject_MockObject $reportTargetNode */ + $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); + + $this->assertCount(2, $result); + $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\Directory', $result[0]); + $this->assertEquals('first node', $result[0]->getName()); + $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\File', $result[1]); + $this->assertEquals('second node', $result[1]->getName()); + } + + public function testFindNodesByFileIdsSubDir() { + $filesNode1 = $this->getMockBuilder('\OCP\Files\Folder') + ->disableOriginalConstructor() + ->getMock(); + $filesNode1->expects($this->once()) + ->method('getName') + ->will($this->returnValue('first node')); + + $filesNode2 = $this->getMockBuilder('\OCP\Files\File') + ->disableOriginalConstructor() + ->getMock(); + $filesNode2->expects($this->once()) + ->method('getName') + ->will($this->returnValue('second node')); + + $reportTargetNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $reportTargetNode->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/sub1/sub2')); + + + $subNode = $this->getMockBuilder('\OCP\Files\Folder') + ->disableOriginalConstructor() + ->getMock(); + + $this->userFolder->expects($this->at(0)) + ->method('get') + ->with('/sub1/sub2') + ->will($this->returnValue($subNode)); + + $subNode->expects($this->at(0)) + ->method('getById') + ->with('111') + ->will($this->returnValue([$filesNode1])); + $subNode->expects($this->at(1)) + ->method('getById') + ->with('222') + ->will($this->returnValue([$filesNode2])); + + /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit_Framework_MockObject_MockObject $reportTargetNode */ + $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); + + $this->assertCount(2, $result); + $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\Directory', $result[0]); + $this->assertEquals('first node', $result[0]->getName()); + $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\File', $result[1]); + $this->assertEquals('second node', $result[1]->getName()); + } + + public function testPrepareResponses() { + $requestedProps = ['{DAV:}getcontentlength', '{http://owncloud.org/ns}fileid', '{DAV:}resourcetype']; + + $node1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $node2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + ->disableOriginalConstructor() + ->getMock(); + + $node1->expects($this->once()) + ->method('getInternalFileId') + ->will($this->returnValue('111')); + $node2->expects($this->once()) + ->method('getInternalFileId') + ->will($this->returnValue('222')); + $node2->expects($this->once()) + ->method('getSize') + ->will($this->returnValue(1024)); + + $config = $this->getMock('\OCP\IConfig'); + + $this->server->addPlugin( + new \OCA\DAV\Connector\Sabre\FilesPlugin( + $this->tree, + $this->view, + $config + ) + ); + $this->plugin->initialize($this->server); + $responses = $this->plugin->prepareResponses($requestedProps, [$node1, $node2]); + + $this->assertCount(2, $responses); + + $this->assertEquals(200, $responses[0]->getHttpStatus()); + $this->assertEquals(200, $responses[1]->getHttpStatus()); + + $props1 = $responses[0]->getResponseProperties(); + $this->assertEquals('111', $props1[200]['{http://owncloud.org/ns}fileid']); + $this->assertNull($props1[404]['{DAV:}getcontentlength']); + $this->assertInstanceOf('\Sabre\DAV\Xml\Property\ResourceType', $props1[200]['{DAV:}resourcetype']); + $resourceType1 = $props1[200]['{DAV:}resourcetype']->getValue(); + $this->assertEquals('{DAV:}collection', $resourceType1[0]); + + $props2 = $responses[1]->getResponseProperties(); + $this->assertEquals('1024', $props2[200]['{DAV:}getcontentlength']); + $this->assertEquals('222', $props2[200]['{http://owncloud.org/ns}fileid']); + $this->assertInstanceOf('\Sabre\DAV\Xml\Property\ResourceType', $props2[200]['{DAV:}resourcetype']); + $this->assertCount(0, $props2[200]['{DAV:}resourcetype']->getValue()); + } + + public function testProcessFilterRulesSingle() { + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(true)); + + $this->tagMapper->expects($this->exactly(1)) + ->method('getObjectIdsForTags') + ->withConsecutive( + ['123', 'files'] + ) + ->willReturnMap([ + ['123', 'files', 0, '', ['111', '222']], + ]); + + $rules = [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ]; + + $this->assertEquals(['111', '222'], $this->invokePrivate($this->plugin, 'processFilterRules', [$rules])); + } + + public function testProcessFilterRulesAndCondition() { + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(true)); + + $this->tagMapper->expects($this->exactly(2)) + ->method('getObjectIdsForTags') + ->withConsecutive( + ['123', 'files'], + ['456', 'files'] + ) + ->willReturnMap([ + ['123', 'files', 0, '', ['111', '222']], + ['456', 'files', 0, '', ['222', '333']], + ]); + + $rules = [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], + ]; + + $this->assertEquals(['222'], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + } + + public function testProcessFilterRulesAndConditionWithOneEmptyResult() { + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(true)); + + $this->tagMapper->expects($this->exactly(2)) + ->method('getObjectIdsForTags') + ->withConsecutive( + ['123', 'files'], + ['456', 'files'] + ) + ->willReturnMap([ + ['123', 'files', 0, '', ['111', '222']], + ['456', 'files', 0, '', []], + ]); + + $rules = [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], + ]; + + $this->assertEquals([], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + } + + public function testProcessFilterRulesAndConditionWithFirstEmptyResult() { + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(true)); + + $this->tagMapper->expects($this->exactly(1)) + ->method('getObjectIdsForTags') + ->withConsecutive( + ['123', 'files'], + ['456', 'files'] + ) + ->willReturnMap([ + ['123', 'files', 0, '', []], + ['456', 'files', 0, '', ['111', '222']], + ]); + + $rules = [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], + ]; + + $this->assertEquals([], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + } + + public function testProcessFilterRulesAndConditionWithEmptyMidResult() { + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(true)); + + $this->tagMapper->expects($this->exactly(2)) + ->method('getObjectIdsForTags') + ->withConsecutive( + ['123', 'files'], + ['456', 'files'], + ['789', 'files'] + ) + ->willReturnMap([ + ['123', 'files', 0, '', ['111', '222']], + ['456', 'files', 0, '', ['333']], + ['789', 'files', 0, '', ['111', '222']], + ]); + + $rules = [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '789'], + ]; + + $this->assertEquals([], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + } + + public function testProcessFilterRulesInvisibleTagAsAdmin() { + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(true)); + + $tag1 = $this->getMock('\OCP\SystemTag\ISystemTag'); + $tag1->expects($this->any()) + ->method('getId') + ->will($this->returnValue('123')); + $tag1->expects($this->any()) + ->method('isUserVisible') + ->will($this->returnValue(true)); + + $tag2 = $this->getMock('\OCP\SystemTag\ISystemTag'); + $tag2->expects($this->any()) + ->method('getId') + ->will($this->returnValue('123')); + $tag2->expects($this->any()) + ->method('isUserVisible') + ->will($this->returnValue(false)); + + // no need to fetch tags to check permissions + $this->tagManager->expects($this->never()) + ->method('getTagsByIds'); + + $this->tagMapper->expects($this->at(0)) + ->method('getObjectIdsForTags') + ->with('123') + ->will($this->returnValue(['111', '222'])); + $this->tagMapper->expects($this->at(1)) + ->method('getObjectIdsForTags') + ->with('456') + ->will($this->returnValue(['222', '333'])); + + $rules = [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], + ]; + + $this->assertEquals(['222'], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + } + + /** + * @expectedException \OCP\SystemTag\TagNotFoundException + */ + public function testProcessFilterRulesInvisibleTagAsUser() { + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(false)); + + $tag1 = $this->getMock('\OCP\SystemTag\ISystemTag'); + $tag1->expects($this->any()) + ->method('getId') + ->will($this->returnValue('123')); + $tag1->expects($this->any()) + ->method('isUserVisible') + ->will($this->returnValue(true)); + + $tag2 = $this->getMock('\OCP\SystemTag\ISystemTag'); + $tag2->expects($this->any()) + ->method('getId') + ->will($this->returnValue('123')); + $tag2->expects($this->any()) + ->method('isUserVisible') + ->will($this->returnValue(false)); // invisible + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['123', '456']) + ->will($this->returnValue([$tag1, $tag2])); + + $rules = [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], + ]; + + $this->invokePrivate($this->plugin, 'processFilterRules', [$rules]); + } + + public function testProcessFilterRulesVisibleTagAsUser() { + $this->groupManager->expects($this->any()) + ->method('isAdmin') + ->will($this->returnValue(false)); + + $tag1 = $this->getMock('\OCP\SystemTag\ISystemTag'); + $tag1->expects($this->any()) + ->method('getId') + ->will($this->returnValue('123')); + $tag1->expects($this->any()) + ->method('isUserVisible') + ->will($this->returnValue(true)); + + $tag2 = $this->getMock('\OCP\SystemTag\ISystemTag'); + $tag2->expects($this->any()) + ->method('getId') + ->will($this->returnValue('123')); + $tag2->expects($this->any()) + ->method('isUserVisible') + ->will($this->returnValue(true)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['123', '456']) + ->will($this->returnValue([$tag1, $tag2])); + + $this->tagMapper->expects($this->at(0)) + ->method('getObjectIdsForTags') + ->with('123') + ->will($this->returnValue(['111', '222'])); + $this->tagMapper->expects($this->at(1)) + ->method('getObjectIdsForTags') + ->with('456') + ->will($this->returnValue(['222', '333'])); + + $rules = [ + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], + ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], + ]; + + $this->assertEquals(['222'], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php new file mode 100644 index 00000000000..a95dcd69f44 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php @@ -0,0 +1,73 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCA\DAV\Connector\Sabre\MaintenancePlugin; +use Test\TestCase; +use OCP\IConfig; + +/** + * Class MaintenancePluginTest + * + * @package OCA\DAV\Tests\unit\Connector\Sabre + */ +class MaintenancePluginTest extends TestCase { + /** @var IConfig */ + private $config; + /** @var MaintenancePlugin */ + private $maintenancePlugin; + + public function setUp() { + parent::setUp(); + + $this->config = $this->getMock('\OCP\IConfig'); + $this->maintenancePlugin = new MaintenancePlugin($this->config); + } + + /** + * @expectedException \Sabre\DAV\Exception\ServiceUnavailable + * @expectedExceptionMessage System in single user mode. + */ + public function testSingleUserMode() { + $this->config + ->expects($this->once()) + ->method('getSystemValue') + ->with('singleuser', false) + ->will($this->returnValue(true)); + + $this->maintenancePlugin->checkMaintenanceMode(); + } + + /** + * @expectedException \Sabre\DAV\Exception\ServiceUnavailable + * @expectedExceptionMessage System in single user mode. + */ + public function testMaintenanceMode() { + $this->config + ->expects($this->exactly(1)) + ->method('getSystemValue') + ->will($this->onConsecutiveCalls([false, true])); + + $this->maintenancePlugin->checkMaintenanceMode(); + } + +} diff --git a/apps/dav/tests/unit/Connector/Sabre/NodeTest.php b/apps/dav/tests/unit/Connector/Sabre/NodeTest.php new file mode 100644 index 00000000000..deb6ecf7f70 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/NodeTest.php @@ -0,0 +1,149 @@ + + * @author Robin Appelman + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +/** + * Class NodeTest + * + * @group DB + * @package OCA\DAV\Tests\unit\Connector\Sabre + */ +class NodeTest extends \Test\TestCase { + public function davPermissionsProvider() { + return array( + array(\OCP\Constants::PERMISSION_ALL, 'file', false, false, 'RDNVW'), + array(\OCP\Constants::PERMISSION_ALL, 'dir', false, false, 'RDNVCK'), + array(\OCP\Constants::PERMISSION_ALL, 'file', true, false, 'SRDNVW'), + array(\OCP\Constants::PERMISSION_ALL, 'file', true, true, 'SRMDNVW'), + array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE, 'file', true, false, 'SDNVW'), + array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_UPDATE, 'file', false, false, 'RD'), + array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_DELETE, 'file', false, false, 'RNVW'), + array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE, 'file', false, false, 'RDNVW'), + array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE, 'dir', false, false, 'RDNV'), + ); + } + + /** + * @dataProvider davPermissionsProvider + */ + public function testDavPermissions($permissions, $type, $shared, $mounted, $expected) { + $info = $this->getMockBuilder('\OC\Files\FileInfo') + ->disableOriginalConstructor() + ->setMethods(array('getPermissions', 'isShared', 'isMounted', 'getType')) + ->getMock(); + $info->expects($this->any()) + ->method('getPermissions') + ->will($this->returnValue($permissions)); + $info->expects($this->any()) + ->method('isShared') + ->will($this->returnValue($shared)); + $info->expects($this->any()) + ->method('isMounted') + ->will($this->returnValue($mounted)); + $info->expects($this->any()) + ->method('getType') + ->will($this->returnValue($type)); + $view = $this->getMock('\OC\Files\View'); + + $node = new \OCA\DAV\Connector\Sabre\File($view, $info); + $this->assertEquals($expected, $node->getDavPermissions()); + } + + public function sharePermissionsProvider() { + return [ + [\OCP\Files\FileInfo::TYPE_FILE, null, 1, 1], + [\OCP\Files\FileInfo::TYPE_FILE, null, 3, 3], + [\OCP\Files\FileInfo::TYPE_FILE, null, 5, 1], + [\OCP\Files\FileInfo::TYPE_FILE, null, 7, 3], + [\OCP\Files\FileInfo::TYPE_FILE, null, 9, 1], + [\OCP\Files\FileInfo::TYPE_FILE, null, 11, 3], + [\OCP\Files\FileInfo::TYPE_FILE, null, 13, 1], + [\OCP\Files\FileInfo::TYPE_FILE, null, 15, 3], + [\OCP\Files\FileInfo::TYPE_FILE, null, 17, 17], + [\OCP\Files\FileInfo::TYPE_FILE, null, 19, 19], + [\OCP\Files\FileInfo::TYPE_FILE, null, 21, 17], + [\OCP\Files\FileInfo::TYPE_FILE, null, 23, 19], + [\OCP\Files\FileInfo::TYPE_FILE, null, 25, 17], + [\OCP\Files\FileInfo::TYPE_FILE, null, 27, 19], + [\OCP\Files\FileInfo::TYPE_FILE, null, 29, 17], + [\OCP\Files\FileInfo::TYPE_FILE, null, 30, 18], + [\OCP\Files\FileInfo::TYPE_FILE, null, 31, 19], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 1, 1], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 3, 3], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 5, 5], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 7, 7], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 9, 9], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 11, 11], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 13, 13], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 15, 15], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 17, 17], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 19, 19], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 21, 21], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 23, 23], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 25, 25], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 27, 27], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 29, 29], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 30, 30], + [\OCP\Files\FileInfo::TYPE_FOLDER, null, 31, 31], + [\OCP\Files\FileInfo::TYPE_FOLDER, 'shareToken', 7, 7], + ]; + } + + /** + * @dataProvider sharePermissionsProvider + */ + public function testSharePermissions($type, $user, $permissions, $expected) { + $storage = $this->getMock('\OCP\Files\Storage'); + $storage->method('getPermissions')->willReturn($permissions); + + $mountpoint = $this->getMock('\OCP\Files\Mount\IMountPoint'); + $mountpoint->method('getMountPoint')->willReturn('myPath'); + $shareManager = $this->getMockBuilder('OCP\Share\IManager')->disableOriginalConstructor()->getMock(); + $share = $this->getMockBuilder('OCP\Share\IShare')->disableOriginalConstructor()->getMock(); + + if ($user === null) { + $shareManager->expects($this->never())->method('getShareByToken'); + $share->expects($this->never())->method('getPermissions'); + } else { + $shareManager->expects($this->once())->method('getShareByToken')->with($user) + ->willReturn($share); + $share->expects($this->once())->method('getPermissions')->willReturn($permissions); + } + + $info = $this->getMockBuilder('\OC\Files\FileInfo') + ->disableOriginalConstructor() + ->setMethods(['getStorage', 'getType', 'getMountPoint']) + ->getMock(); + + $info->method('getStorage')->willReturn($storage); + $info->method('getType')->willReturn($type); + $info->method('getMountPoint')->willReturn($mountpoint); + + $view = $this->getMock('\OC\Files\View'); + + $node = new \OCA\DAV\Connector\Sabre\File($view, $info); + $this->invokePrivate($node, 'shareManager', [$shareManager]); + $this->assertEquals($expected, $node->getSharePermissions($user)); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php new file mode 100644 index 00000000000..4a5e43376c0 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php @@ -0,0 +1,355 @@ + + * @author Morris Jobke + * @author Robin Appelman + * @author Thomas Müller + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + + +use OC\Files\FileInfo; +use OC\Files\Storage\Temporary; + +class TestDoubleFileView extends \OC\Files\View { + + public function __construct($updatables, $deletables, $canRename = true) { + $this->updatables = $updatables; + $this->deletables = $deletables; + $this->canRename = $canRename; + } + + public function isUpdatable($path) { + return $this->updatables[$path]; + } + + public function isCreatable($path) { + return $this->updatables[$path]; + } + + public function isDeletable($path) { + return $this->deletables[$path]; + } + + public function rename($path1, $path2) { + return $this->canRename; + } + + public function getRelativePath($path) { + return $path; + } +} + +/** + * Class ObjectTreeTest + * + * @group DB + * + * @package OCA\DAV\Tests\Unit\Connector\Sabre + */ +class ObjectTreeTest extends \Test\TestCase { + + /** + * @dataProvider moveFailedProvider + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testMoveFailed($source, $destination, $updatables, $deletables) { + $this->moveTest($source, $destination, $updatables, $deletables); + } + + /** + * @dataProvider moveSuccessProvider + */ + public function testMoveSuccess($source, $destination, $updatables, $deletables) { + $this->moveTest($source, $destination, $updatables, $deletables); + $this->assertTrue(true); + } + + /** + * @dataProvider moveFailedInvalidCharsProvider + * @expectedException \OCA\DAV\Connector\Sabre\Exception\InvalidPath + */ + public function testMoveFailedInvalidChars($source, $destination, $updatables, $deletables) { + $this->moveTest($source, $destination, $updatables, $deletables); + } + + function moveFailedInvalidCharsProvider() { + return array( + array('a/b', 'a/*', array('a' => true, 'a/b' => true, 'a/c*' => false), array()), + ); + } + + function moveFailedProvider() { + return array( + array('a/b', 'a/c', array('a' => false, 'a/b' => false, 'a/c' => false), array()), + array('a/b', 'b/b', array('a' => false, 'a/b' => false, 'b' => false, 'b/b' => false), array()), + array('a/b', 'b/b', array('a' => false, 'a/b' => true, 'b' => false, 'b/b' => false), array()), + array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => false, 'b/b' => false), array()), + array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false), array('a/b' => false)), + array('a/b', 'a/c', array('a' => false, 'a/b' => true, 'a/c' => false), array()), + ); + } + + function moveSuccessProvider() { + return array( + array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false), array('a/b' => true)), + // older files with special chars can still be renamed to valid names + array('a/b*', 'b/b', array('a' => true, 'a/b*' => true, 'b' => true, 'b/b' => false), array('a/b*' => true)), + ); + } + + /** + * @param $source + * @param $destination + * @param $updatables + */ + private function moveTest($source, $destination, $updatables, $deletables) { + $view = new TestDoubleFileView($updatables, $deletables); + + $info = new FileInfo('', null, null, array(), null); + + $rootDir = new \OCA\DAV\Connector\Sabre\Directory($view, $info); + $objectTree = $this->getMock('\OCA\DAV\Connector\Sabre\ObjectTree', + array('nodeExists', 'getNodeForPath'), + array($rootDir, $view)); + + $objectTree->expects($this->once()) + ->method('getNodeForPath') + ->with($this->identicalTo($source)) + ->will($this->returnValue(false)); + + /** @var $objectTree \OCA\DAV\Connector\Sabre\ObjectTree */ + $mountManager = \OC\Files\Filesystem::getMountManager(); + $objectTree->init($rootDir, $view, $mountManager); + $objectTree->move($source, $destination); + } + + /** + * @dataProvider nodeForPathProvider + */ + public function testGetNodeForPath( + $inputFileName, + $fileInfoQueryPath, + $outputFileName, + $type, + $enableChunkingHeader + ) { + + if ($enableChunkingHeader) { + $_SERVER['HTTP_OC_CHUNKED'] = true; + } + + $rootNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $mountManager = $this->getMock('\OC\Files\Mount\Manager'); + $view = $this->getMock('\OC\Files\View'); + $fileInfo = $this->getMock('\OCP\Files\FileInfo'); + $fileInfo->expects($this->once()) + ->method('getType') + ->will($this->returnValue($type)); + $fileInfo->expects($this->once()) + ->method('getName') + ->will($this->returnValue($outputFileName)); + + $view->expects($this->once()) + ->method('getFileInfo') + ->with($fileInfoQueryPath) + ->will($this->returnValue($fileInfo)); + + $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); + $tree->init($rootNode, $view, $mountManager); + + $node = $tree->getNodeForPath($inputFileName); + + $this->assertNotNull($node); + $this->assertEquals($outputFileName, $node->getName()); + + if ($type === 'file') { + $this->assertTrue($node instanceof \OCA\DAV\Connector\Sabre\File); + } else { + $this->assertTrue($node instanceof \OCA\DAV\Connector\Sabre\Directory); + } + + unset($_SERVER['HTTP_OC_CHUNKED']); + } + + function nodeForPathProvider() { + return array( + // regular file + array( + 'regularfile.txt', + 'regularfile.txt', + 'regularfile.txt', + 'file', + false + ), + // regular directory + array( + 'regulardir', + 'regulardir', + 'regulardir', + 'dir', + false + ), + // regular file with chunking + array( + 'regularfile.txt', + 'regularfile.txt', + 'regularfile.txt', + 'file', + true + ), + // regular directory with chunking + array( + 'regulardir', + 'regulardir', + 'regulardir', + 'dir', + true + ), + // file with chunky file name + array( + 'regularfile.txt-chunking-123566789-10-1', + 'regularfile.txt', + 'regularfile.txt', + 'file', + true + ), + // regular file in subdir + array( + 'subdir/regularfile.txt', + 'subdir/regularfile.txt', + 'regularfile.txt', + 'file', + false + ), + // regular directory in subdir + array( + 'subdir/regulardir', + 'subdir/regulardir', + 'regulardir', + 'dir', + false + ), + // file with chunky file name in subdir + array( + 'subdir/regularfile.txt-chunking-123566789-10-1', + 'subdir/regularfile.txt', + 'regularfile.txt', + 'file', + true + ), + ); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\InvalidPath + */ + public function testGetNodeForPathInvalidPath() { + $path = '/foo\bar'; + + + $storage = new Temporary([]); + + $view = $this->getMock('\OC\Files\View', ['resolvePath']); + $view->expects($this->once()) + ->method('resolvePath') + ->will($this->returnCallback(function($path) use ($storage){ + return [$storage, ltrim($path, '/')]; + })); + + $rootNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $mountManager = $this->getMock('\OC\Files\Mount\Manager'); + + $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); + $tree->init($rootNode, $view, $mountManager); + + $tree->getNodeForPath($path); + } + + public function testGetNodeForPathRoot() { + $path = '/'; + + + $storage = new Temporary([]); + + $view = $this->getMock('\OC\Files\View', ['resolvePath']); + $view->expects($this->any()) + ->method('resolvePath') + ->will($this->returnCallback(function ($path) use ($storage) { + return [$storage, ltrim($path, '/')]; + })); + + $rootNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $mountManager = $this->getMock('\OC\Files\Mount\Manager'); + + $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); + $tree->init($rootNode, $view, $mountManager); + + $this->assertInstanceOf('\Sabre\DAV\INode', $tree->getNodeForPath($path)); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + * @expectedExceptionMessage Could not copy directory nameOfSourceNode, target exists + */ + public function testFailingMove() { + $source = 'a/b'; + $destination = 'b/b'; + $updatables = array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false); + $deletables = array('a/b' => true); + + $view = new TestDoubleFileView($updatables, $deletables); + + $info = new FileInfo('', null, null, array(), null); + + $rootDir = new \OCA\DAV\Connector\Sabre\Directory($view, $info); + $objectTree = $this->getMock('\OCA\DAV\Connector\Sabre\ObjectTree', + array('nodeExists', 'getNodeForPath'), + array($rootDir, $view)); + + $sourceNode = $this->getMockBuilder('\Sabre\DAV\ICollection') + ->disableOriginalConstructor() + ->getMock(); + $sourceNode->expects($this->once()) + ->method('getName') + ->will($this->returnValue('nameOfSourceNode')); + + $objectTree->expects($this->once()) + ->method('nodeExists') + ->with($this->identicalTo($destination)) + ->will($this->returnValue(true)); + $objectTree->expects($this->once()) + ->method('getNodeForPath') + ->with($this->identicalTo($source)) + ->will($this->returnValue($sourceNode)); + + /** @var $objectTree \OCA\DAV\Connector\Sabre\ObjectTree */ + $mountManager = \OC\Files\Filesystem::getMountManager(); + $objectTree->init($rootDir, $view, $mountManager); + $objectTree->move($source, $destination); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php new file mode 100644 index 00000000000..63717713a7c --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php @@ -0,0 +1,273 @@ + + * @author Thomas Müller + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +use OCP\IGroupManager; +use \Sabre\DAV\PropPatch; +use OCP\IUserManager; +use Test\TestCase; + +class PrincipalTest extends TestCase { + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */ + private $userManager; + /** @var \OCA\DAV\Connector\Sabre\Principal */ + private $connector; + /** @var IGroupManager | \PHPUnit_Framework_MockObject_MockObject */ + private $groupManager; + + public function setUp() { + $this->userManager = $this->getMockBuilder('\OCP\IUserManager') + ->disableOriginalConstructor()->getMock(); + $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') + ->disableOriginalConstructor()->getMock(); + + $this->connector = new \OCA\DAV\Connector\Sabre\Principal( + $this->userManager, + $this->groupManager); + parent::setUp(); + } + + public function testGetPrincipalsByPrefixWithoutPrefix() { + $response = $this->connector->getPrincipalsByPrefix(''); + $this->assertSame([], $response); + } + + public function testGetPrincipalsByPrefixWithUsers() { + $fooUser = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $fooUser + ->expects($this->exactly(1)) + ->method('getUID') + ->will($this->returnValue('foo')); + $fooUser + ->expects($this->exactly(1)) + ->method('getDisplayName') + ->will($this->returnValue('Dr. Foo-Bar')); + $fooUser + ->expects($this->exactly(1)) + ->method('getEMailAddress') + ->will($this->returnValue('')); + $barUser = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $barUser + ->expects($this->exactly(1)) + ->method('getUID') + ->will($this->returnValue('bar')); + $barUser + ->expects($this->exactly(1)) + ->method('getEMailAddress') + ->will($this->returnValue('bar@owncloud.org')); + $this->userManager + ->expects($this->once()) + ->method('search') + ->with('') + ->will($this->returnValue([$fooUser, $barUser])); + + $expectedResponse = [ + 0 => [ + 'uri' => 'principals/users/foo', + '{DAV:}displayname' => 'Dr. Foo-Bar' + ], + 1 => [ + 'uri' => 'principals/users/bar', + '{DAV:}displayname' => 'bar', + '{http://sabredav.org/ns}email-address' => 'bar@owncloud.org' + ] + ]; + $response = $this->connector->getPrincipalsByPrefix('principals/users'); + $this->assertSame($expectedResponse, $response); + } + + public function testGetPrincipalsByPrefixEmpty() { + $this->userManager + ->expects($this->once()) + ->method('search') + ->with('') + ->will($this->returnValue([])); + + $response = $this->connector->getPrincipalsByPrefix('principals/users'); + $this->assertSame([], $response); + } + + public function testGetPrincipalsByPathWithoutMail() { + $fooUser = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $fooUser + ->expects($this->exactly(1)) + ->method('getUID') + ->will($this->returnValue('foo')); + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue($fooUser)); + + $expectedResponse = [ + 'uri' => 'principals/users/foo', + '{DAV:}displayname' => 'foo' + ]; + $response = $this->connector->getPrincipalByPath('principals/users/foo'); + $this->assertSame($expectedResponse, $response); + } + + public function testGetPrincipalsByPathWithMail() { + $fooUser = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $fooUser + ->expects($this->exactly(1)) + ->method('getEMailAddress') + ->will($this->returnValue('foo@owncloud.org')); + $fooUser + ->expects($this->exactly(1)) + ->method('getUID') + ->will($this->returnValue('foo')); + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue($fooUser)); + + $expectedResponse = [ + 'uri' => 'principals/users/foo', + '{DAV:}displayname' => 'foo', + '{http://sabredav.org/ns}email-address' => 'foo@owncloud.org' + ]; + $response = $this->connector->getPrincipalByPath('principals/users/foo'); + $this->assertSame($expectedResponse, $response); + } + + public function testGetPrincipalsByPathEmpty() { + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue(null)); + + $response = $this->connector->getPrincipalByPath('principals/users/foo'); + $this->assertSame(null, $response); + } + + public function testGetGroupMemberSet() { + $fooUser = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $fooUser + ->expects($this->exactly(1)) + ->method('getUID') + ->will($this->returnValue('foo')); + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue($fooUser)); + + $response = $this->connector->getGroupMemberSet('principals/users/foo'); + $this->assertSame(['principals/users/foo'], $response); + } + + /** + * @expectedException \Sabre\DAV\Exception + * @expectedExceptionMessage Principal not found + */ + public function testGetGroupMemberSetEmpty() { + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue(null)); + + $this->connector->getGroupMemberSet('principals/users/foo'); + } + + public function testGetGroupMembership() { + $fooUser = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $group = $this->getMockBuilder('\OCP\IGroup') + ->disableOriginalConstructor()->getMock(); + $group->expects($this->once()) + ->method('getGID') + ->willReturn('group1'); + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->willReturn($fooUser); + $this->groupManager + ->expects($this->once()) + ->method('getUserGroups') + ->willReturn([ + $group + ]); + + $expectedResponse = [ + 'principals/groups/group1' + ]; + $response = $this->connector->getGroupMembership('principals/users/foo'); + $this->assertSame($expectedResponse, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception + * @expectedExceptionMessage Principal not found + */ + public function testGetGroupMembershipEmpty() { + $this->userManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue(null)); + + $this->connector->getGroupMembership('principals/users/foo'); + } + + /** + * @expectedException \Sabre\DAV\Exception + * @expectedExceptionMessage Setting members of the group is not supported yet + */ + public function testSetGroupMembership() { + $this->connector->setGroupMemberSet('principals/users/foo', ['foo']); + } + + public function testUpdatePrincipal() { + $this->assertSame(0, $this->connector->updatePrincipal('foo', new PropPatch(array()))); + } + + public function testSearchPrincipals() { + $this->assertSame([], $this->connector->searchPrincipals('principals/users', [])); + } + + public function testFindByUri() { + $fooUser = $this->getMockBuilder('\OC\User\User') + ->disableOriginalConstructor()->getMock(); + $fooUser + ->expects($this->exactly(1)) + ->method('getUID') + ->will($this->returnValue('foo')); + + $this->userManager->expects($this->once())->method('getByEmail')->willReturn([ + $fooUser + ]); + $ret = $this->connector->findByUri('mailto:foo@bar.net', 'principals/users'); + $this->assertSame('principals/users/foo', $ret); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php new file mode 100644 index 00000000000..45fb1743d15 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php @@ -0,0 +1,223 @@ + + * @author Thomas Müller + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace OCA\DAV\Tests\unit\Connector\Sabre; +/** + * Copyright (c) 2013 Thomas Müller + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +class QuotaPluginTest extends \Test\TestCase { + + /** + * @var \Sabre\DAV\Server + */ + private $server; + + /** + * @var \OCA\DAV\Connector\Sabre\QuotaPlugin + */ + private $plugin; + + private function init($quota, $checkedPath = '') { + $view = $this->buildFileViewMock($quota, $checkedPath); + $this->server = new \Sabre\DAV\Server(); + $this->plugin = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\QuotaPlugin') + ->setConstructorArgs([$view]) + ->setMethods(['getFileChunking']) + ->getMock(); + $this->plugin->initialize($this->server); + } + + /** + * @dataProvider lengthProvider + */ + public function testLength($expected, $headers) { + $this->init(0); + $this->plugin->expects($this->never()) + ->method('getFileChunking'); + $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); + $length = $this->plugin->getLength(); + $this->assertEquals($expected, $length); + } + + /** + * @dataProvider quotaOkayProvider + */ + public function testCheckQuota($quota, $headers) { + $this->init($quota); + $this->plugin->expects($this->never()) + ->method('getFileChunking'); + + $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); + $result = $this->plugin->checkQuota(''); + $this->assertTrue($result); + } + + /** + * @expectedException \Sabre\DAV\Exception\InsufficientStorage + * @dataProvider quotaExceededProvider + */ + public function testCheckExceededQuota($quota, $headers) { + $this->init($quota); + $this->plugin->expects($this->never()) + ->method('getFileChunking'); + + $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); + $this->plugin->checkQuota(''); + } + + /** + * @dataProvider quotaOkayProvider + */ + public function testCheckQuotaOnPath($quota, $headers) { + $this->init($quota, 'sub/test.txt'); + $this->plugin->expects($this->never()) + ->method('getFileChunking'); + + $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); + $result = $this->plugin->checkQuota('/sub/test.txt'); + $this->assertTrue($result); + } + + public function quotaOkayProvider() { + return array( + array(1024, array()), + array(1024, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), + array(1024, array('CONTENT-LENGTH' => '512')), + array(1024, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), + // \OCP\Files\FileInfo::SPACE-UNKNOWN = -2 + array(-2, array()), + array(-2, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), + array(-2, array('CONTENT-LENGTH' => '512')), + array(-2, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), + ); + } + + public function quotaExceededProvider() { + return array( + array(1023, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), + array(511, array('CONTENT-LENGTH' => '512')), + array(2047, array('OC-TOTAL-LENGTH' => '2048', 'CONTENT-LENGTH' => '1024')), + ); + } + + public function lengthProvider() { + return array( + array(null, array()), + array(1024, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), + array(512, array('CONTENT-LENGTH' => '512')), + array(2048, array('OC-TOTAL-LENGTH' => '2048', 'CONTENT-LENGTH' => '1024')), + array(4096, array('OC-TOTAL-LENGTH' => '2048', 'X-EXPECTED-ENTITY-LENGTH' => '4096')), + ); + } + + public function quotaChunkedOkProvider() { + return array( + array(1024, 0, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), + array(1024, 0, array('CONTENT-LENGTH' => '512')), + array(1024, 0, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), + // with existing chunks (allowed size = total length - chunk total size) + array(400, 128, array('X-EXPECTED-ENTITY-LENGTH' => '512')), + array(400, 128, array('CONTENT-LENGTH' => '512')), + array(400, 128, array('OC-TOTAL-LENGTH' => '512', 'CONTENT-LENGTH' => '500')), + // \OCP\Files\FileInfo::SPACE-UNKNOWN = -2 + array(-2, 0, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), + array(-2, 0, array('CONTENT-LENGTH' => '512')), + array(-2, 0, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), + array(-2, 128, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), + array(-2, 128, array('CONTENT-LENGTH' => '512')), + array(-2, 128, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), + ); + } + + /** + * @dataProvider quotaChunkedOkProvider + */ + public function testCheckQuotaChunkedOk($quota, $chunkTotalSize, $headers) { + $this->init($quota, 'sub/test.txt'); + + $mockChunking = $this->getMockBuilder('\OC_FileChunking') + ->disableOriginalConstructor() + ->getMock(); + $mockChunking->expects($this->once()) + ->method('getCurrentSize') + ->will($this->returnValue($chunkTotalSize)); + + $this->plugin->expects($this->once()) + ->method('getFileChunking') + ->will($this->returnValue($mockChunking)); + + $headers['OC-CHUNKED'] = 1; + $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); + $result = $this->plugin->checkQuota('/sub/test.txt-chunking-12345-3-1'); + $this->assertTrue($result); + } + + public function quotaChunkedFailProvider() { + return array( + array(400, 0, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), + array(400, 0, array('CONTENT-LENGTH' => '512')), + array(400, 0, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), + // with existing chunks (allowed size = total length - chunk total size) + array(380, 128, array('X-EXPECTED-ENTITY-LENGTH' => '512')), + array(380, 128, array('CONTENT-LENGTH' => '512')), + array(380, 128, array('OC-TOTAL-LENGTH' => '512', 'CONTENT-LENGTH' => '500')), + ); + } + + /** + * @dataProvider quotaChunkedFailProvider + * @expectedException \Sabre\DAV\Exception\InsufficientStorage + */ + public function testCheckQuotaChunkedFail($quota, $chunkTotalSize, $headers) { + $this->init($quota, 'sub/test.txt'); + + $mockChunking = $this->getMockBuilder('\OC_FileChunking') + ->disableOriginalConstructor() + ->getMock(); + $mockChunking->expects($this->once()) + ->method('getCurrentSize') + ->will($this->returnValue($chunkTotalSize)); + + $this->plugin->expects($this->once()) + ->method('getFileChunking') + ->will($this->returnValue($mockChunking)); + + $headers['OC-CHUNKED'] = 1; + $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); + $this->plugin->checkQuota('/sub/test.txt-chunking-12345-3-1'); + } + + private function buildFileViewMock($quota, $checkedPath) { + // mock filesysten + $view = $this->getMock('\OC\Files\View', array('free_space'), array(), '', false); + $view->expects($this->any()) + ->method('free_space') + ->with($this->identicalTo($checkedPath)) + ->will($this->returnValue($quota)); + + return $view; + } + +} diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php new file mode 100644 index 00000000000..a8fcf552849 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php @@ -0,0 +1,117 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; + +use Sabre\DAV\Auth\Backend\BackendInterface; +use Sabre\HTTP\RequestInterface; +use Sabre\HTTP\ResponseInterface; + +class Auth implements BackendInterface { + /** + * @var string + */ + private $user; + + /** + * @var string + */ + private $password; + + /** + * Auth constructor. + * + * @param string $user + * @param string $password + */ + public function __construct($user, $password) { + $this->user = $user; + $this->password = $password; + } + + /** + * When this method is called, the backend must check if authentication was + * successful. + * + * The returned value must be one of the following + * + * [true, "principals/username"] + * [false, "reason for failure"] + * + * If authentication was successful, it's expected that the authentication + * backend returns a so-called principal url. + * + * Examples of a principal url: + * + * principals/admin + * principals/user1 + * principals/users/joe + * principals/uid/123457 + * + * If you don't use WebDAV ACL (RFC3744) we recommend that you simply + * return a string such as: + * + * principals/users/[username] + * + * @param RequestInterface $request + * @param ResponseInterface $response + * @return array + */ + function check(RequestInterface $request, ResponseInterface $response) { + $userSession = \OC::$server->getUserSession(); + $result = $userSession->login($this->user, $this->password); + if ($result) { + //we need to pass the user name, which may differ from login name + $user = $userSession->getUser()->getUID(); + \OC_Util::setupFS($user); + //trigger creation of user home and /files folder + \OC::$server->getUserFolder($user); + return [true, "principals/$user"]; + } + return [false, "login failed"]; + } + + /** + * This method is called when a user could not be authenticated, and + * authentication was required for the current request. + * + * This gives you the opportunity to set authentication headers. The 401 + * status code will already be set. + * + * In this case of Basic Auth, this would for example mean that the + * following header needs to be set: + * + * $response->addHeader('WWW-Authenticate', 'Basic realm=SabreDAV'); + * + * Keep in mind that in the case of multiple authentication backends, other + * WWW-Authenticate headers may already have been set, and you'll want to + * append your own WWW-Authenticate header instead of overwriting the + * existing one. + * + * @param RequestInterface $request + * @param ResponseInterface $response + * @return void + */ + function challenge(RequestInterface $request, ResponseInterface $response) { + // TODO: Implement challenge() method. + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DownloadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DownloadTest.php new file mode 100644 index 00000000000..1b296aaa243 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DownloadTest.php @@ -0,0 +1,73 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; + +use OCP\AppFramework\Http; +use OCP\Lock\ILockingProvider; + +/** + * Class DownloadTest + * + * @group DB + * + * @package OCA\DAV\Tests\unit\Connector\Sabre\RequestTest + */ +class DownloadTest extends RequestTest { + public function testDownload() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $view->file_put_contents('foo.txt', 'bar'); + + $response = $this->request($view, $user, 'pass', 'GET', '/foo.txt'); + $this->assertEquals(Http::STATUS_OK, $response->getStatus()); + $this->assertEquals(stream_get_contents($response->getBody()), 'bar'); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked + */ + public function testDownloadWriteLocked() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $view->file_put_contents('foo.txt', 'bar'); + + $view->lockFile('/foo.txt', ILockingProvider::LOCK_EXCLUSIVE); + + $this->request($view, $user, 'pass', 'GET', '/foo.txt', 'asd'); + } + + public function testDownloadReadLocked() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $view->file_put_contents('foo.txt', 'bar'); + + $view->lockFile('/foo.txt', ILockingProvider::LOCK_SHARED); + + $response = $this->request($view, $user, 'pass', 'GET', '/foo.txt', 'asd'); + $this->assertEquals(Http::STATUS_OK, $response->getStatus()); + $this->assertEquals(stream_get_contents($response->getBody()), 'bar'); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php new file mode 100644 index 00000000000..1a593cb8d76 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php @@ -0,0 +1,46 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; + +use OC\Files\View; +use Test\Traits\EncryptionTrait; + +/** + * Class EncryptionUploadTest + * + * @group DB + * + * @package OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest + */ +class EncryptionUploadTest extends UploadTest { + use EncryptionTrait; + + protected function setupUser($name, $password) { + $this->createUser($name, $password); + $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); + $this->setupForUser($name, $password); + $this->loginWithEncryption($name); + return new View('/' . $name . '/files'); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/ExceptionPlugin.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/ExceptionPlugin.php new file mode 100644 index 00000000000..42b8ef927f0 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/ExceptionPlugin.php @@ -0,0 +1,46 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; + +use Sabre\DAV\Exception; + +class ExceptionPlugin extends \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin { + /** + * @var \Exception[] + */ + protected $exceptions = []; + + public function logException(\Exception $ex) { + $exceptionClass = get_class($ex); + if (!isset($this->nonFatalExceptions[$exceptionClass])) { + $this->exceptions[] = $ex; + } + } + + /** + * @return \Exception[] + */ + public function getExceptions() { + return $this->exceptions; + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php new file mode 100644 index 00000000000..2986db4a7f1 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php @@ -0,0 +1,56 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; + +use OC\Files\View; +use Test\Traits\EncryptionTrait; + +/** + * Class PartFileInRootUploadTest + * + * @group DB + * + * @package OCA\DAV\Tests\unit\Connector\Sabre\RequestTest + */ +class PartFileInRootUploadTest extends UploadTest { + protected function setUp() { + $config = \OC::$server->getConfig(); + $mockConfig = $this->getMock('\OCP\IConfig'); + $mockConfig->expects($this->any()) + ->method('getSystemValue') + ->will($this->returnCallback(function ($key, $default) use ($config) { + if ($key === 'part_file_in_storage') { + return false; + } else { + return $config->getSystemValue($key, $default); + } + })); + $this->overwriteService('AllConfig', $mockConfig); + parent::setUp(); + } + + protected function tearDown() { + $this->restoreService('AllConfig'); + return parent::tearDown(); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTest.php new file mode 100644 index 00000000000..1c951a2fbd0 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTest.php @@ -0,0 +1,146 @@ + + * @author Lukas Reschke + * @author Robin Appelman + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; + +use OCA\DAV\Connector\Sabre\Server; +use OCA\DAV\Connector\Sabre\ServerFactory; +use OC\Files\Mount\MountPoint; +use OC\Files\Storage\StorageFactory; +use OC\Files\Storage\Temporary; +use OC\Files\View; +use OCP\IUser; +use Sabre\HTTP\Request; +use Test\TestCase; +use Test\Traits\MountProviderTrait; +use Test\Traits\UserTrait; + +abstract class RequestTest extends TestCase { + use UserTrait; + use MountProviderTrait; + + /** + * @var \OCA\DAV\Connector\Sabre\ServerFactory + */ + protected $serverFactory; + + protected function getStream($string) { + $stream = fopen('php://temp', 'r+'); + fwrite($stream, $string); + fseek($stream, 0); + return $stream; + } + + protected function setUp() { + parent::setUp(); + + $this->serverFactory = new ServerFactory( + \OC::$server->getConfig(), + \OC::$server->getLogger(), + \OC::$server->getDatabaseConnection(), + \OC::$server->getUserSession(), + \OC::$server->getMountManager(), + \OC::$server->getTagManager(), + $this->getMock('\OCP\IRequest') + ); + } + + protected function setupUser($name, $password) { + $this->createUser($name, $password); + $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); + $this->loginAsUser($name); + return new View('/' . $name . '/files'); + } + + /** + * @param \OC\Files\View $view the view to run the webdav server against + * @param string $user + * @param string $password + * @param string $method + * @param string $url + * @param resource|string|null $body + * @param array|null $headers + * @return \Sabre\HTTP\Response + * @throws \Exception + */ + protected function request($view, $user, $password, $method, $url, $body = null, $headers = null) { + if (is_string($body)) { + $body = $this->getStream($body); + } + $this->logout(); + $exceptionPlugin = new ExceptionPlugin('webdav', null); + $server = $this->getSabreServer($view, $user, $password, $exceptionPlugin); + $request = new Request($method, $url, $headers, $body); + + // since sabre catches all exceptions we need to save them and throw them from outside the sabre server + + $originalServer = $_SERVER; + + if (is_array($headers)) { + foreach ($headers as $header => $value) { + $_SERVER['HTTP_' . strtoupper(str_replace('-', '_', $header))] = $value; + } + } + + $result = $this->makeRequest($server, $request); + + foreach ($exceptionPlugin->getExceptions() as $exception) { + throw $exception; + } + $_SERVER = $originalServer; + return $result; + } + + /** + * @param Server $server + * @param Request $request + * @return \Sabre\HTTP\Response + */ + protected function makeRequest(Server $server, Request $request) { + $sapi = new Sapi($request); + $server->sapi = $sapi; + $server->httpRequest = $request; + $server->exec(); + return $sapi->getResponse(); + } + + /** + * @param View $view + * @param string $user + * @param string $password + * @param ExceptionPlugin $exceptionPlugin + * @return Server + */ + protected function getSabreServer(View $view, $user, $password, ExceptionPlugin $exceptionPlugin) { + $authBackend = new Auth($user, $password); + + $server = $this->serverFactory->createServer('/', 'dummy', $authBackend, function () use ($view) { + return $view; + }); + $server->addPlugin($exceptionPlugin); + + return $server; + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php new file mode 100644 index 00000000000..0f11ded89e0 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php @@ -0,0 +1,75 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; + +use Sabre\HTTP\Request; +use Sabre\HTTP\Response; + +class Sapi { + /** + * @var \Sabre\HTTP\Request + */ + private $request; + + /** + * @var \Sabre\HTTP\Response + */ + private $response; + + /** + * This static method will create a new Request object, based on the + * current PHP request. + * + * @return \Sabre\HTTP\Request + */ + public function getRequest() { + return $this->request; + } + + public function __construct(Request $request) { + $this->request = $request; + } + + /** + * @param \Sabre\HTTP\Response $response + * @return void + */ + public function sendResponse(Response $response) { + // we need to copy the body since we close the source stream + $copyStream = fopen('php://temp', 'r+'); + if (is_string($response->getBody())) { + fwrite($copyStream, $response->getBody()); + } else if (is_resource($response->getBody())) { + stream_copy_to_stream($response->getBody(), $copyStream); + } + rewind($copyStream); + $this->response = new Response($response->getStatus(), $response->getHeaders(), $copyStream); + } + + /** + * @return \Sabre\HTTP\Response + */ + public function getResponse() { + return $this->response; + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php new file mode 100644 index 00000000000..efb499b69c3 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php @@ -0,0 +1,211 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; + +use OC\Connector\Sabre\Exception\FileLocked; +use OCP\AppFramework\Http; +use OCP\Lock\ILockingProvider; + +/** + * Class UploadTest + * + * @group DB + * + * @package OCA\DAV\Tests\unit\Connector\Sabre\RequestTest + */ +class UploadTest extends RequestTest { + public function testBasicUpload() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $this->assertFalse($view->file_exists('foo.txt')); + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt', 'asd'); + + $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); + $this->assertTrue($view->file_exists('foo.txt')); + $this->assertEquals('asd', $view->file_get_contents('foo.txt')); + + $info = $view->getFileInfo('foo.txt'); + $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertEquals(3, $info->getSize()); + } + + public function testUploadOverWrite() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $view->file_put_contents('foo.txt', 'foobar'); + + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt', 'asd'); + + $this->assertEquals(Http::STATUS_NO_CONTENT, $response->getStatus()); + $this->assertEquals('asd', $view->file_get_contents('foo.txt')); + + $info = $view->getFileInfo('foo.txt'); + $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertEquals(3, $info->getSize()); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked + */ + public function testUploadOverWriteReadLocked() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $view->file_put_contents('foo.txt', 'bar'); + + $view->lockFile('/foo.txt', ILockingProvider::LOCK_SHARED); + + $this->request($view, $user, 'pass', 'PUT', '/foo.txt', 'asd'); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked + */ + public function testUploadOverWriteWriteLocked() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $view->file_put_contents('foo.txt', 'bar'); + + $view->lockFile('/foo.txt', ILockingProvider::LOCK_EXCLUSIVE); + + $this->request($view, $user, 'pass', 'PUT', '/foo.txt', 'asd'); + } + + public function testChunkedUpload() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $this->assertFalse($view->file_exists('foo.txt')); + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); + + $this->assertEquals(201, $response->getStatus()); + $this->assertFalse($view->file_exists('foo.txt')); + + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); + + $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); + $this->assertTrue($view->file_exists('foo.txt')); + + $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); + + $info = $view->getFileInfo('foo.txt'); + $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertEquals(6, $info->getSize()); + } + + public function testChunkedUploadOverWrite() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $view->file_put_contents('foo.txt', 'bar'); + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); + + $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); + $this->assertEquals('bar', $view->file_get_contents('foo.txt')); + + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); + + $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); + + $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); + + $info = $view->getFileInfo('foo.txt'); + $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertEquals(6, $info->getSize()); + } + + public function testChunkedUploadOutOfOrder() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $this->assertFalse($view->file_exists('foo.txt')); + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); + + $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); + $this->assertFalse($view->file_exists('foo.txt')); + + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); + + $this->assertEquals(201, $response->getStatus()); + $this->assertTrue($view->file_exists('foo.txt')); + + $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); + + $info = $view->getFileInfo('foo.txt'); + $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertEquals(6, $info->getSize()); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked + */ + public function testChunkedUploadOutOfOrderReadLocked() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $this->assertFalse($view->file_exists('foo.txt')); + + $view->lockFile('/foo.txt', ILockingProvider::LOCK_SHARED); + + try { + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); + } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { + $this->fail('Didn\'t expect locked error for the first chunk on read lock'); + return; + } + + $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); + $this->assertFalse($view->file_exists('foo.txt')); + + // last chunk should trigger the locked error since it tries to assemble + $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); + } + + /** + * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked + */ + public function testChunkedUploadOutOfOrderWriteLocked() { + $user = $this->getUniqueID(); + $view = $this->setupUser($user, 'pass'); + + $this->assertFalse($view->file_exists('foo.txt')); + + $view->lockFile('/foo.txt', ILockingProvider::LOCK_EXCLUSIVE); + + try { + $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); + } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { + $this->fail('Didn\'t expect locked error for the first chunk on write lock'); // maybe forbid this in the future for write locks only? + return; + } + + $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); + $this->assertFalse($view->file_exists('foo.txt')); + + // last chunk should trigger the locked error since it tries to assemble + $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php new file mode 100644 index 00000000000..ff1f59e7851 --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php @@ -0,0 +1,259 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +class SharesPluginTest extends \Test\TestCase { + + const SHARETYPES_PROPERTYNAME = \OCA\DAV\Connector\Sabre\SharesPlugin::SHARETYPES_PROPERTYNAME; + + /** + * @var \Sabre\DAV\Server + */ + private $server; + + /** + * @var \Sabre\DAV\Tree + */ + private $tree; + + /** + * @var \OCP\Share\IManager + */ + private $shareManager; + + /** + * @var \OCP\Files\Folder + */ + private $userFolder; + + /** + * @var \OCA\DAV\Connector\Sabre\SharesPlugin + */ + private $plugin; + + public function setUp() { + parent::setUp(); + $this->server = new \Sabre\DAV\Server(); + $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + ->disableOriginalConstructor() + ->getMock(); + $this->shareManager = $this->getMock('\OCP\Share\IManager'); + $user = $this->getMock('\OCP\IUser'); + $user->expects($this->once()) + ->method('getUID') + ->will($this->returnValue('user1')); + $userSession = $this->getMock('\OCP\IUserSession'); + $userSession->expects($this->once()) + ->method('getUser') + ->will($this->returnValue($user)); + + $this->userFolder = $this->getMock('\OCP\Files\Folder'); + + $this->plugin = new \OCA\DAV\Connector\Sabre\SharesPlugin( + $this->tree, + $userSession, + $this->userFolder, + $this->shareManager + ); + $this->plugin->initialize($this->server); + } + + /** + * @dataProvider sharesGetPropertiesDataProvider + */ + public function testGetProperties($shareTypes) { + $sabreNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + ->disableOriginalConstructor() + ->getMock(); + $sabreNode->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + $sabreNode->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/subdir')); + + // node API nodes + $node = $this->getMock('\OCP\Files\Folder'); + + $this->userFolder->expects($this->once()) + ->method('get') + ->with('/subdir') + ->will($this->returnValue($node)); + + $this->shareManager->expects($this->any()) + ->method('getSharesBy') + ->with( + $this->equalTo('user1'), + $this->anything(), + $this->anything(), + $this->equalTo(false), + $this->equalTo(1) + ) + ->will($this->returnCallback(function($userId, $requestedShareType, $node, $flag, $limit) use ($shareTypes){ + if (in_array($requestedShareType, $shareTypes)) { + return ['dummyshare']; + } + return []; + })); + + $propFind = new \Sabre\DAV\PropFind( + '/dummyPath', + [self::SHARETYPES_PROPERTYNAME], + 0 + ); + + $this->plugin->handleGetProperties( + $propFind, + $sabreNode + ); + + $result = $propFind->getResultForMultiStatus(); + + $this->assertEmpty($result[404]); + unset($result[404]); + $this->assertEquals($shareTypes, $result[200][self::SHARETYPES_PROPERTYNAME]->getShareTypes()); + } + + /** + * @dataProvider sharesGetPropertiesDataProvider + */ + public function testPreloadThenGetProperties($shareTypes) { + $sabreNode1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + ->disableOriginalConstructor() + ->getMock(); + $sabreNode1->expects($this->any()) + ->method('getId') + ->will($this->returnValue(111)); + $sabreNode1->expects($this->never()) + ->method('getPath'); + $sabreNode2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + ->disableOriginalConstructor() + ->getMock(); + $sabreNode2->expects($this->any()) + ->method('getId') + ->will($this->returnValue(222)); + $sabreNode2->expects($this->never()) + ->method('getPath'); + + $sabreNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $sabreNode->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + // never, because we use getDirectoryListing from the Node API instead + $sabreNode->expects($this->never()) + ->method('getChildren'); + $sabreNode->expects($this->any()) + ->method('getPath') + ->will($this->returnValue('/subdir')); + + // node API nodes + $node = $this->getMock('\OCP\Files\Folder'); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + $node1 = $this->getMock('\OCP\Files\File'); + $node1->expects($this->any()) + ->method('getId') + ->will($this->returnValue(111)); + $node2 = $this->getMock('\OCP\Files\File'); + $node2->expects($this->any()) + ->method('getId') + ->will($this->returnValue(222)); + $node->expects($this->once()) + ->method('getDirectoryListing') + ->will($this->returnValue([$node1, $node2])); + + $this->userFolder->expects($this->once()) + ->method('get') + ->with('/subdir') + ->will($this->returnValue($node)); + + $this->shareManager->expects($this->any()) + ->method('getSharesBy') + ->with( + $this->equalTo('user1'), + $this->anything(), + $this->anything(), + $this->equalTo(false), + $this->equalTo(1) + ) + ->will($this->returnCallback(function($userId, $requestedShareType, $node, $flag, $limit) use ($shareTypes){ + if ($node->getId() === 111 && in_array($requestedShareType, $shareTypes)) { + return ['dummyshare']; + } + + return []; + })); + + // simulate sabre recursive PROPFIND traversal + $propFindRoot = new \Sabre\DAV\PropFind( + '/subdir', + [self::SHARETYPES_PROPERTYNAME], + 1 + ); + $propFind1 = new \Sabre\DAV\PropFind( + '/subdir/test.txt', + [self::SHARETYPES_PROPERTYNAME], + 0 + ); + $propFind2 = new \Sabre\DAV\PropFind( + '/subdir/test2.txt', + [self::SHARETYPES_PROPERTYNAME], + 0 + ); + + $this->plugin->handleGetProperties( + $propFindRoot, + $sabreNode + ); + $this->plugin->handleGetProperties( + $propFind1, + $sabreNode1 + ); + $this->plugin->handleGetProperties( + $propFind2, + $sabreNode2 + ); + + $result = $propFind1->getResultForMultiStatus(); + + $this->assertEmpty($result[404]); + unset($result[404]); + $this->assertEquals($shareTypes, $result[200][self::SHARETYPES_PROPERTYNAME]->getShareTypes()); + } + + function sharesGetPropertiesDataProvider() { + return [ + [[]], + [[\OCP\Share::SHARE_TYPE_USER]], + [[\OCP\Share::SHARE_TYPE_GROUP]], + [[\OCP\Share::SHARE_TYPE_LINK]], + [[\OCP\Share::SHARE_TYPE_REMOTE]], + [[\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP]], + [[\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK]], + [[\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_LINK]], + [[\OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK]], + [[\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_REMOTE]], + ]; + } +} diff --git a/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php new file mode 100644 index 00000000000..e48d9b3aa5f --- /dev/null +++ b/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php @@ -0,0 +1,417 @@ + + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace OCA\DAV\Tests\unit\Connector\Sabre; + +/** + * Copyright (c) 2014 Vincent Petry + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ +class TagsPluginTest extends \Test\TestCase { + + const TAGS_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::TAGS_PROPERTYNAME; + const FAVORITE_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::FAVORITE_PROPERTYNAME; + const TAG_FAVORITE = \OCA\DAV\Connector\Sabre\TagsPlugin::TAG_FAVORITE; + + /** + * @var \Sabre\DAV\Server + */ + private $server; + + /** + * @var \Sabre\DAV\Tree + */ + private $tree; + + /** + * @var \OCP\ITagManager + */ + private $tagManager; + + /** + * @var \OCP\ITags + */ + private $tagger; + + /** + * @var \OCA\DAV\Connector\Sabre\TagsPlugin + */ + private $plugin; + + public function setUp() { + parent::setUp(); + $this->server = new \Sabre\DAV\Server(); + $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + ->disableOriginalConstructor() + ->getMock(); + $this->tagger = $this->getMock('\OCP\ITags'); + $this->tagManager = $this->getMock('\OCP\ITagManager'); + $this->tagManager->expects($this->any()) + ->method('load') + ->with('files') + ->will($this->returnValue($this->tagger)); + $this->plugin = new \OCA\DAV\Connector\Sabre\TagsPlugin($this->tree, $this->tagManager); + $this->plugin->initialize($this->server); + } + + /** + * @dataProvider tagsGetPropertiesDataProvider + */ + public function testGetProperties($tags, $requestedProperties, $expectedProperties) { + $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + + $expectedCallCount = 0; + if (count($requestedProperties) > 0) { + $expectedCallCount = 1; + } + + $this->tagger->expects($this->exactly($expectedCallCount)) + ->method('getTagsForObjects') + ->with($this->equalTo(array(123))) + ->will($this->returnValue(array(123 => $tags))); + + $propFind = new \Sabre\DAV\PropFind( + '/dummyPath', + $requestedProperties, + 0 + ); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + + $result = $propFind->getResultForMultiStatus(); + + $this->assertEmpty($result[404]); + unset($result[404]); + $this->assertEquals($expectedProperties, $result); + } + + /** + * @dataProvider tagsGetPropertiesDataProvider + */ + public function testPreloadThenGetProperties($tags, $requestedProperties, $expectedProperties) { + $node1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + ->disableOriginalConstructor() + ->getMock(); + $node1->expects($this->any()) + ->method('getId') + ->will($this->returnValue(111)); + $node2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') + ->disableOriginalConstructor() + ->getMock(); + $node2->expects($this->any()) + ->method('getId') + ->will($this->returnValue(222)); + + $expectedCallCount = 0; + if (count($requestedProperties) > 0) { + // this guarantees that getTagsForObjects + // is only called once and then the tags + // are cached + $expectedCallCount = 1; + } + + $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + $node->expects($this->exactly($expectedCallCount)) + ->method('getChildren') + ->will($this->returnValue(array($node1, $node2))); + + $this->tagger->expects($this->exactly($expectedCallCount)) + ->method('getTagsForObjects') + ->with($this->equalTo(array(123, 111, 222))) + ->will($this->returnValue( + array( + 111 => $tags, + 123 => $tags + ) + )); + + // simulate sabre recursive PROPFIND traversal + $propFindRoot = new \Sabre\DAV\PropFind( + '/subdir', + $requestedProperties, + 1 + ); + $propFind1 = new \Sabre\DAV\PropFind( + '/subdir/test.txt', + $requestedProperties, + 0 + ); + $propFind2 = new \Sabre\DAV\PropFind( + '/subdir/test2.txt', + $requestedProperties, + 0 + ); + + $this->plugin->handleGetProperties( + $propFindRoot, + $node + ); + $this->plugin->handleGetProperties( + $propFind1, + $node1 + ); + $this->plugin->handleGetProperties( + $propFind2, + $node2 + ); + + $result = $propFind1->getResultForMultiStatus(); + + $this->assertEmpty($result[404]); + unset($result[404]); + $this->assertEquals($expectedProperties, $result); + } + + function tagsGetPropertiesDataProvider() { + return array( + // request both, receive both + array( + array('tag1', 'tag2', self::TAG_FAVORITE), + array(self::TAGS_PROPERTYNAME, self::FAVORITE_PROPERTYNAME), + array( + 200 => array( + self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array('tag1', 'tag2')), + self::FAVORITE_PROPERTYNAME => true, + ) + ) + ), + // request tags alone + array( + array('tag1', 'tag2', self::TAG_FAVORITE), + array(self::TAGS_PROPERTYNAME), + array( + 200 => array( + self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array('tag1', 'tag2')), + ) + ) + ), + // request fav alone + array( + array('tag1', 'tag2', self::TAG_FAVORITE), + array(self::FAVORITE_PROPERTYNAME), + array( + 200 => array( + self::FAVORITE_PROPERTYNAME => true, + ) + ) + ), + // request none + array( + array('tag1', 'tag2', self::TAG_FAVORITE), + array(), + array( + 200 => array() + ), + ), + // request both with none set, receive both + array( + array(), + array(self::TAGS_PROPERTYNAME, self::FAVORITE_PROPERTYNAME), + array( + 200 => array( + self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array()), + self::FAVORITE_PROPERTYNAME => false, + ) + ) + ), + ); + } + + public function testUpdateTags() { + // this test will replace the existing tags "tagremove" with "tag1" and "tag2" + // and keep "tagkeep" + $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->returnValue($node)); + + $this->tagger->expects($this->at(0)) + ->method('getTagsForObjects') + ->with($this->equalTo(array(123))) + ->will($this->returnValue(array(123 => array('tagkeep', 'tagremove', self::TAG_FAVORITE)))); + + // then tag as tag1 and tag2 + $this->tagger->expects($this->at(1)) + ->method('tagAs') + ->with(123, 'tag1'); + $this->tagger->expects($this->at(2)) + ->method('tagAs') + ->with(123, 'tag2'); + + // it will untag tag3 + $this->tagger->expects($this->at(3)) + ->method('unTag') + ->with(123, 'tagremove'); + + // properties to set + $propPatch = new \Sabre\DAV\PropPatch(array( + self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array('tag1', 'tag2', 'tagkeep')) + )); + + $this->plugin->handleUpdateProperties( + '/dummypath', + $propPatch + ); + + $propPatch->commit(); + + // all requested properties removed, as they were processed already + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertEquals(200, $result[self::TAGS_PROPERTYNAME]); + $this->assertFalse(isset($result[self::FAVORITE_PROPERTYNAME])); + } + + public function testUpdateTagsFromScratch() { + $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->returnValue($node)); + + $this->tagger->expects($this->at(0)) + ->method('getTagsForObjects') + ->with($this->equalTo(array(123))) + ->will($this->returnValue(array())); + + // then tag as tag1 and tag2 + $this->tagger->expects($this->at(1)) + ->method('tagAs') + ->with(123, 'tag1'); + $this->tagger->expects($this->at(2)) + ->method('tagAs') + ->with(123, 'tag2'); + + // properties to set + $propPatch = new \Sabre\DAV\PropPatch(array( + self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array('tag1', 'tag2', 'tagkeep')) + )); + + $this->plugin->handleUpdateProperties( + '/dummypath', + $propPatch + ); + + $propPatch->commit(); + + // all requested properties removed, as they were processed already + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertEquals(200, $result[self::TAGS_PROPERTYNAME]); + $this->assertFalse(false, isset($result[self::FAVORITE_PROPERTYNAME])); + } + + public function testUpdateFav() { + // this test will replace the existing tags "tagremove" with "tag1" and "tag2" + // and keep "tagkeep" + $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getId') + ->will($this->returnValue(123)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/dummypath') + ->will($this->returnValue($node)); + + // set favorite tag + $this->tagger->expects($this->once()) + ->method('tagAs') + ->with(123, self::TAG_FAVORITE); + + // properties to set + $propPatch = new \Sabre\DAV\PropPatch(array( + self::FAVORITE_PROPERTYNAME => true + )); + + $this->plugin->handleUpdateProperties( + '/dummypath', + $propPatch + ); + + $propPatch->commit(); + + // all requested properties removed, as they were processed already + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertFalse(false, isset($result[self::TAGS_PROPERTYNAME])); + $this->assertEquals(200, isset($result[self::FAVORITE_PROPERTYNAME])); + + // unfavorite now + // set favorite tag + $this->tagger->expects($this->once()) + ->method('unTag') + ->with(123, self::TAG_FAVORITE); + + // properties to set + $propPatch = new \Sabre\DAV\PropPatch(array( + self::FAVORITE_PROPERTYNAME => false + )); + + $this->plugin->handleUpdateProperties( + '/dummypath', + $propPatch + ); + + $propPatch->commit(); + + // all requested properties removed, as they were processed already + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertFalse(false, isset($result[self::TAGS_PROPERTYNAME])); + $this->assertEquals(200, isset($result[self::FAVORITE_PROPERTYNAME])); + } + +} diff --git a/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php b/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php new file mode 100644 index 00000000000..c2ffd91ba31 --- /dev/null +++ b/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php @@ -0,0 +1,58 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\DAV; + +use OCA\DAV\Files\BrowserErrorPagePlugin; +use PHPUnit_Framework_MockObject_MockObject; +use Sabre\DAV\Exception\NotFound; + +class BrowserErrorPagePluginTest extends \Test\TestCase { + + /** + * @dataProvider providesExceptions + * @param $expectedCode + * @param $exception + */ + public function test($expectedCode, $exception) { + /** @var BrowserErrorPagePlugin | PHPUnit_Framework_MockObject_MockObject $plugin */ + $plugin = $this->getMockBuilder('OCA\DAV\Files\BrowserErrorPagePlugin')->setMethods(['sendResponse', 'generateBody'])->getMock(); + $plugin->expects($this->once())->method('generateBody')->willReturn(':boom:'); + $plugin->expects($this->once())->method('sendResponse'); + /** @var \Sabre\DAV\Server | PHPUnit_Framework_MockObject_MockObject $server */ + $server = $this->getMockBuilder('Sabre\DAV\Server')->disableOriginalConstructor()->getMock(); + $server->expects($this->once())->method('on'); + $httpResponse = $this->getMockBuilder('Sabre\HTTP\Response')->disableOriginalConstructor()->getMock(); + $httpResponse->expects($this->once())->method('addHeaders'); + $httpResponse->expects($this->once())->method('setStatus')->with($expectedCode); + $httpResponse->expects($this->once())->method('setBody')->with(':boom:'); + $server->httpResponse = $httpResponse; + $plugin->initialize($server); + $plugin->logException($exception); + } + + public function providesExceptions() { + return [ + [ 404, new NotFound()], + [ 500, new \RuntimeException()], + ]; + } +} diff --git a/apps/dav/tests/unit/DAV/GroupPrincipalTest.php b/apps/dav/tests/unit/DAV/GroupPrincipalTest.php new file mode 100644 index 00000000000..7bfb89609e4 --- /dev/null +++ b/apps/dav/tests/unit/DAV/GroupPrincipalTest.php @@ -0,0 +1,165 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\DAV; + +use OCA\DAV\DAV\GroupPrincipalBackend; +use OCP\IGroupManager; +use PHPUnit_Framework_MockObject_MockObject; +use \Sabre\DAV\PropPatch; + +class GroupPrincipalTest extends \Test\TestCase { + + /** @var IGroupManager | PHPUnit_Framework_MockObject_MockObject */ + private $groupManager; + + /** @var GroupPrincipalBackend */ + private $connector; + + public function setUp() { + $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') + ->disableOriginalConstructor()->getMock(); + + $this->connector = new GroupPrincipalBackend($this->groupManager); + parent::setUp(); + } + + public function testGetPrincipalsByPrefixWithoutPrefix() { + $response = $this->connector->getPrincipalsByPrefix(''); + $this->assertSame([], $response); + } + + public function testGetPrincipalsByPrefixWithUsers() { + $group1 = $this->mockGroup('foo'); + $group2 = $this->mockGroup('bar'); + $this->groupManager + ->expects($this->once()) + ->method('search') + ->with('') + ->will($this->returnValue([$group1, $group2])); + + $expectedResponse = [ + 0 => [ + 'uri' => 'principals/groups/foo', + '{DAV:}displayname' => 'foo' + ], + 1 => [ + 'uri' => 'principals/groups/bar', + '{DAV:}displayname' => 'bar', + ] + ]; + $response = $this->connector->getPrincipalsByPrefix('principals/groups'); + $this->assertSame($expectedResponse, $response); + } + + public function testGetPrincipalsByPrefixEmpty() { + $this->groupManager + ->expects($this->once()) + ->method('search') + ->with('') + ->will($this->returnValue([])); + + $response = $this->connector->getPrincipalsByPrefix('principals/groups'); + $this->assertSame([], $response); + } + + public function testGetPrincipalsByPathWithoutMail() { + $group1 = $this->mockGroup('foo'); + $this->groupManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue($group1)); + + $expectedResponse = [ + 'uri' => 'principals/groups/foo', + '{DAV:}displayname' => 'foo' + ]; + $response = $this->connector->getPrincipalByPath('principals/groups/foo'); + $this->assertSame($expectedResponse, $response); + } + + public function testGetPrincipalsByPathWithMail() { + $fooUser = $this->mockGroup('foo'); + $this->groupManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue($fooUser)); + + $expectedResponse = [ + 'uri' => 'principals/groups/foo', + '{DAV:}displayname' => 'foo', + ]; + $response = $this->connector->getPrincipalByPath('principals/groups/foo'); + $this->assertSame($expectedResponse, $response); + } + + public function testGetPrincipalsByPathEmpty() { + $this->groupManager + ->expects($this->once()) + ->method('get') + ->with('foo') + ->will($this->returnValue(null)); + + $response = $this->connector->getPrincipalByPath('principals/groups/foo'); + $this->assertSame(null, $response); + } + + public function testGetGroupMemberSet() { + $response = $this->connector->getGroupMemberSet('principals/groups/foo'); + $this->assertSame([], $response); + } + + public function testGetGroupMembership() { + $response = $this->connector->getGroupMembership('principals/groups/foo'); + $this->assertSame([], $response); + } + + /** + * @expectedException \Sabre\DAV\Exception + * @expectedExceptionMessage Setting members of the group is not supported yet + */ + public function testSetGroupMembership() { + $this->connector->setGroupMemberSet('principals/groups/foo', ['foo']); + } + + public function testUpdatePrincipal() { + $this->assertSame(0, $this->connector->updatePrincipal('foo', new PropPatch(array()))); + } + + public function testSearchPrincipals() { + $this->assertSame([], $this->connector->searchPrincipals('principals/groups', [])); + } + + /** + * @return PHPUnit_Framework_MockObject_MockObject + */ + private function mockGroup($gid) { + $fooUser = $this->getMockBuilder('\OC\Group\Group') + ->disableOriginalConstructor()->getMock(); + $fooUser + ->expects($this->exactly(1)) + ->method('getGID') + ->will($this->returnValue($gid)); + return $fooUser; + } +} diff --git a/apps/dav/tests/unit/DAV/HookManagerTest.php b/apps/dav/tests/unit/DAV/HookManagerTest.php new file mode 100644 index 00000000000..25eb3b8c11c --- /dev/null +++ b/apps/dav/tests/unit/DAV/HookManagerTest.php @@ -0,0 +1,152 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\DAV; + +use OCA\DAV\CalDAV\BirthdayService; +use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\CardDAV\CardDavBackend; +use OCA\DAV\CardDAV\SyncService; +use OCA\DAV\HookManager; +use OCP\IUserManager; +use Test\TestCase; + +class HookManagerTest extends TestCase { + public function test() { + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->once())->method('getUID')->willReturn('newUser'); + + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ + $userManager = $this->getMockBuilder('\OCP\IUserManager') + ->disableOriginalConstructor() + ->getMock(); + $userManager->expects($this->once())->method('get')->willReturn($user); + + /** @var SyncService | \PHPUnit_Framework_MockObject_MockObject $syncService */ + $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') + ->disableOriginalConstructor() + ->getMock(); + + /** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject $cal */ + $cal = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend') + ->disableOriginalConstructor() + ->getMock(); + $cal->expects($this->once())->method('getCalendarsForUser')->willReturn([]); + $cal->expects($this->once())->method('createCalendar')->with( + 'principals/users/newUser', + 'personal', ['{DAV:}displayname' => 'Personal']); + + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $card */ + $card = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') + ->disableOriginalConstructor() + ->getMock(); + $card->expects($this->once())->method('getAddressBooksForUser')->willReturn([]); + $card->expects($this->once())->method('createAddressBook')->with( + 'principals/users/newUser', + 'contacts', ['{DAV:}displayname' => 'Contacts']); + + $hm = new HookManager($userManager, $syncService, $cal, $card); + $hm->postLogin(['uid' => 'newUser']); + } + + public function testWithExisting() { + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->once())->method('getUID')->willReturn('newUser'); + + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ + $userManager = $this->getMockBuilder('\OCP\IUserManager') + ->disableOriginalConstructor() + ->getMock(); + $userManager->expects($this->once())->method('get')->willReturn($user); + + /** @var SyncService | \PHPUnit_Framework_MockObject_MockObject $syncService */ + $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') + ->disableOriginalConstructor() + ->getMock(); + + /** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject $cal */ + $cal = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend') + ->disableOriginalConstructor() + ->getMock(); + $cal->expects($this->once())->method('getCalendarsForUser')->willReturn([ + ['uri' => 'my-events'] + ]); + $cal->expects($this->never())->method('createCalendar'); + + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $card */ + $card = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') + ->disableOriginalConstructor() + ->getMock(); + $card->expects($this->once())->method('getAddressBooksForUser')->willReturn([ + ['uri' => 'my-contacts'] + ]); + $card->expects($this->never())->method('createAddressBook'); + + $hm = new HookManager($userManager, $syncService, $cal, $card); + $hm->postLogin(['uid' => 'newUser']); + } + + public function testWithBirthdayCalendar() { + $user = $this->getMockBuilder('\OCP\IUser') + ->disableOriginalConstructor() + ->getMock(); + $user->expects($this->once())->method('getUID')->willReturn('newUser'); + + /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ + $userManager = $this->getMockBuilder('\OCP\IUserManager') + ->disableOriginalConstructor() + ->getMock(); + $userManager->expects($this->once())->method('get')->willReturn($user); + + /** @var SyncService | \PHPUnit_Framework_MockObject_MockObject $syncService */ + $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') + ->disableOriginalConstructor() + ->getMock(); + + /** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject $cal */ + $cal = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend') + ->disableOriginalConstructor() + ->getMock(); + $cal->expects($this->once())->method('getCalendarsForUser')->willReturn([ + ['uri' => BirthdayService::BIRTHDAY_CALENDAR_URI] + ]); + $cal->expects($this->once())->method('createCalendar')->with( + 'principals/users/newUser', + 'personal', ['{DAV:}displayname' => 'Personal']); + + /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $card */ + $card = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') + ->disableOriginalConstructor() + ->getMock(); + $card->expects($this->once())->method('getAddressBooksForUser')->willReturn([]); + $card->expects($this->once())->method('createAddressBook')->with( + 'principals/users/newUser', + 'contacts', ['{DAV:}displayname' => 'Contacts']); + + $hm = new HookManager($userManager, $syncService, $cal, $card); + $hm->postLogin(['uid' => 'newUser']); + } +} diff --git a/apps/dav/tests/unit/DAV/Sharing/PluginTest.php b/apps/dav/tests/unit/DAV/Sharing/PluginTest.php new file mode 100644 index 00000000000..eccb59923f1 --- /dev/null +++ b/apps/dav/tests/unit/DAV/Sharing/PluginTest.php @@ -0,0 +1,83 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\DAV\Sharing; + + +use OCA\DAV\DAV\Sharing\IShareable; +use OCA\DAV\DAV\Sharing\Plugin; +use OCA\DAV\Connector\Sabre\Auth; +use OCP\IRequest; +use Sabre\DAV\Server; +use Sabre\DAV\SimpleCollection; +use Sabre\HTTP\Request; +use Sabre\HTTP\Response; +use Test\TestCase; + +class PluginTest extends TestCase { + + /** @var Plugin */ + private $plugin; + /** @var Server */ + private $server; + /** @var IShareable | \PHPUnit_Framework_MockObject_MockObject */ + private $book; + + public function setUp() { + parent::setUp(); + + /** @var Auth | \PHPUnit_Framework_MockObject_MockObject $authBackend */ + $authBackend = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Auth')->disableOriginalConstructor()->getMock(); + $authBackend->method('isDavAuthenticated')->willReturn(true); + + /** @var IRequest $request */ + $request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); + $this->plugin = new Plugin($authBackend, $request); + + $root = new SimpleCollection('root'); + $this->server = new \Sabre\DAV\Server($root); + /** @var SimpleCollection $node */ + $this->book = $this->getMockBuilder('OCA\DAV\DAV\Sharing\IShareable')-> + disableOriginalConstructor()-> + getMock(); + $this->book->method('getName')->willReturn('addressbook1.vcf'); + $root->addChild($this->book); + $this->plugin->initialize($this->server); + } + + public function testSharing() { + + $this->book->expects($this->once())->method('updateShares')->with([[ + 'href' => 'principal:principals/admin', + 'commonName' => null, + 'summary' => null, + 'readOnly' => false + ]], ['mailto:wilfredo@example.com']); + + // setup request + $request = new Request(); + $request->addHeader('Content-Type', 'application/xml'); + $request->setUrl('addressbook1.vcf'); + $request->setBody('principal:principals/admin mailto:wilfredo@example.com'); + $response = new Response(); + $this->plugin->httpPost($request, $response); + } +} diff --git a/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php b/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php new file mode 100644 index 00000000000..a09b24fa8d9 --- /dev/null +++ b/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php @@ -0,0 +1,131 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\DAV; + +use OCA\DAV\DAV\SystemPrincipalBackend; +use Test\TestCase; + +class SystemPrincipalBackendTest extends TestCase { + + /** + * @dataProvider providesPrefix + * @param $expected + * @param $prefix + */ + public function testGetPrincipalsByPrefix($expected, $prefix) { + $backend = new SystemPrincipalBackend(); + $result = $backend->getPrincipalsByPrefix($prefix); + $this->assertEquals($expected, $result); + } + + public function providesPrefix() { + return [ + [[], ''], + [[[ + 'uri' => 'principals/system/system', + '{DAV:}displayname' => 'system', + ]], 'principals/system'], + ]; + } + + /** + * @dataProvider providesPath + * @param $expected + * @param $path + */ + public function testGetPrincipalByPath($expected, $path) { + $backend = new SystemPrincipalBackend(); + $result = $backend->getPrincipalByPath($path); + $this->assertEquals($expected, $result); + } + + public function providesPath() { + return [ + [null, ''], + [null, 'principals'], + [null, 'principals/system'], + [[ + 'uri' => 'principals/system/system', + '{DAV:}displayname' => 'system', + ], 'principals/system/system'], + ]; + } + + /** + * @dataProvider providesPrincipalForGetGroupMemberSet + * @expectedException \Sabre\DAV\Exception + * @expectedExceptionMessage Principal not found + * + * @param string $principal + * @throws \Sabre\DAV\Exception + */ + public function testGetGroupMemberSetExceptional($principal) { + $backend = new SystemPrincipalBackend(); + $backend->getGroupMemberSet($principal); + } + + public function providesPrincipalForGetGroupMemberSet() { + return [ + [null], + ['principals/system'], + ]; + } + + /** + * @throws \Sabre\DAV\Exception + */ + public function testGetGroupMemberSet() { + $backend = new SystemPrincipalBackend(); + $result = $backend->getGroupMemberSet('principals/system/system'); + $this->assertEquals(['principals/system/system'], $result); + } + + /** + * @dataProvider providesPrincipalForGetGroupMembership + * @expectedException \Sabre\DAV\Exception + * @expectedExceptionMessage Principal not found + * + * @param string $principal + * @throws \Sabre\DAV\Exception + */ + public function testGetGroupMembershipExceptional($principal) { + $backend = new SystemPrincipalBackend(); + $backend->getGroupMembership($principal); + } + + public function providesPrincipalForGetGroupMembership() { + return [ + ['principals/system/a'], + ]; + } + + /** + * @throws \Sabre\DAV\Exception + */ + public function testGetGroupMembership() { + $backend = new SystemPrincipalBackend(); + $result = $backend->getGroupMembership('principals/system/system'); + $this->assertEquals([], $result); + } + + +} diff --git a/apps/dav/tests/unit/ServerTest.php b/apps/dav/tests/unit/ServerTest.php new file mode 100644 index 00000000000..f52585ad203 --- /dev/null +++ b/apps/dav/tests/unit/ServerTest.php @@ -0,0 +1,43 @@ + + * @author Thomas Müller + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ +namespace OCA\DAV\Tests\unit; + +use OCA\DAV\Server; +use OCP\IRequest; + +/** + * Class ServerTest + * + * @group DB + * + * @package OCA\DAV\Tests\Unit + */ +class ServerTest extends \Test\TestCase { + + public function test() { + /** @var IRequest $r */ + $r = $this->getMockBuilder('\OCP\IRequest') + ->disableOriginalConstructor()->getMock(); + $s = new Server($r, '/'); + $this->assertNotNull($s->server); + } +} diff --git a/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php b/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php new file mode 100644 index 00000000000..28f8c93a611 --- /dev/null +++ b/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php @@ -0,0 +1,160 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\SystemTag; + +use Sabre\DAV\Exception\NotFound; +use OC\SystemTag\SystemTag; +use OCP\SystemTag\TagNotFoundException; +use OCP\SystemTag\ISystemTag; + +class SystemTagMappingNodeTest extends \Test\TestCase { + + /** + * @var \OCP\SystemTag\ISystemTagManager + */ + private $tagManager; + + /** + * @var \OCP\SystemTag\ISystemTagObjectMapper + */ + private $tagMapper; + + /** + * @var \OCP\IUser + */ + private $user; + + protected function setUp() { + parent::setUp(); + + $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); + $this->tagMapper = $this->getMock('\OCP\SystemTag\ISystemTagObjectMapper'); + $this->user = $this->getMock('\OCP\IUser'); + } + + public function getMappingNode($tag = null) { + if ($tag === null) { + $tag = new SystemTag(1, 'Test', true, true); + } + return new \OCA\DAV\SystemTag\SystemTagMappingNode( + $tag, + 123, + 'files', + $this->user, + $this->tagManager, + $this->tagMapper + ); + } + + public function testGetters() { + $tag = new SystemTag(1, 'Test', true, false); + $node = $this->getMappingNode($tag); + $this->assertEquals('1', $node->getName()); + $this->assertEquals($tag, $node->getSystemTag()); + $this->assertEquals(123, $node->getObjectId()); + $this->assertEquals('files', $node->getObjectType()); + } + + public function testDeleteTag() { + $node = $this->getMappingNode(); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($node->getSystemTag()) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->once()) + ->method('canUserAssignTag') + ->with($node->getSystemTag()) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->never()) + ->method('deleteTags'); + $this->tagMapper->expects($this->once()) + ->method('unassignTags') + ->with(123, 'files', 1); + + $node->delete(); + } + + public function tagNodeDeleteProviderPermissionException() { + return [ + [ + // cannot unassign invisible tag + new SystemTag(1, 'Original', false, true), + 'Sabre\DAV\Exception\NotFound', + ], + [ + // cannot unassign non-assignable tag + new SystemTag(1, 'Original', true, false), + 'Sabre\DAV\Exception\Forbidden', + ], + ]; + } + + /** + * @dataProvider tagNodeDeleteProviderPermissionException + */ + public function testDeleteTagExpectedException(ISystemTag $tag, $expectedException) { + $this->tagManager->expects($this->any()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue($tag->isUserVisible())); + $this->tagManager->expects($this->any()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue($tag->isUserAssignable())); + $this->tagManager->expects($this->never()) + ->method('deleteTags'); + $this->tagMapper->expects($this->never()) + ->method('unassignTags'); + + $thrown = null; + try { + $this->getMappingNode($tag)->delete(); + } catch (\Exception $e) { + $thrown = $e; + } + + $this->assertInstanceOf($expectedException, $thrown); + } + + /** + * @expectedException Sabre\DAV\Exception\NotFound + */ + public function testDeleteTagNotFound() { + // assuming the tag existed at the time the node was created, + // but got deleted concurrently in the database + $tag = new SystemTag(1, 'Test', true, true); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue($tag->isUserVisible())); + $this->tagManager->expects($this->once()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue($tag->isUserAssignable())); + $this->tagMapper->expects($this->once()) + ->method('unassignTags') + ->with(123, 'files', 1) + ->will($this->throwException(new TagNotFoundException())); + + $this->getMappingNode($tag)->delete(); + } +} diff --git a/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php b/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php new file mode 100644 index 00000000000..ff5f6d1aa02 --- /dev/null +++ b/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php @@ -0,0 +1,312 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\SystemTag; + +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\MethodNotAllowed; +use Sabre\DAV\Exception\Conflict; + +use OC\SystemTag\SystemTag; +use OCP\SystemTag\TagNotFoundException; +use OCP\SystemTag\TagAlreadyExistsException; +use OCP\SystemTag\ISystemTag; + +class SystemTagNodeTest extends \Test\TestCase { + + /** + * @var \OCP\SystemTag\ISystemTagManager + */ + private $tagManager; + + /** + * @var \OCP\IUser + */ + private $user; + + protected function setUp() { + parent::setUp(); + + $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); + $this->user = $this->getMock('\OCP\IUser'); + } + + protected function getTagNode($isAdmin = true, $tag = null) { + if ($tag === null) { + $tag = new SystemTag(1, 'Test', true, true); + } + return new \OCA\DAV\SystemTag\SystemTagNode( + $tag, + $this->user, + $isAdmin, + $this->tagManager + ); + } + + public function adminFlagProvider() { + return [[true], [false]]; + } + + /** + * @dataProvider adminFlagProvider + */ + public function testGetters($isAdmin) { + $tag = new SystemTag('1', 'Test', true, true); + $node = $this->getTagNode($isAdmin, $tag); + $this->assertEquals('1', $node->getName()); + $this->assertEquals($tag, $node->getSystemTag()); + } + + /** + * @expectedException Sabre\DAV\Exception\MethodNotAllowed + */ + public function testSetName() { + $this->getTagNode()->setName('2'); + } + + public function tagNodeProvider() { + return [ + // admin + [ + true, + new SystemTag(1, 'Original', true, true), + ['Renamed', true, true] + ], + [ + true, + new SystemTag(1, 'Original', true, true), + ['Original', false, false] + ], + // non-admin + [ + // renaming allowed + false, + new SystemTag(1, 'Original', true, true), + ['Rename', true, true] + ], + ]; + } + + /** + * @dataProvider tagNodeProvider + */ + public function testUpdateTag($isAdmin, $originalTag, $changedArgs) { + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($originalTag) + ->will($this->returnValue($originalTag->isUserVisible() || $isAdmin)); + $this->tagManager->expects($this->once()) + ->method('canUserAssignTag') + ->with($originalTag) + ->will($this->returnValue($originalTag->isUserAssignable() || $isAdmin)); + $this->tagManager->expects($this->once()) + ->method('updateTag') + ->with(1, $changedArgs[0], $changedArgs[1], $changedArgs[2]); + $this->getTagNode($isAdmin, $originalTag) + ->update($changedArgs[0], $changedArgs[1], $changedArgs[2]); + } + + public function tagNodeProviderPermissionException() { + return [ + [ + // changing permissions not allowed + new SystemTag(1, 'Original', true, true), + ['Original', false, true], + 'Sabre\DAV\Exception\Forbidden', + ], + [ + // changing permissions not allowed + new SystemTag(1, 'Original', true, true), + ['Original', true, false], + 'Sabre\DAV\Exception\Forbidden', + ], + [ + // changing permissions not allowed + new SystemTag(1, 'Original', true, true), + ['Original', false, false], + 'Sabre\DAV\Exception\Forbidden', + ], + [ + // changing non-assignable not allowed + new SystemTag(1, 'Original', true, false), + ['Rename', true, false], + 'Sabre\DAV\Exception\Forbidden', + ], + [ + // changing non-assignable not allowed + new SystemTag(1, 'Original', true, false), + ['Original', true, true], + 'Sabre\DAV\Exception\Forbidden', + ], + [ + // invisible tag does not exist + new SystemTag(1, 'Original', false, false), + ['Rename', false, false], + 'Sabre\DAV\Exception\NotFound', + ], + ]; + } + + /** + * @dataProvider tagNodeProviderPermissionException + */ + public function testUpdateTagPermissionException($originalTag, $changedArgs, $expectedException = null) { + $this->tagManager->expects($this->any()) + ->method('canUserSeeTag') + ->with($originalTag) + ->will($this->returnValue($originalTag->isUserVisible())); + $this->tagManager->expects($this->any()) + ->method('canUserAssignTag') + ->with($originalTag) + ->will($this->returnValue($originalTag->isUserAssignable())); + $this->tagManager->expects($this->never()) + ->method('updateTag'); + + $thrown = null; + + try { + $this->getTagNode(false, $originalTag) + ->update($changedArgs[0], $changedArgs[1], $changedArgs[2]); + } catch (\Exception $e) { + $thrown = $e; + } + + $this->assertInstanceOf($expectedException, $thrown); + } + + /** + * @expectedException Sabre\DAV\Exception\Conflict + */ + public function testUpdateTagAlreadyExists() { + $tag = new SystemTag(1, 'tag1', true, true); + $this->tagManager->expects($this->any()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->any()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->once()) + ->method('updateTag') + ->with(1, 'Renamed', true, true) + ->will($this->throwException(new TagAlreadyExistsException())); + $this->getTagNode(false, $tag)->update('Renamed', true, true); + } + + /** + * @expectedException Sabre\DAV\Exception\NotFound + */ + public function testUpdateTagNotFound() { + $tag = new SystemTag(1, 'tag1', true, true); + $this->tagManager->expects($this->any()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->any()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->once()) + ->method('updateTag') + ->with(1, 'Renamed', true, true) + ->will($this->throwException(new TagNotFoundException())); + $this->getTagNode(false, $tag)->update('Renamed', true, true); + } + + /** + * @dataProvider adminFlagProvider + */ + public function testDeleteTag($isAdmin) { + $tag = new SystemTag(1, 'tag1', true, true); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->once()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->once()) + ->method('deleteTags') + ->with('1'); + $this->getTagNode($isAdmin, $tag)->delete(); + } + + public function tagNodeDeleteProviderPermissionException() { + return [ + [ + // cannot delete invisible tag + new SystemTag(1, 'Original', false, true), + 'Sabre\DAV\Exception\NotFound', + ], + [ + // cannot delete non-assignable tag + new SystemTag(1, 'Original', true, false), + 'Sabre\DAV\Exception\Forbidden', + ], + ]; + } + + /** + * @dataProvider tagNodeDeleteProviderPermissionException + */ + public function testDeleteTagPermissionException(ISystemTag $tag, $expectedException) { + $this->tagManager->expects($this->any()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue($tag->isUserVisible())); + $this->tagManager->expects($this->any()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue($tag->isUserAssignable())); + $this->tagManager->expects($this->never()) + ->method('deleteTags'); + + try { + $this->getTagNode(false, $tag)->delete(); + } catch (\Exception $e) { + $thrown = $e; + } + + $this->assertInstanceOf($expectedException, $thrown); + } + + /** + * @expectedException Sabre\DAV\Exception\NotFound + */ + public function testDeleteTagNotFound() { + $tag = new SystemTag(1, 'tag1', true, true); + $this->tagManager->expects($this->any()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue($tag->isUserVisible())); + $this->tagManager->expects($this->any()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue($tag->isUserAssignable())); + $this->tagManager->expects($this->once()) + ->method('deleteTags') + ->with('1') + ->will($this->throwException(new TagNotFoundException())); + $this->getTagNode(false, $tag)->delete(); + } +} diff --git a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php new file mode 100644 index 00000000000..154aa619866 --- /dev/null +++ b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php @@ -0,0 +1,734 @@ + + * @author Lukas Reschke + * @author Vincent Petry + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\SystemTag; + +use OC\SystemTag\SystemTag; +use OCP\IGroupManager; +use OCP\IUserSession; +use OCP\SystemTag\TagAlreadyExistsException; +use OCP\IUser; +use OCP\SystemTag\ISystemTag; + +class SystemTagPluginTest extends \Test\TestCase { + + const ID_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::ID_PROPERTYNAME; + const DISPLAYNAME_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::DISPLAYNAME_PROPERTYNAME; + const USERVISIBLE_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::USERVISIBLE_PROPERTYNAME; + const USERASSIGNABLE_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::USERASSIGNABLE_PROPERTYNAME; + const CANASSIGN_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::CANASSIGN_PROPERTYNAME; + const GROUPS_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::GROUPS_PROPERTYNAME; + + /** + * @var \Sabre\DAV\Server + */ + private $server; + + /** + * @var \Sabre\DAV\Tree + */ + private $tree; + + /** + * @var \OCP\SystemTag\ISystemTagManager + */ + private $tagManager; + + /** + * @var IGroupManager + */ + private $groupManager; + + /** + * @var IUserSession + */ + private $userSession; + + /** + * @var IUser + */ + private $user; + + /** + * @var \OCA\DAV\SystemTag\SystemTagPlugin + */ + private $plugin; + + public function setUp() { + parent::setUp(); + $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') + ->disableOriginalConstructor() + ->getMock(); + + $this->server = new \Sabre\DAV\Server($this->tree); + + $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); + $this->groupManager = $this->getMock('\OCP\IGroupManager'); + $this->user = $this->getMock('\OCP\IUser'); + $this->userSession = $this->getMock('\OCP\IUserSession'); + $this->userSession + ->expects($this->any()) + ->method('getUser') + ->willReturn($this->user); + $this->userSession + ->expects($this->any()) + ->method('isLoggedIn') + ->willReturn(true); + + $this->plugin = new \OCA\DAV\SystemTag\SystemTagPlugin( + $this->tagManager, + $this->groupManager, + $this->userSession + ); + $this->plugin->initialize($this->server); + } + + public function getPropertiesDataProvider() { + return [ + [ + new SystemTag(1, 'Test', true, true), + [], + [ + self::ID_PROPERTYNAME, + self::DISPLAYNAME_PROPERTYNAME, + self::USERVISIBLE_PROPERTYNAME, + self::USERASSIGNABLE_PROPERTYNAME, + self::CANASSIGN_PROPERTYNAME, + ], + [ + self::ID_PROPERTYNAME => '1', + self::DISPLAYNAME_PROPERTYNAME => 'Test', + self::USERVISIBLE_PROPERTYNAME => 'true', + self::USERASSIGNABLE_PROPERTYNAME => 'true', + self::CANASSIGN_PROPERTYNAME => 'true', + ] + ], + [ + new SystemTag(1, 'Test', true, false), + [], + [ + self::ID_PROPERTYNAME, + self::DISPLAYNAME_PROPERTYNAME, + self::USERVISIBLE_PROPERTYNAME, + self::USERASSIGNABLE_PROPERTYNAME, + self::CANASSIGN_PROPERTYNAME, + ], + [ + self::ID_PROPERTYNAME => '1', + self::DISPLAYNAME_PROPERTYNAME => 'Test', + self::USERVISIBLE_PROPERTYNAME => 'true', + self::USERASSIGNABLE_PROPERTYNAME => 'false', + self::CANASSIGN_PROPERTYNAME => 'false', + ] + ], + [ + new SystemTag(1, 'Test', true, false), + ['group1', 'group2'], + [ + self::ID_PROPERTYNAME, + self::GROUPS_PROPERTYNAME, + ], + [ + self::ID_PROPERTYNAME => '1', + self::GROUPS_PROPERTYNAME => 'group1|group2', + ] + ], + [ + new SystemTag(1, 'Test', true, true), + ['group1', 'group2'], + [ + self::ID_PROPERTYNAME, + self::GROUPS_PROPERTYNAME, + ], + [ + self::ID_PROPERTYNAME => '1', + // groups only returned when userAssignable is false + self::GROUPS_PROPERTYNAME => '', + ] + ], + ]; + } + + /** + * @dataProvider getPropertiesDataProvider + */ + public function testGetProperties(ISystemTag $systemTag, $groups, $requestedProperties, $expectedProperties) { + $this->user->expects($this->any()) + ->method('getUID') + ->willReturn('admin'); + $this->groupManager + ->expects($this->any()) + ->method('isAdmin') + ->with('admin') + ->willReturn(true); + + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getSystemTag') + ->will($this->returnValue($systemTag)); + + $this->tagManager->expects($this->any()) + ->method('canUserAssignTag') + ->will($this->returnValue($systemTag->isUserAssignable())); + + $this->tagManager->expects($this->any()) + ->method('getTagGroups') + ->will($this->returnValue($groups)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtag/1') + ->will($this->returnValue($node)); + + $propFind = new \Sabre\DAV\PropFind( + '/systemtag/1', + $requestedProperties, + 0 + ); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + + $result = $propFind->getResultForMultiStatus(); + + $this->assertEmpty($result[404]); + $this->assertEquals($expectedProperties, $result[200]); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testGetPropertiesForbidden() { + $systemTag = new SystemTag(1, 'Test', true, false); + $requestedProperties = [ + self::ID_PROPERTYNAME, + self::GROUPS_PROPERTYNAME, + ]; + $this->user->expects($this->once()) + ->method('getUID') + ->willReturn('admin'); + $this->groupManager + ->expects($this->once()) + ->method('isAdmin') + ->with('admin') + ->willReturn(false); + + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getSystemTag') + ->will($this->returnValue($systemTag)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtag/1') + ->will($this->returnValue($node)); + + $propFind = new \Sabre\DAV\PropFind( + '/systemtag/1', + $requestedProperties, + 0 + ); + + $this->plugin->handleGetProperties( + $propFind, + $node + ); + } + + public function testUpdatePropertiesAdmin() { + $systemTag = new SystemTag(1, 'Test', true, false); + $this->user->expects($this->any()) + ->method('getUID') + ->willReturn('admin'); + $this->groupManager + ->expects($this->any()) + ->method('isAdmin') + ->with('admin') + ->willReturn(true); + + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getSystemTag') + ->will($this->returnValue($systemTag)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtag/1') + ->will($this->returnValue($node)); + + $node->expects($this->once()) + ->method('update') + ->with('Test changed', false, true); + + $this->tagManager->expects($this->once()) + ->method('setTagGroups') + ->with($systemTag, ['group1', 'group2']); + + // properties to set + $propPatch = new \Sabre\DAV\PropPatch(array( + self::DISPLAYNAME_PROPERTYNAME => 'Test changed', + self::USERVISIBLE_PROPERTYNAME => 'false', + self::USERASSIGNABLE_PROPERTYNAME => 'true', + self::GROUPS_PROPERTYNAME => 'group1|group2', + )); + + $this->plugin->handleUpdateProperties( + '/systemtag/1', + $propPatch + ); + + $propPatch->commit(); + + // all requested properties removed, as they were processed already + $this->assertEmpty($propPatch->getRemainingMutations()); + + $result = $propPatch->getResult(); + $this->assertEquals(200, $result[self::DISPLAYNAME_PROPERTYNAME]); + $this->assertEquals(200, $result[self::USERASSIGNABLE_PROPERTYNAME]); + $this->assertEquals(200, $result[self::USERVISIBLE_PROPERTYNAME]); + } + + /** + * @expectedException \Sabre\DAV\Exception\Forbidden + */ + public function testUpdatePropertiesForbidden() { + $systemTag = new SystemTag(1, 'Test', true, false); + $this->user->expects($this->any()) + ->method('getUID') + ->willReturn('admin'); + $this->groupManager + ->expects($this->any()) + ->method('isAdmin') + ->with('admin') + ->willReturn(false); + + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') + ->disableOriginalConstructor() + ->getMock(); + $node->expects($this->any()) + ->method('getSystemTag') + ->will($this->returnValue($systemTag)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtag/1') + ->will($this->returnValue($node)); + + $node->expects($this->never()) + ->method('update'); + + $this->tagManager->expects($this->never()) + ->method('setTagGroups'); + + // properties to set + $propPatch = new \Sabre\DAV\PropPatch(array( + self::GROUPS_PROPERTYNAME => 'group1|group2', + )); + + $this->plugin->handleUpdateProperties( + '/systemtag/1', + $propPatch + ); + + $propPatch->commit(); + } + + public function createTagInsufficientPermissionsProvider() { + return [ + [true, false, ''], + [false, true, ''], + [true, true, 'group1|group2'], + ]; + } + /** + * @dataProvider createTagInsufficientPermissionsProvider + * @expectedException \Sabre\DAV\Exception\BadRequest + * @expectedExceptionMessage Not sufficient permissions + */ + public function testCreateNotAssignableTagAsRegularUser($userVisible, $userAssignable, $groups) { + $this->user->expects($this->once()) + ->method('getUID') + ->willReturn('admin'); + $this->groupManager + ->expects($this->once()) + ->method('isAdmin') + ->with('admin') + ->willReturn(false); + + $requestData = [ + 'name' => 'Test', + 'userVisible' => $userVisible, + 'userAssignable' => $userAssignable, + ]; + if (!empty($groups)) { + $requestData['groups'] = $groups; + } + $requestData = json_encode($requestData); + + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') + ->disableOriginalConstructor() + ->getMock(); + $this->tagManager->expects($this->never()) + ->method('createTag'); + $this->tagManager->expects($this->never()) + ->method('setTagGroups'); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtags') + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/systemtags')); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $this->plugin->httpPost($request, $response); + } + + public function testCreateTagInByIdCollectionAsRegularUser() { + $systemTag = new SystemTag(1, 'Test', true, false); + + $requestData = json_encode([ + 'name' => 'Test', + 'userVisible' => true, + 'userAssignable' => true, + ]); + + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') + ->disableOriginalConstructor() + ->getMock(); + $this->tagManager->expects($this->once()) + ->method('createTag') + ->with('Test', true, true) + ->will($this->returnValue($systemTag)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtags') + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/systemtags')); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $request->expects($this->once()) + ->method('getUrl') + ->will($this->returnValue('http://example.com/dav/systemtags')); + + $response->expects($this->once()) + ->method('setHeader') + ->with('Content-Location', 'http://example.com/dav/systemtags/1'); + + $this->plugin->httpPost($request, $response); + } + + public function createTagProvider() { + return [ + [true, false, ''], + [false, false, ''], + [true, false, 'group1|group2'], + ]; + } + + /** + * @dataProvider createTagProvider + */ + public function testCreateTagInByIdCollection($userVisible, $userAssignable, $groups) { + $this->user->expects($this->once()) + ->method('getUID') + ->willReturn('admin'); + $this->groupManager + ->expects($this->once()) + ->method('isAdmin') + ->with('admin') + ->willReturn(true); + + $systemTag = new SystemTag(1, 'Test', true, false); + + $requestData = [ + 'name' => 'Test', + 'userVisible' => $userVisible, + 'userAssignable' => $userAssignable, + ]; + if (!empty($groups)) { + $requestData['groups'] = $groups; + } + $requestData = json_encode($requestData); + + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') + ->disableOriginalConstructor() + ->getMock(); + $this->tagManager->expects($this->once()) + ->method('createTag') + ->with('Test', $userVisible, $userAssignable) + ->will($this->returnValue($systemTag)); + + if (!empty($groups)) { + $this->tagManager->expects($this->once()) + ->method('setTagGroups') + ->with($systemTag, explode('|', $groups)) + ->will($this->returnValue($systemTag)); + } else { + $this->tagManager->expects($this->never()) + ->method('setTagGroups'); + } + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtags') + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/systemtags')); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $request->expects($this->once()) + ->method('getUrl') + ->will($this->returnValue('http://example.com/dav/systemtags')); + + $response->expects($this->once()) + ->method('setHeader') + ->with('Content-Location', 'http://example.com/dav/systemtags/1'); + + $this->plugin->httpPost($request, $response); + } + + public function nodeClassProvider() { + return [ + ['\OCA\DAV\SystemTag\SystemTagsByIdCollection'], + ['\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection'], + ]; + } + + public function testCreateTagInMappingCollection() { + $this->user->expects($this->once()) + ->method('getUID') + ->willReturn('admin'); + $this->groupManager + ->expects($this->once()) + ->method('isAdmin') + ->with('admin') + ->willReturn(true); + + $systemTag = new SystemTag(1, 'Test', true, false); + + $requestData = json_encode([ + 'name' => 'Test', + 'userVisible' => true, + 'userAssignable' => false, + ]); + + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection') + ->disableOriginalConstructor() + ->getMock(); + + $this->tagManager->expects($this->once()) + ->method('createTag') + ->with('Test', true, false) + ->will($this->returnValue($systemTag)); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtags-relations/files/12') + ->will($this->returnValue($node)); + + $node->expects($this->once()) + ->method('createFile') + ->with(1); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/systemtags-relations/files/12')); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $request->expects($this->once()) + ->method('getBaseUrl') + ->will($this->returnValue('http://example.com/dav/')); + + $response->expects($this->once()) + ->method('setHeader') + ->with('Content-Location', 'http://example.com/dav/systemtags/1'); + + $this->plugin->httpPost($request, $response); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotFound + */ + public function testCreateTagToUnknownNode() { + $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection') + ->disableOriginalConstructor() + ->getMock(); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); + + $this->tagManager->expects($this->never()) + ->method('createTag'); + + $node->expects($this->never()) + ->method('createFile'); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/systemtags-relations/files/12')); + + $this->plugin->httpPost($request, $response); + } + + /** + * @dataProvider nodeClassProvider + * @expectedException \Sabre\DAV\Exception\Conflict + */ + public function testCreateTagConflict($nodeClass) { + $this->user->expects($this->once()) + ->method('getUID') + ->willReturn('admin'); + $this->groupManager + ->expects($this->once()) + ->method('isAdmin') + ->with('admin') + ->willReturn(true); + + $requestData = json_encode([ + 'name' => 'Test', + 'userVisible' => true, + 'userAssignable' => false, + ]); + + $node = $this->getMockBuilder($nodeClass) + ->disableOriginalConstructor() + ->getMock(); + $this->tagManager->expects($this->once()) + ->method('createTag') + ->with('Test', true, false) + ->will($this->throwException(new TagAlreadyExistsException('Tag already exists'))); + + $this->tree->expects($this->any()) + ->method('getNodeForPath') + ->with('/systemtags') + ->will($this->returnValue($node)); + + $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') + ->disableOriginalConstructor() + ->getMock(); + $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') + ->disableOriginalConstructor() + ->getMock(); + + $request->expects($this->once()) + ->method('getPath') + ->will($this->returnValue('/systemtags')); + + $request->expects($this->once()) + ->method('getBodyAsString') + ->will($this->returnValue($requestData)); + + $request->expects($this->once()) + ->method('getHeader') + ->with('Content-Type') + ->will($this->returnValue('application/json')); + + $this->plugin->httpPost($request, $response); + } + +} diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php new file mode 100644 index 00000000000..7722ac08df5 --- /dev/null +++ b/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php @@ -0,0 +1,233 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\SystemTag; + + +use OC\SystemTag\SystemTag; +use OCP\SystemTag\TagNotFoundException; + +class SystemTagsByIdCollectionTest extends \Test\TestCase { + + /** + * @var \OCP\SystemTag\ISystemTagManager + */ + private $tagManager; + + /** + * @var \OCP\IUser + */ + private $user; + + protected function setUp() { + parent::setUp(); + + $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); + } + + public function getNode($isAdmin = true) { + $this->user = $this->getMock('\OCP\IUser'); + $this->user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('testuser')); + $userSession = $this->getMock('\OCP\IUserSession'); + $userSession->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($this->user)); + $groupManager = $this->getMock('\OCP\IGroupManager'); + $groupManager->expects($this->any()) + ->method('isAdmin') + ->with('testuser') + ->will($this->returnValue($isAdmin)); + return new \OCA\DAV\SystemTag\SystemTagsByIdCollection( + $this->tagManager, + $userSession, + $groupManager + ); + } + + public function adminFlagProvider() { + return [[true], [false]]; + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testForbiddenCreateFile() { + $this->getNode()->createFile('555'); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testForbiddenCreateDirectory() { + $this->getNode()->createDirectory('789'); + } + + public function testGetChild() { + $tag = new SystemTag(123, 'Test', true, false); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue(true)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['123']) + ->will($this->returnValue([$tag])); + + $childNode = $this->getNode()->getChild('123'); + + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $childNode); + $this->assertEquals('123', $childNode->getName()); + $this->assertEquals($tag, $childNode->getSystemTag()); + } + + /** + * @expectedException Sabre\DAV\Exception\BadRequest + */ + public function testGetChildInvalidName() { + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['invalid']) + ->will($this->throwException(new \InvalidArgumentException())); + + $this->getNode()->getChild('invalid'); + } + + /** + * @expectedException Sabre\DAV\Exception\NotFound + */ + public function testGetChildNotFound() { + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['444']) + ->will($this->throwException(new TagNotFoundException())); + + $this->getNode()->getChild('444'); + } + + /** + * @expectedException Sabre\DAV\Exception\NotFound + */ + public function testGetChildUserNotVisible() { + $tag = new SystemTag(123, 'Test', false, false); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['123']) + ->will($this->returnValue([$tag])); + + $this->getNode(false)->getChild('123'); + } + + public function testGetChildrenAdmin() { + $tag1 = new SystemTag(123, 'One', true, false); + $tag2 = new SystemTag(456, 'Two', true, true); + + $this->tagManager->expects($this->once()) + ->method('getAllTags') + ->with(null) + ->will($this->returnValue([$tag1, $tag2])); + + $children = $this->getNode(true)->getChildren(); + + $this->assertCount(2, $children); + + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); + $this->assertEquals($tag1, $children[0]->getSystemTag()); + $this->assertEquals($tag2, $children[1]->getSystemTag()); + } + + public function testGetChildrenNonAdmin() { + $tag1 = new SystemTag(123, 'One', true, false); + $tag2 = new SystemTag(456, 'Two', true, true); + + $this->tagManager->expects($this->once()) + ->method('getAllTags') + ->with(true) + ->will($this->returnValue([$tag1, $tag2])); + + $children = $this->getNode(false)->getChildren(); + + $this->assertCount(2, $children); + + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); + $this->assertEquals($tag1, $children[0]->getSystemTag()); + $this->assertEquals($tag2, $children[1]->getSystemTag()); + } + + public function testGetChildrenEmpty() { + $this->tagManager->expects($this->once()) + ->method('getAllTags') + ->with(null) + ->will($this->returnValue([])); + $this->assertCount(0, $this->getNode()->getChildren()); + } + + public function childExistsProvider() { + return [ + [true, true], + [false, false], + ]; + } + + /** + * @dataProvider childExistsProvider + */ + public function testChildExists($userVisible, $expectedResult) { + $tag = new SystemTag(123, 'One', $userVisible, false); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue($userVisible)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['123']) + ->will($this->returnValue([$tag])); + + $this->assertEquals($expectedResult, $this->getNode()->childExists('123')); + } + + public function testChildExistsNotFound() { + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['123']) + ->will($this->throwException(new TagNotFoundException())); + + $this->assertFalse($this->getNode()->childExists('123')); + } + + /** + * @expectedException Sabre\DAV\Exception\BadRequest + */ + public function testChildExistsBadRequest() { + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['invalid']) + ->will($this->throwException(new \InvalidArgumentException())); + + $this->getNode()->childExists('invalid'); + } +} diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php new file mode 100644 index 00000000000..63ab6032f7a --- /dev/null +++ b/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php @@ -0,0 +1,348 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\SystemTag; + + +use OC\SystemTag\SystemTag; +use OCP\SystemTag\TagNotFoundException; + +class SystemTagsObjectMappingCollectionTest extends \Test\TestCase { + + /** + * @var \OCP\SystemTag\ISystemTagManager + */ + private $tagManager; + + /** + * @var \OCP\SystemTag\ISystemTagObjectMapper + */ + private $tagMapper; + + /** + * @var \OCP\IUser + */ + private $user; + + protected function setUp() { + parent::setUp(); + + $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); + $this->tagMapper = $this->getMock('\OCP\SystemTag\ISystemTagObjectMapper'); + + $this->user = $this->getMock('\OCP\IUser'); + } + + public function getNode() { + return new \OCA\DAV\SystemTag\SystemTagsObjectMappingCollection ( + 111, + 'files', + $this->user, + $this->tagManager, + $this->tagMapper + ); + } + + public function testAssignTag() { + $tag = new SystemTag('1', 'Test', true, true); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue(true)); + $this->tagManager->expects($this->once()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue(true)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['555']) + ->will($this->returnValue([$tag])); + $this->tagMapper->expects($this->once()) + ->method('assignTags') + ->with(111, 'files', '555'); + + $this->getNode()->createFile('555'); + } + + public function permissionsProvider() { + return [ + // invisible, tag does not exist for user + [false, true, '\Sabre\DAV\Exception\PreconditionFailed'], + // visible but static, cannot assign tag + [true, false, '\Sabre\DAV\Exception\Forbidden'], + ]; + } + + /** + * @dataProvider permissionsProvider + */ + public function testAssignTagNoPermission($userVisible, $userAssignable, $expectedException) { + $tag = new SystemTag('1', 'Test', $userVisible, $userAssignable); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue($userVisible)); + $this->tagManager->expects($this->any()) + ->method('canUserAssignTag') + ->with($tag) + ->will($this->returnValue($userAssignable)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['555']) + ->will($this->returnValue([$tag])); + $this->tagMapper->expects($this->never()) + ->method('assignTags'); + + $thrown = null; + try { + $this->getNode()->createFile('555'); + } catch (\Exception $e) { + $thrown = $e; + } + + $this->assertInstanceOf($expectedException, $thrown); + } + + /** + * @expectedException Sabre\DAV\Exception\PreconditionFailed + */ + public function testAssignTagNotFound() { + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['555']) + ->will($this->throwException(new TagNotFoundException())); + + $this->getNode()->createFile('555'); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testForbiddenCreateDirectory() { + $this->getNode()->createDirectory('789'); + } + + public function testGetChild() { + $tag = new SystemTag(555, 'TheTag', true, false); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue(true)); + + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '555', true) + ->will($this->returnValue(true)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['555']) + ->will($this->returnValue(['555' => $tag])); + + $childNode = $this->getNode()->getChild('555'); + + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $childNode); + $this->assertEquals('555', $childNode->getName()); + } + + /** + * @expectedException \Sabre\DAV\Exception\NotFound + */ + public function testGetChildNonVisible() { + $tag = new SystemTag(555, 'TheTag', false, false); + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue(false)); + + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '555', true) + ->will($this->returnValue(true)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['555']) + ->will($this->returnValue(['555' => $tag])); + + $this->getNode()->getChild('555'); + } + + /** + * @expectedException Sabre\DAV\Exception\NotFound + */ + public function testGetChildRelationNotFound() { + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '777') + ->will($this->returnValue(false)); + + $this->getNode()->getChild('777'); + } + + /** + * @expectedException Sabre\DAV\Exception\BadRequest + */ + public function testGetChildInvalidId() { + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', 'badid') + ->will($this->throwException(new \InvalidArgumentException())); + + $this->getNode()->getChild('badid'); + } + + /** + * @expectedException Sabre\DAV\Exception\NotFound + */ + public function testGetChildTagDoesNotExist() { + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '777') + ->will($this->throwException(new TagNotFoundException())); + + $this->getNode()->getChild('777'); + } + + public function testGetChildren() { + $tag1 = new SystemTag(555, 'TagOne', true, false); + $tag2 = new SystemTag(556, 'TagTwo', true, true); + $tag3 = new SystemTag(557, 'InvisibleTag', false, true); + + $this->tagMapper->expects($this->once()) + ->method('getTagIdsForObjects') + ->with([111], 'files') + ->will($this->returnValue(['111' => ['555', '556', '557']])); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['555', '556', '557']) + ->will($this->returnValue(['555' => $tag1, '556' => $tag2, '557' => $tag3])); + + $this->tagManager->expects($this->exactly(3)) + ->method('canUserSeeTag') + ->will($this->returnCallback(function($tag) { + return $tag->isUserVisible(); + })); + + $children = $this->getNode()->getChildren(); + + $this->assertCount(2, $children); + + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $children[0]); + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $children[1]); + + $this->assertEquals(111, $children[0]->getObjectId()); + $this->assertEquals('files', $children[0]->getObjectType()); + $this->assertEquals($tag1, $children[0]->getSystemTag()); + + $this->assertEquals(111, $children[1]->getObjectId()); + $this->assertEquals('files', $children[1]->getObjectType()); + $this->assertEquals($tag2, $children[1]->getSystemTag()); + } + + public function testChildExistsWithVisibleTag() { + $tag = new SystemTag(555, 'TagOne', true, false); + + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '555') + ->will($this->returnValue(true)); + + $this->tagManager->expects($this->once()) + ->method('canUserSeeTag') + ->with($tag) + ->will($this->returnValue(true)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['555']) + ->will($this->returnValue([$tag])); + + $this->assertTrue($this->getNode()->childExists('555')); + } + + public function testChildExistsWithInvisibleTag() { + $tag = new SystemTag(555, 'TagOne', false, false); + + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '555') + ->will($this->returnValue(true)); + + $this->tagManager->expects($this->once()) + ->method('getTagsByIds') + ->with(['555']) + ->will($this->returnValue([$tag])); + + $this->assertFalse($this->getNode()->childExists('555')); + } + + public function testChildExistsNotFound() { + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '555') + ->will($this->returnValue(false)); + + $this->assertFalse($this->getNode()->childExists('555')); + } + + public function testChildExistsTagNotFound() { + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '555') + ->will($this->throwException(new TagNotFoundException())); + + $this->assertFalse($this->getNode()->childExists('555')); + } + + /** + * @expectedException Sabre\DAV\Exception\BadRequest + */ + public function testChildExistsInvalidId() { + $this->tagMapper->expects($this->once()) + ->method('haveTag') + ->with([111], 'files', '555') + ->will($this->throwException(new \InvalidArgumentException())); + + $this->getNode()->childExists('555'); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testDelete() { + $this->getNode()->delete(); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testSetName() { + $this->getNode()->setName('somethingelse'); + } + + public function testGetName() { + $this->assertEquals('111', $this->getNode()->getName()); + } +} diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php new file mode 100644 index 00000000000..036b4150426 --- /dev/null +++ b/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php @@ -0,0 +1,160 @@ + + * + * @copyright Copyright (c) 2016, ownCloud, Inc. + * @license AGPL-3.0 + * + * This code is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License, version 3, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License, version 3, + * along with this program. If not, see + * + */ + +namespace OCA\DAV\Tests\unit\SystemTag; + +class SystemTagsObjectTypeCollectionTest extends \Test\TestCase { + + /** + * @var \OCA\DAV\SystemTag\SystemTagsObjectTypeCollection + */ + private $node; + + /** + * @var \OCP\SystemTag\ISystemTagManager + */ + private $tagManager; + + /** + * @var \OCP\SystemTag\ISystemTagObjectMapper + */ + private $tagMapper; + + /** + * @var \OCP\Files\Folder + */ + private $userFolder; + + protected function setUp() { + parent::setUp(); + + $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); + $this->tagMapper = $this->getMock('\OCP\SystemTag\ISystemTagObjectMapper'); + + $user = $this->getMock('\OCP\IUser'); + $user->expects($this->any()) + ->method('getUID') + ->will($this->returnValue('testuser')); + $userSession = $this->getMock('\OCP\IUserSession'); + $userSession->expects($this->any()) + ->method('getUser') + ->will($this->returnValue($user)); + $groupManager = $this->getMock('\OCP\IGroupManager'); + $groupManager->expects($this->any()) + ->method('isAdmin') + ->with('testuser') + ->will($this->returnValue(true)); + + $this->userFolder = $this->getMock('\OCP\Files\Folder'); + + $fileRoot = $this->getMock('\OCP\Files\IRootFolder'); + $fileRoot->expects($this->any()) + ->method('getUserfolder') + ->with('testuser') + ->will($this->returnValue($this->userFolder)); + + $this->node = new \OCA\DAV\SystemTag\SystemTagsObjectTypeCollection( + 'files', + $this->tagManager, + $this->tagMapper, + $userSession, + $groupManager, + $fileRoot + ); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testForbiddenCreateFile() { + $this->node->createFile('555'); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testForbiddenCreateDirectory() { + $this->node->createDirectory('789'); + } + + public function testGetChild() { + $this->userFolder->expects($this->once()) + ->method('getById') + ->with('555') + ->will($this->returnValue([true])); + $childNode = $this->node->getChild('555'); + + $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection', $childNode); + $this->assertEquals('555', $childNode->getName()); + } + + /** + * @expectedException Sabre\DAV\Exception\NotFound + */ + public function testGetChildWithoutAccess() { + $this->userFolder->expects($this->once()) + ->method('getById') + ->with('555') + ->will($this->returnValue([])); + $this->node->getChild('555'); + } + + /** + * @expectedException Sabre\DAV\Exception\MethodNotAllowed + */ + public function testGetChildren() { + $this->node->getChildren(); + } + + public function testChildExists() { + $this->userFolder->expects($this->once()) + ->method('getById') + ->with('123') + ->will($this->returnValue([true])); + $this->assertTrue($this->node->childExists('123')); + } + + public function testChildExistsWithoutAccess() { + $this->userFolder->expects($this->once()) + ->method('getById') + ->with('555') + ->will($this->returnValue([])); + $this->assertFalse($this->node->childExists('555')); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testDelete() { + $this->node->delete(); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testSetName() { + $this->node->setName('somethingelse'); + } + + public function testGetName() { + $this->assertEquals('files', $this->node->getName()); + } +} diff --git a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php new file mode 100644 index 00000000000..b8fb1aa12e4 --- /dev/null +++ b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php @@ -0,0 +1,48 @@ +assertEquals($expected, $content); + } + + function providesNodes() { + return[ + 'one node only' => ['1234567890', [ + $this->buildNode('0', '1234567890') + ]], + 'two nodes' => ['1234567890', [ + $this->buildNode('1', '67890'), + $this->buildNode('0', '12345') + ]] + ]; + } + + private function buildNode($name, $data) { + $node = $this->getMockBuilder('\Sabre\DAV\File') + ->setMethods(['getName', 'get', 'getSize']) + ->getMockForAbstractClass(); + + $node->expects($this->any()) + ->method('getName') + ->willReturn($name); + + $node->expects($this->any()) + ->method('get') + ->willReturn($data); + + $node->expects($this->any()) + ->method('getSize') + ->willReturn(strlen($data)); + + return $node; + } +} + diff --git a/apps/dav/tests/unit/Upload/FutureFileTest.php b/apps/dav/tests/unit/Upload/FutureFileTest.php new file mode 100644 index 00000000000..7e1c84ef5ad --- /dev/null +++ b/apps/dav/tests/unit/Upload/FutureFileTest.php @@ -0,0 +1,91 @@ +mockFutureFile(); + $this->assertEquals('application/octet-stream', $f->getContentType()); + } + + public function testGetETag() { + $f = $this->mockFutureFile(); + $this->assertEquals('1234567890', $f->getETag()); + } + + public function testGetName() { + $f = $this->mockFutureFile(); + $this->assertEquals('foo.txt', $f->getName()); + } + + public function testGetLastModified() { + $f = $this->mockFutureFile(); + $this->assertEquals(12121212, $f->getLastModified()); + } + + public function testGetSize() { + $f = $this->mockFutureFile(); + $this->assertEquals(0, $f->getSize()); + } + + public function testGet() { + $f = $this->mockFutureFile(); + $stream = $f->get(); + $this->assertTrue(is_resource($stream)); + } + + public function testDelete() { + $d = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->setMethods(['delete']) + ->getMock(); + + $d->expects($this->once()) + ->method('delete'); + + $f = new \OCA\DAV\Upload\FutureFile($d, 'foo.txt'); + $f->delete(); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testPut() { + $f = $this->mockFutureFile(); + $f->put(''); + } + + /** + * @expectedException Sabre\DAV\Exception\Forbidden + */ + public function testSetName() { + $f = $this->mockFutureFile(); + $f->setName(''); + } + + /** + * @return \OCA\DAV\Upload\FutureFile + */ + private function mockFutureFile() { + $d = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Directory') + ->disableOriginalConstructor() + ->setMethods(['getETag', 'getLastModified', 'getChildren']) + ->getMock(); + + $d->expects($this->any()) + ->method('getETag') + ->willReturn('1234567890'); + + $d->expects($this->any()) + ->method('getLastModified') + ->willReturn(12121212); + + $d->expects($this->any()) + ->method('getChildren') + ->willReturn([]); + + return new \OCA\DAV\Upload\FutureFile($d, 'foo.txt'); + } +} + diff --git a/apps/dav/tests/unit/appinfo/applicationtest.php b/apps/dav/tests/unit/appinfo/applicationtest.php deleted file mode 100644 index 05dd75b2c68..00000000000 --- a/apps/dav/tests/unit/appinfo/applicationtest.php +++ /dev/null @@ -1,62 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\AppInfo; - -use OCA\DAV\AppInfo\Application; -use OCP\Contacts\IManager; -use Test\TestCase; - -/** - * Class ApplicationTest - * - * @group DB - * - * @package OCA\DAV\Tests\Unit\AppInfo - */ -class ApplicationTest extends TestCase { - public function test() { - $app = new Application(); - $c = $app->getContainer(); - - // assert service instances in the container are properly setup - $s = $c->query('ContactsManager'); - $this->assertInstanceOf('OCA\DAV\CardDAV\ContactsManager', $s); - $s = $c->query('CardDavBackend'); - $this->assertInstanceOf('OCA\DAV\CardDAV\CardDavBackend', $s); - } - - public function testContactsManagerSetup() { - $app = new Application(); - $c = $app->getContainer(); - $c->registerService('CardDavBackend', function($c) { - $service = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); - $service->method('getAddressBooksForUser')->willReturn([]); - return $service; - }); - - // assert setupContactsProvider() is proper - /** @var IManager | \PHPUnit_Framework_MockObject_MockObject $cm */ - $cm = $this->getMockBuilder('OCP\Contacts\IManager')->disableOriginalConstructor()->getMock(); - $app->setupContactsProvider($cm, 'xxx'); - $this->assertTrue(true); - } -} diff --git a/apps/dav/tests/unit/caldav/caldavbackendtest.php b/apps/dav/tests/unit/caldav/caldavbackendtest.php deleted file mode 100644 index 89be5671ca8..00000000000 --- a/apps/dav/tests/unit/caldav/caldavbackendtest.php +++ /dev/null @@ -1,504 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace Tests\Connector\Sabre; - -use DateTime; -use DateTimeZone; -use OCA\DAV\CalDAV\CalDavBackend; -use OCA\DAV\CalDAV\Calendar; -use OCA\DAV\Connector\Sabre\Principal; -use OCP\IL10N; -use Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet; -use Sabre\DAV\PropPatch; -use Sabre\DAV\Xml\Property\Href; -use Sabre\DAVACL\IACL; -use Test\TestCase; - -/** - * Class CalDavBackendTest - * - * @group DB - * - * @package Tests\Connector\Sabre - */ -class CalDavBackendTest extends TestCase { - - /** @var CalDavBackend */ - private $backend; - - /** @var Principal | \PHPUnit_Framework_MockObject_MockObject */ - private $principal; - - const UNIT_TEST_USER = 'principals/users/caldav-unit-test'; - const UNIT_TEST_USER1 = 'principals/users/caldav-unit-test1'; - const UNIT_TEST_GROUP = 'principals/groups/caldav-unit-test-group'; - - public function setUp() { - parent::setUp(); - - $this->principal = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Principal') - ->disableOriginalConstructor() - ->setMethods(['getPrincipalByPath', 'getGroupMembership']) - ->getMock(); - $this->principal->expects($this->any())->method('getPrincipalByPath') - ->willReturn([ - 'uri' => 'principals/best-friend' - ]); - $this->principal->expects($this->any())->method('getGroupMembership') - ->withAnyParameters() - ->willReturn([self::UNIT_TEST_GROUP]); - - $db = \OC::$server->getDatabaseConnection(); - $this->backend = new CalDavBackend($db, $this->principal); - - $this->tearDown(); - } - - public function tearDown() { - parent::tearDown(); - - if (is_null($this->backend)) { - return; - } - $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); - foreach ($books as $book) { - $this->backend->deleteCalendar($book['id']); - } - $subscriptions = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); - foreach ($subscriptions as $subscription) { - $this->backend->deleteSubscription($subscription['id']); - } - } - - public function testCalendarOperations() { - - $calendarId = $this->createTestCalendar(); - - // update it's display name - $patch = new PropPatch([ - '{DAV:}displayname' => 'Unit test', - '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'Calendar used for unit testing' - ]); - $this->backend->updateCalendar($calendarId, $patch); - $patch->commit(); - $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $this->assertEquals('Unit test', $books[0]['{DAV:}displayname']); - $this->assertEquals('Calendar used for unit testing', $books[0]['{urn:ietf:params:xml:ns:caldav}calendar-description']); - - // delete the address book - $this->backend->deleteCalendar($books[0]['id']); - $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); - $this->assertEquals(0, count($books)); - } - - public function providesSharingData() { - return [ - [true, true, true, false, [ - [ - 'href' => 'principal:' . self::UNIT_TEST_USER1, - 'readOnly' => false - ], - [ - 'href' => 'principal:' . self::UNIT_TEST_GROUP, - 'readOnly' => true - ] - ]], - [true, false, false, false, [ - [ - 'href' => 'principal:' . self::UNIT_TEST_USER1, - 'readOnly' => true - ], - ]], - - ]; - } - - /** - * @dataProvider providesSharingData - */ - public function testCalendarSharing($userCanRead, $userCanWrite, $groupCanRead, $groupCanWrite, $add) { - - /** @var IL10N | \PHPUnit_Framework_MockObject_MockObject $l10n */ - $l10n = $this->getMockBuilder('\OCP\IL10N') - ->disableOriginalConstructor()->getMock(); - $l10n - ->expects($this->any()) - ->method('t') - ->will($this->returnCallback(function ($text, $parameters = array()) { - return vsprintf($text, $parameters); - })); - - $calendarId = $this->createTestCalendar(); - $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $calendar = new Calendar($this->backend, $books[0], $l10n); - $this->backend->updateShares($calendar, $add, []); - $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER1); - $this->assertEquals(1, count($books)); - $calendar = new Calendar($this->backend, $books[0], $l10n); - $acl = $calendar->getACL(); - $this->assertAcl(self::UNIT_TEST_USER, '{DAV:}read', $acl); - $this->assertAcl(self::UNIT_TEST_USER, '{DAV:}write', $acl); - $this->assertAccess($userCanRead, self::UNIT_TEST_USER1, '{DAV:}read', $acl); - $this->assertAccess($userCanWrite, self::UNIT_TEST_USER1, '{DAV:}write', $acl); - $this->assertAccess($groupCanRead, self::UNIT_TEST_GROUP, '{DAV:}read', $acl); - $this->assertAccess($groupCanWrite, self::UNIT_TEST_GROUP, '{DAV:}write', $acl); - $this->assertEquals(self::UNIT_TEST_USER, $calendar->getOwner()); - - // test acls on the child - $uri = $this->getUniqueID('calobj'); - $calData = <<<'EOD' -BEGIN:VCALENDAR -VERSION:2.0 -PRODID:ownCloud Calendar -BEGIN:VEVENT -CREATED;VALUE=DATE-TIME:20130910T125139Z -UID:47d15e3ec8 -LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z -DTSTAMP;VALUE=DATE-TIME:20130910T125139Z -SUMMARY:Test Event -DTSTART;VALUE=DATE-TIME:20130912T130000Z -DTEND;VALUE=DATE-TIME:20130912T140000Z -CLASS:PUBLIC -END:VEVENT -END:VCALENDAR -EOD; - - $this->backend->createCalendarObject($calendarId, $uri, $calData); - - /** @var IACL $child */ - $child = $calendar->getChild($uri); - $acl = $child->getACL(); - $this->assertAcl(self::UNIT_TEST_USER, '{DAV:}read', $acl); - $this->assertAcl(self::UNIT_TEST_USER, '{DAV:}write', $acl); - $this->assertAccess($userCanRead, self::UNIT_TEST_USER1, '{DAV:}read', $acl); - $this->assertAccess($userCanWrite, self::UNIT_TEST_USER1, '{DAV:}write', $acl); - $this->assertAccess($groupCanRead, self::UNIT_TEST_GROUP, '{DAV:}read', $acl); - $this->assertAccess($groupCanWrite, self::UNIT_TEST_GROUP, '{DAV:}write', $acl); - - // delete the address book - $this->backend->deleteCalendar($books[0]['id']); - $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); - $this->assertEquals(0, count($books)); - } - - public function testCalendarObjectsOperations() { - - $calendarId = $this->createTestCalendar(); - - // create a card - $uri = $this->getUniqueID('calobj'); - $calData = <<<'EOD' -BEGIN:VCALENDAR -VERSION:2.0 -PRODID:ownCloud Calendar -BEGIN:VEVENT -CREATED;VALUE=DATE-TIME:20130910T125139Z -UID:47d15e3ec8 -LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z -DTSTAMP;VALUE=DATE-TIME:20130910T125139Z -SUMMARY:Test Event -DTSTART;VALUE=DATE-TIME:20130912T130000Z -DTEND;VALUE=DATE-TIME:20130912T140000Z -CLASS:PUBLIC -END:VEVENT -END:VCALENDAR -EOD; - - $this->backend->createCalendarObject($calendarId, $uri, $calData); - - // get all the cards - $calendarObjects = $this->backend->getCalendarObjects($calendarId); - $this->assertEquals(1, count($calendarObjects)); - $this->assertEquals($calendarId, $calendarObjects[0]['calendarid']); - - // get the cards - $calendarObject = $this->backend->getCalendarObject($calendarId, $uri); - $this->assertNotNull($calendarObject); - $this->assertArrayHasKey('id', $calendarObject); - $this->assertArrayHasKey('uri', $calendarObject); - $this->assertArrayHasKey('lastmodified', $calendarObject); - $this->assertArrayHasKey('etag', $calendarObject); - $this->assertArrayHasKey('size', $calendarObject); - $this->assertEquals($calData, $calendarObject['calendardata']); - - // update the card - $calData = <<<'EOD' -BEGIN:VCALENDAR -VERSION:2.0 -PRODID:ownCloud Calendar -BEGIN:VEVENT -CREATED;VALUE=DATE-TIME:20130910T125139Z -UID:47d15e3ec8 -LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z -DTSTAMP;VALUE=DATE-TIME:20130910T125139Z -SUMMARY:Test Event -DTSTART;VALUE=DATE-TIME:20130912T130000Z -DTEND;VALUE=DATE-TIME:20130912T140000Z -END:VEVENT -END:VCALENDAR -EOD; - $this->backend->updateCalendarObject($calendarId, $uri, $calData); - $calendarObject = $this->backend->getCalendarObject($calendarId, $uri); - $this->assertEquals($calData, $calendarObject['calendardata']); - - // delete the card - $this->backend->deleteCalendarObject($calendarId, $uri); - $calendarObjects = $this->backend->getCalendarObjects($calendarId); - $this->assertEquals(0, count($calendarObjects)); - } - - public function testMultiCalendarObjects() { - - $calendarId = $this->createTestCalendar(); - - // create an event - $calData = <<<'EOD' -BEGIN:VCALENDAR -VERSION:2.0 -PRODID:ownCloud Calendar -BEGIN:VEVENT -CREATED;VALUE=DATE-TIME:20130910T125139Z -UID:47d15e3ec8 -LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z -DTSTAMP;VALUE=DATE-TIME:20130910T125139Z -SUMMARY:Test Event -DTSTART;VALUE=DATE-TIME:20130912T130000Z -DTEND;VALUE=DATE-TIME:20130912T140000Z -CLASS:PUBLIC -END:VEVENT -END:VCALENDAR -EOD; - $uri0 = $this->getUniqueID('card'); - $this->backend->createCalendarObject($calendarId, $uri0, $calData); - $uri1 = $this->getUniqueID('card'); - $this->backend->createCalendarObject($calendarId, $uri1, $calData); - $uri2 = $this->getUniqueID('card'); - $this->backend->createCalendarObject($calendarId, $uri2, $calData); - - // get all the cards - $calendarObjects = $this->backend->getCalendarObjects($calendarId); - $this->assertEquals(3, count($calendarObjects)); - - // get the cards - $calendarObjects = $this->backend->getMultipleCalendarObjects($calendarId, [$uri1, $uri2]); - $this->assertEquals(2, count($calendarObjects)); - foreach($calendarObjects as $card) { - $this->assertArrayHasKey('id', $card); - $this->assertArrayHasKey('uri', $card); - $this->assertArrayHasKey('lastmodified', $card); - $this->assertArrayHasKey('etag', $card); - $this->assertArrayHasKey('size', $card); - $this->assertEquals($calData, $card['calendardata']); - } - - // delete the card - $this->backend->deleteCalendarObject($calendarId, $uri0); - $this->backend->deleteCalendarObject($calendarId, $uri1); - $this->backend->deleteCalendarObject($calendarId, $uri2); - $calendarObjects = $this->backend->getCalendarObjects($calendarId); - $this->assertEquals(0, count($calendarObjects)); - } - - /** - * @dataProvider providesCalendarQueryParameters - */ - public function testCalendarQuery($expectedEventsInResult, $propFilters, $compFilter) { - $calendarId = $this->createTestCalendar(); - $events = []; - $events[0] = $this->createEvent($calendarId, '20130912T130000Z', '20130912T140000Z'); - $events[1] = $this->createEvent($calendarId, '20130912T150000Z', '20130912T170000Z'); - $events[2] = $this->createEvent($calendarId, '20130912T173000Z', '20130912T220000Z'); - $events[3] = $this->createEvent($calendarId, '21130912T130000Z', '22130912T130000Z'); - - $result = $this->backend->calendarQuery($calendarId, [ - 'name' => '', - 'prop-filters' => $propFilters, - 'comp-filters' => $compFilter - ]); - - $expectedEventsInResult = array_map(function($index) use($events) { - return $events[$index]; - }, $expectedEventsInResult); - $this->assertEquals($expectedEventsInResult, $result, '', 0.0, 10, true); - } - - public function testGetCalendarObjectByUID() { - $calendarId = $this->createTestCalendar(); - $this->createEvent($calendarId, '20130912T130000Z', '20130912T140000Z'); - - $co = $this->backend->getCalendarObjectByUID(self::UNIT_TEST_USER, '47d15e3ec8'); - $this->assertNotNull($co); - } - - public function providesCalendarQueryParameters() { - return [ - 'all' => [[0, 1, 2, 3], [], []], - 'only-todos' => [[], ['name' => 'VTODO'], []], - 'only-events' => [[0, 1, 2, 3], [], [['name' => 'VEVENT', 'is-not-defined' => false, 'comp-filters' => [], 'time-range' => ['start' => null, 'end' => null], 'prop-filters' => []]],], - 'start' => [[1, 2, 3], [], [['name' => 'VEVENT', 'is-not-defined' => false, 'comp-filters' => [], 'time-range' => ['start' => new DateTime('2013-09-12 14:00:00', new DateTimeZone('UTC')), 'end' => null], 'prop-filters' => []]],], - 'end' => [[0], [], [['name' => 'VEVENT', 'is-not-defined' => false, 'comp-filters' => [], 'time-range' => ['start' => null, 'end' => new DateTime('2013-09-12 14:00:00', new DateTimeZone('UTC'))], 'prop-filters' => []]],], - 'future' => [[3], [], [['name' => 'VEVENT', 'is-not-defined' => false, 'comp-filters' => [], 'time-range' => ['start' => new DateTime('2099-09-12 14:00:00', new DateTimeZone('UTC')), 'end' => null], 'prop-filters' => []]],], - ]; - } - - private function createTestCalendar() { - $this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', [ - '{http://apple.com/ns/ical/}calendar-color' => '#1C4587FF' - ]); - $calendars = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($calendars)); - $this->assertEquals(self::UNIT_TEST_USER, $calendars[0]['principaluri']); - /** @var SupportedCalendarComponentSet $components */ - $components = $calendars[0]['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set']; - $this->assertEquals(['VEVENT','VTODO'], $components->getValue()); - $color = $calendars[0]['{http://apple.com/ns/ical/}calendar-color']; - $this->assertEquals('#1C4587FF', $color); - $this->assertEquals('Example', $calendars[0]['uri']); - $this->assertEquals('Example', $calendars[0]['{DAV:}displayname']); - $calendarId = $calendars[0]['id']; - - return $calendarId; - } - - private function createEvent($calendarId, $start = '20130912T130000Z', $end = '20130912T140000Z') { - - $calData = <<getUniqueID('event'); - $this->backend->createCalendarObject($calendarId, $uri0, $calData); - - return $uri0; - } - - public function testSyncSupport() { - $calendarId = $this->createTestCalendar(); - - // fist call without synctoken - $changes = $this->backend->getChangesForCalendar($calendarId, '', 1); - $syncToken = $changes['syncToken']; - - // add a change - $event = $this->createEvent($calendarId, '20130912T130000Z', '20130912T140000Z'); - - // look for changes - $changes = $this->backend->getChangesForCalendar($calendarId, $syncToken, 1); - $this->assertEquals($event, $changes['added'][0]); - } - - public function testSubscriptions() { - $id = $this->backend->createSubscription(self::UNIT_TEST_USER, 'Subscription', [ - '{http://calendarserver.org/ns/}source' => new Href('test-source') - ]); - - $subscriptions = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($subscriptions)); - $this->assertEquals($id, $subscriptions[0]['id']); - - $patch = new PropPatch([ - '{DAV:}displayname' => 'Unit test', - ]); - $this->backend->updateSubscription($id, $patch); - $patch->commit(); - - $subscriptions = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($subscriptions)); - $this->assertEquals($id, $subscriptions[0]['id']); - $this->assertEquals('Unit test', $subscriptions[0]['{DAV:}displayname']); - - $this->backend->deleteSubscription($id); - $subscriptions = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); - $this->assertEquals(0, count($subscriptions)); - } - - public function testScheduling() { - $this->backend->createSchedulingObject(self::UNIT_TEST_USER, 'Sample Schedule', ''); - - $sos = $this->backend->getSchedulingObjects(self::UNIT_TEST_USER); - $this->assertEquals(1, count($sos)); - - $so = $this->backend->getSchedulingObject(self::UNIT_TEST_USER, 'Sample Schedule'); - $this->assertNotNull($so); - - $this->backend->deleteSchedulingObject(self::UNIT_TEST_USER, 'Sample Schedule'); - - $sos = $this->backend->getSchedulingObjects(self::UNIT_TEST_USER); - $this->assertEquals(0, count($sos)); - } - - /** - * @dataProvider providesCalDataForGetDenormalizedData - */ - public function testGetDenormalizedData($expectedFirstOccurance, $calData) { - $actual = $this->invokePrivate($this->backend, 'getDenormalizedData', [$calData]); - $this->assertEquals($expectedFirstOccurance, $actual['firstOccurence']); - } - - public function providesCalDataForGetDenormalizedData() { - return [ - [0, "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:413F269B-B51B-46B1-AFB6-40055C53A4DC\r\nDTSTAMP:20160309T095056Z\r\nDTSTART;VALUE=DATE:16040222\r\nDTEND;VALUE=DATE:16040223\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:SUMMARY\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], - [null, "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:413F269B-B51B-46B1-AFB6-40055C53A4DC\r\nDTSTAMP:20160309T095056Z\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:SUMMARY\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"] - ]; - } - - private function assertAcl($principal, $privilege, $acl) { - foreach($acl as $a) { - if ($a['principal'] === $principal && $a['privilege'] === $privilege) { - $this->assertTrue(true); - return; - } - } - $this->fail("ACL does not contain $principal / $privilege"); - } - - private function assertNotAcl($principal, $privilege, $acl) { - foreach($acl as $a) { - if ($a['principal'] === $principal && $a['privilege'] === $privilege) { - $this->fail("ACL contains $principal / $privilege"); - return; - } - } - $this->assertTrue(true); - } - - private function assertAccess($shouldHaveAcl, $principal, $privilege, $acl) { - if ($shouldHaveAcl) { - $this->assertAcl($principal, $privilege, $acl); - } else { - $this->assertNotAcl($principal, $privilege, $acl); - } - } -} diff --git a/apps/dav/tests/unit/caldav/calendartest.php b/apps/dav/tests/unit/caldav/calendartest.php deleted file mode 100644 index f13edde6085..00000000000 --- a/apps/dav/tests/unit/caldav/calendartest.php +++ /dev/null @@ -1,191 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\CalDAV; - -use OCA\DAV\CalDAV\BirthdayService; -use OCA\DAV\CalDAV\CalDavBackend; -use OCA\DAV\CalDAV\Calendar; -use OCP\IL10N; -use Sabre\DAV\PropPatch; -use Test\TestCase; - -class CalendarTest extends TestCase { - - /** @var IL10N */ - private $l10n; - - public function setUp() { - parent::setUp(); - $this->l10n = $this->getMockBuilder('\OCP\IL10N') - ->disableOriginalConstructor()->getMock(); - $this->l10n - ->expects($this->any()) - ->method('t') - ->will($this->returnCallback(function ($text, $parameters = array()) { - return vsprintf($text, $parameters); - })); - } - - public function testDelete() { - /** @var \PHPUnit_Framework_MockObject_MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); - $backend->expects($this->once())->method('updateShares'); - $backend->expects($this->any())->method('getShares')->willReturn([ - ['href' => 'principal:user2'] - ]); - $calendarInfo = [ - '{http://owncloud.org/ns}owner-principal' => 'user1', - 'principaluri' => 'user2', - 'id' => 666, - 'uri' => 'cal', - ]; - $c = new Calendar($backend, $calendarInfo, $this->l10n); - $c->delete(); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteFromGroup() { - /** @var \PHPUnit_Framework_MockObject_MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); - $backend->expects($this->never())->method('updateShares'); - $backend->expects($this->any())->method('getShares')->willReturn([ - ['href' => 'principal:group2'] - ]); - $calendarInfo = [ - '{http://owncloud.org/ns}owner-principal' => 'user1', - 'principaluri' => 'user2', - 'id' => 666, - 'uri' => 'cal', - ]; - $c = new Calendar($backend, $calendarInfo, $this->l10n); - $c->delete(); - } - - public function dataPropPatch() { - return [ - [[], true], - [[ - '{http://owncloud.org/ns}calendar-enabled' => true, - ], false], - [[ - '{DAV:}displayname' => true, - ], true], - [[ - '{DAV:}displayname' => true, - '{http://owncloud.org/ns}calendar-enabled' => true, - ], true], - ]; - } - - /** - * @dataProvider dataPropPatch - */ - public function testPropPatch($mutations, $throws) { - /** @var \PHPUnit_Framework_MockObject_MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); - $calendarInfo = [ - '{http://owncloud.org/ns}owner-principal' => 'user1', - 'principaluri' => 'user2', - 'id' => 666, - 'uri' => 'default' - ]; - $c = new Calendar($backend, $calendarInfo, $this->l10n); - - if ($throws) { - $this->setExpectedException('\Sabre\DAV\Exception\Forbidden'); - } - $c->propPatch(new PropPatch($mutations)); - if (!$throws) { - $this->assertTrue(true); - } - } - - /** - * @dataProvider providesReadOnlyInfo - */ - public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet, $uri = 'default') { - /** @var \PHPUnit_Framework_MockObject_MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); - $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1); - $calendarInfo = [ - 'principaluri' => 'user2', - 'id' => 666, - 'uri' => $uri - ]; - if (!is_null($readOnlyValue)) { - $calendarInfo['{http://owncloud.org/ns}read-only'] = $readOnlyValue; - } - if ($hasOwnerSet) { - $calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1'; - } - $c = new Calendar($backend, $calendarInfo, $this->l10n); - $acl = $c->getACL(); - $childAcl = $c->getChildACL(); - - $expectedAcl = [[ - 'privilege' => '{DAV:}read', - 'principal' => $hasOwnerSet ? 'user1' : 'user2', - 'protected' => true - ], [ - 'privilege' => '{DAV:}write', - 'principal' => $hasOwnerSet ? 'user1' : 'user2', - 'protected' => true - ]]; - if ($uri === BirthdayService::BIRTHDAY_CALENDAR_URI) { - $expectedAcl = [[ - 'privilege' => '{DAV:}read', - 'principal' => $hasOwnerSet ? 'user1' : 'user2', - 'protected' => true - ]]; - } - if ($hasOwnerSet) { - $expectedAcl[] = [ - 'privilege' => '{DAV:}read', - 'principal' => 'user2', - 'protected' => true - ]; - if ($expectsWrite) { - $expectedAcl[] = [ - 'privilege' => '{DAV:}write', - 'principal' => 'user2', - 'protected' => true - ]; - } - } - $this->assertEquals($expectedAcl, $acl); - $this->assertEquals($expectedAcl, $childAcl); - } - - public function providesReadOnlyInfo() { - return [ - 'read-only property not set' => [true, null, true], - 'read-only property is false' => [true, false, true], - 'read-only property is true' => [false, true, true], - 'read-only property not set and no owner' => [true, null, false], - 'read-only property is false and no owner' => [true, false, false], - 'read-only property is true and no owner' => [false, true, false], - 'birthday calendar' => [false, false, false, BirthdayService::BIRTHDAY_CALENDAR_URI] - ]; - } -} diff --git a/apps/dav/tests/unit/caldav/schedule/imipplugintest.php b/apps/dav/tests/unit/caldav/schedule/imipplugintest.php deleted file mode 100644 index fcbf4fde04c..00000000000 --- a/apps/dav/tests/unit/caldav/schedule/imipplugintest.php +++ /dev/null @@ -1,91 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\CalDAV\Schedule; - -use OC\Mail\Mailer; -use OCA\DAV\CalDAV\Schedule\IMipPlugin; -use OCP\ILogger; -use Sabre\VObject\Component\VCalendar; -use Sabre\VObject\ITip\Message; -use Test\TestCase; - -class IMipPluginTest extends TestCase { - - public function testDelivery() { - $mailMessage = new \OC\Mail\Message(new \Swift_Message()); - /** @var Mailer | \PHPUnit_Framework_MockObject_MockObject $mailer */ - $mailer = $this->getMockBuilder('OC\Mail\Mailer')->disableOriginalConstructor()->getMock(); - $mailer->method('createMessage')->willReturn($mailMessage); - $mailer->expects($this->once())->method('send'); - /** @var ILogger | \PHPUnit_Framework_MockObject_MockObject $logger */ - $logger = $this->getMockBuilder('OC\Log')->disableOriginalConstructor()->getMock(); - - $plugin = new IMipPlugin($mailer, $logger); - $message = new Message(); - $message->method = 'REQUEST'; - $message->message = new VCalendar(); - $message->message->add('VEVENT', [ - 'UID' => $message->uid, - 'SEQUENCE' => $message->sequence, - 'SUMMARY' => 'Fellowship meeting', - ]); - $message->sender = 'mailto:gandalf@wiz.ard'; - $message->recipient = 'mailto:frodo@hobb.it'; - - $plugin->schedule($message); - $this->assertEquals('1.1', $message->getScheduleStatus()); - $this->assertEquals('Fellowship meeting', $mailMessage->getSubject()); - $this->assertEquals(['frodo@hobb.it' => null], $mailMessage->getTo()); - $this->assertEquals(['gandalf@wiz.ard' => null], $mailMessage->getReplyTo()); - $this->assertEquals('text/calendar; charset=UTF-8; method=REQUEST', $mailMessage->getSwiftMessage()->getContentType()); - } - - public function testFailedDelivery() { - $mailMessage = new \OC\Mail\Message(new \Swift_Message()); - /** @var Mailer | \PHPUnit_Framework_MockObject_MockObject $mailer */ - $mailer = $this->getMockBuilder('OC\Mail\Mailer')->disableOriginalConstructor()->getMock(); - $mailer->method('createMessage')->willReturn($mailMessage); - $mailer->method('send')->willThrowException(new \Exception()); - /** @var ILogger | \PHPUnit_Framework_MockObject_MockObject $logger */ - $logger = $this->getMockBuilder('OC\Log')->disableOriginalConstructor()->getMock(); - - $plugin = new IMipPlugin($mailer, $logger); - $message = new Message(); - $message->method = 'REQUEST'; - $message->message = new VCalendar(); - $message->message->add('VEVENT', [ - 'UID' => $message->uid, - 'SEQUENCE' => $message->sequence, - 'SUMMARY' => 'Fellowship meeting', - ]); - $message->sender = 'mailto:gandalf@wiz.ard'; - $message->recipient = 'mailto:frodo@hobb.it'; - - $plugin->schedule($message); - $this->assertEquals('5.0', $message->getScheduleStatus()); - $this->assertEquals('Fellowship meeting', $mailMessage->getSubject()); - $this->assertEquals(['frodo@hobb.it' => null], $mailMessage->getTo()); - $this->assertEquals(['gandalf@wiz.ard' => null], $mailMessage->getReplyTo()); - $this->assertEquals('text/calendar; charset=UTF-8; method=REQUEST', $mailMessage->getSwiftMessage()->getContentType()); - } - -} diff --git a/apps/dav/tests/unit/carddav/addressbookimpltest.php b/apps/dav/tests/unit/carddav/addressbookimpltest.php deleted file mode 100644 index ba537a631be..00000000000 --- a/apps/dav/tests/unit/carddav/addressbookimpltest.php +++ /dev/null @@ -1,288 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - - -namespace OCA\DAV\Tests\Unit\CardDAV; - - -use OCA\DAV\CardDAV\AddressBook; -use OCA\DAV\CardDAV\AddressBookImpl; -use OCA\DAV\CardDAV\CardDavBackend; -use Sabre\VObject\Component\VCard; -use Sabre\VObject\Property\Text; -use Test\TestCase; - -class AddressBookImplTest extends TestCase { - - /** @var AddressBookImpl */ - private $addressBookImpl; - - /** @var array */ - private $addressBookInfo; - - /** @var AddressBook | \PHPUnit_Framework_MockObject_MockObject */ - private $addressBook; - - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject */ - private $backend; - - /** @var VCard | \PHPUnit_Framework_MockObject_MockObject */ - private $vCard; - - public function setUp() { - parent::setUp(); - - $this->addressBookInfo = [ - 'id' => 42, - '{DAV:}displayname' => 'display name' - ]; - $this->addressBook = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBook') - ->disableOriginalConstructor()->getMock(); - $this->backend = $this->getMockBuilder('\OCA\DAV\CardDAV\CardDavBackend') - ->disableOriginalConstructor()->getMock(); - $this->vCard = $this->getMock('Sabre\VObject\Component\VCard'); - - $this->addressBookImpl = new AddressBookImpl( - $this->addressBook, - $this->addressBookInfo, - $this->backend - ); - } - - public function testGetKey() { - $this->assertSame($this->addressBookInfo['id'], - $this->addressBookImpl->getKey()); - } - - public function testGetDisplayName() { - $this->assertSame($this->addressBookInfo['{DAV:}displayname'], - $this->addressBookImpl->getDisplayName()); - } - - public function testSearch() { - - /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ - $addressBookImpl = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBookImpl') - ->setConstructorArgs( - [ - $this->addressBook, - $this->addressBookInfo, - $this->backend - ] - ) - ->setMethods(['vCard2Array', 'readCard']) - ->getMock(); - - $pattern = 'pattern'; - $searchProperties = 'properties'; - - $this->backend->expects($this->once())->method('search') - ->with($this->addressBookInfo['id'], $pattern, $searchProperties) - ->willReturn( - [ - 'cardData1', - 'cardData2' - ] - ); - - $addressBookImpl->expects($this->exactly(2))->method('readCard') - ->willReturn($this->vCard); - $addressBookImpl->expects($this->exactly(2))->method('vCard2Array') - ->with($this->vCard)->willReturn('vCard'); - - $result = $addressBookImpl->search($pattern, $searchProperties, []); - $this->assertTrue((is_array($result))); - $this->assertSame(2, count($result)); - } - - /** - * @dataProvider dataTestCreate - * - * @param array $properties - */ - public function testCreate($properties) { - - $uid = 'uid'; - - /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ - $addressBookImpl = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBookImpl') - ->setConstructorArgs( - [ - $this->addressBook, - $this->addressBookInfo, - $this->backend - ] - ) - ->setMethods(['vCard2Array', 'createUid', 'createEmptyVCard']) - ->getMock(); - - $addressBookImpl->expects($this->once())->method('createUid') - ->willReturn($uid); - $addressBookImpl->expects($this->once())->method('createEmptyVCard') - ->with($uid)->willReturn($this->vCard); - $this->vCard->expects($this->exactly(count($properties))) - ->method('createProperty'); - $this->backend->expects($this->once())->method('createCard'); - $this->backend->expects($this->never())->method('updateCard'); - $this->backend->expects($this->never())->method('getCard'); - $addressBookImpl->expects($this->once())->method('vCard2Array') - ->with($this->vCard)->willReturn(true); - - $this->assertTrue($addressBookImpl->createOrUpdate($properties)); - } - - public function dataTestCreate() { - return [ - [[]], - [['FN' => 'John Doe']] - ]; - } - - public function testUpdate() { - - $uid = 'uid'; - $properties = ['UID' => $uid, 'FN' => 'John Doe']; - - /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ - $addressBookImpl = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBookImpl') - ->setConstructorArgs( - [ - $this->addressBook, - $this->addressBookInfo, - $this->backend - ] - ) - ->setMethods(['vCard2Array', 'createUid', 'createEmptyVCard', 'readCard']) - ->getMock(); - - $addressBookImpl->expects($this->never())->method('createUid'); - $addressBookImpl->expects($this->never())->method('createEmptyVCard'); - $this->backend->expects($this->once())->method('getCard') - ->with($this->addressBookInfo['id'], $uid . '.vcf') - ->willReturn(['carddata' => 'data']); - $addressBookImpl->expects($this->once())->method('readCard') - ->with('data')->willReturn($this->vCard); - $this->vCard->expects($this->exactly(count($properties))) - ->method('createProperty'); - $this->backend->expects($this->never())->method('createCard'); - $this->backend->expects($this->once())->method('updateCard'); - $addressBookImpl->expects($this->once())->method('vCard2Array') - ->with($this->vCard)->willReturn(true); - - $this->assertTrue($addressBookImpl->createOrUpdate($properties)); - } - - /** - * @dataProvider dataTestGetPermissions - * - * @param array $permissions - * @param int $expected - */ - public function testGetPermissions($permissions, $expected) { - $this->addressBook->expects($this->once())->method('getACL') - ->willReturn($permissions); - - $this->assertSame($expected, - $this->addressBookImpl->getPermissions() - ); - } - - public function dataTestGetPermissions() { - return [ - [[], 0], - [[['privilege' => '{DAV:}read']], 1], - [[['privilege' => '{DAV:}write']], 6], - [[['privilege' => '{DAV:}all']], 31], - [[['privilege' => '{DAV:}read'],['privilege' => '{DAV:}write']], 7], - [[['privilege' => '{DAV:}read'],['privilege' => '{DAV:}all']], 31], - [[['privilege' => '{DAV:}all'],['privilege' => '{DAV:}write']], 31], - [[['privilege' => '{DAV:}read'],['privilege' => '{DAV:}write'],['privilege' => '{DAV:}all']], 31], - [[['privilege' => '{DAV:}all'],['privilege' => '{DAV:}read'],['privilege' => '{DAV:}write']], 31], - ]; - } - - public function testDelete() { - $cardId = 1; - $cardUri = 'cardUri'; - $this->backend->expects($this->once())->method('getCardUri') - ->with($cardId)->willReturn($cardUri); - $this->backend->expects($this->once())->method('deleteCard') - ->with($this->addressBookInfo['id'], $cardUri) - ->willReturn(true); - - $this->assertTrue($this->addressBookImpl->delete($cardId)); - } - - public function testReadCard() { - $vCard = new VCard(); - $vCard->add(new Text($vCard, 'UID', 'uid')); - $vCardSerialized = $vCard->serialize(); - - $result = $this->invokePrivate($this->addressBookImpl, 'readCard', [$vCardSerialized]); - $resultSerialized = $result->serialize(); - - $this->assertSame($vCardSerialized, $resultSerialized); - } - - public function testCreateUid() { - /** @var \PHPUnit_Framework_MockObject_MockObject | AddressBookImpl $addressBookImpl */ - $addressBookImpl = $this->getMockBuilder('OCA\DAV\CardDAV\AddressBookImpl') - ->setConstructorArgs( - [ - $this->addressBook, - $this->addressBookInfo, - $this->backend - ] - ) - ->setMethods(['getUid']) - ->getMock(); - - $addressBookImpl->expects($this->at(0))->method('getUid')->willReturn('uid0'); - $addressBookImpl->expects($this->at(1))->method('getUid')->willReturn('uid1'); - - // simulate that 'uid0' already exists, so the second uid will be returned - $this->backend->expects($this->exactly(2))->method('getContact') - ->willReturnCallback( - function($id, $uid) { - return ($uid === 'uid0.vcf'); - } - ); - - $this->assertSame('uid1', - $this->invokePrivate($addressBookImpl, 'createUid', []) - ); - - } - - public function testCreateEmptyVCard() { - $uid = 'uid'; - $expectedVCard = new VCard(); - $expectedVCard->add(new Text($expectedVCard, 'UID', $uid)); - $expectedVCardSerialized = $expectedVCard->serialize(); - - $result = $this->invokePrivate($this->addressBookImpl, 'createEmptyVCard', [$uid]); - $resultSerialized = $result->serialize(); - - $this->assertSame($expectedVCardSerialized, $resultSerialized); - } - -} diff --git a/apps/dav/tests/unit/carddav/addressbooktest.php b/apps/dav/tests/unit/carddav/addressbooktest.php deleted file mode 100644 index c5cf7e5f7ba..00000000000 --- a/apps/dav/tests/unit/carddav/addressbooktest.php +++ /dev/null @@ -1,139 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\CardDAV; - -use OCA\DAV\CardDAV\AddressBook; -use OCA\DAV\CardDAV\CardDavBackend; -use Sabre\DAV\PropPatch; -use Test\TestCase; - -class AddressBookTest extends TestCase { - - public function testDelete() { - /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); - $backend->expects($this->once())->method('updateShares'); - $backend->expects($this->any())->method('getShares')->willReturn([ - ['href' => 'principal:user2'] - ]); - $calendarInfo = [ - '{http://owncloud.org/ns}owner-principal' => 'user1', - 'principaluri' => 'user2', - 'id' => 666 - ]; - $c = new AddressBook($backend, $calendarInfo); - $c->delete(); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteFromGroup() { - /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); - $backend->expects($this->never())->method('updateShares'); - $backend->expects($this->any())->method('getShares')->willReturn([ - ['href' => 'principal:group2'] - ]); - $calendarInfo = [ - '{http://owncloud.org/ns}owner-principal' => 'user1', - 'principaluri' => 'user2', - 'id' => 666 - ]; - $c = new AddressBook($backend, $calendarInfo); - $c->delete(); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testPropPatch() { - /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); - $calendarInfo = [ - '{http://owncloud.org/ns}owner-principal' => 'user1', - 'principaluri' => 'user2', - 'id' => 666 - ]; - $c = new AddressBook($backend, $calendarInfo); - $c->propPatch(new PropPatch([])); - } - - /** - * @dataProvider providesReadOnlyInfo - */ - public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet) { - /** @var \PHPUnit_Framework_MockObject_MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); - $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1); - $calendarInfo = [ - 'principaluri' => 'user2', - 'id' => 666, - 'uri' => 'default' - ]; - if (!is_null($readOnlyValue)) { - $calendarInfo['{http://owncloud.org/ns}read-only'] = $readOnlyValue; - } - if ($hasOwnerSet) { - $calendarInfo['{http://owncloud.org/ns}owner-principal'] = 'user1'; - } - $c = new AddressBook($backend, $calendarInfo); - $acl = $c->getACL(); - $childAcl = $c->getChildACL(); - - $expectedAcl = [[ - 'privilege' => '{DAV:}read', - 'principal' => $hasOwnerSet ? 'user1' : 'user2', - 'protected' => true - ], [ - 'privilege' => '{DAV:}write', - 'principal' => $hasOwnerSet ? 'user1' : 'user2', - 'protected' => true - ]]; - if ($hasOwnerSet) { - $expectedAcl[] = [ - 'privilege' => '{DAV:}read', - 'principal' => 'user2', - 'protected' => true - ]; - if ($expectsWrite) { - $expectedAcl[] = [ - 'privilege' => '{DAV:}write', - 'principal' => 'user2', - 'protected' => true - ]; - } - } - $this->assertEquals($expectedAcl, $acl); - $this->assertEquals($expectedAcl, $childAcl); - } - - public function providesReadOnlyInfo() { - return [ - 'read-only property not set' => [true, null, true], - 'read-only property is false' => [true, false, true], - 'read-only property is true' => [false, true, true], - 'read-only property not set and no owner' => [true, null, false], - 'read-only property is false and no owner' => [true, false, false], - 'read-only property is true and no owner' => [false, true, false], - ]; - }} diff --git a/apps/dav/tests/unit/carddav/birthdayservicetest.php b/apps/dav/tests/unit/carddav/birthdayservicetest.php deleted file mode 100644 index e15edd16c62..00000000000 --- a/apps/dav/tests/unit/carddav/birthdayservicetest.php +++ /dev/null @@ -1,216 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\CardDAV; - -use OCA\DAV\CalDAV\BirthdayService; -use OCA\DAV\CalDAV\CalDavBackend; -use OCA\DAV\CardDAV\CardDavBackend; -use OCA\DAV\DAV\GroupPrincipalBackend; -use Sabre\VObject\Component\VCalendar; -use Sabre\VObject\Reader; -use Test\TestCase; - -class BirthdayServiceTest extends TestCase { - - /** @var BirthdayService */ - private $service; - /** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject */ - private $calDav; - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject */ - private $cardDav; - /** @var GroupPrincipalBackend | \PHPUnit_Framework_MockObject_MockObject */ - private $groupPrincialBackend; - - public function setUp() { - parent::setUp(); - - $this->calDav = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend')->disableOriginalConstructor()->getMock(); - $this->cardDav = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); - $this->groupPrincialBackend = $this->getMockBuilder('OCA\DAV\DAV\GroupPrincipalBackend')->disableOriginalConstructor()->getMock(); - - $this->service = new BirthdayService($this->calDav, $this->cardDav, $this->groupPrincialBackend); - } - - /** - * @dataProvider providesVCards - * @param boolean $nullExpected - * @param string | null $data - */ - public function testBuildBirthdayFromContact($nullExpected, $data) { - $cal = $this->service->buildBirthdayFromContact($data); - if ($nullExpected) { - $this->assertNull($cal); - } else { - $this->assertInstanceOf('Sabre\VObject\Component\VCalendar', $cal); - $this->assertTrue(isset($cal->VEVENT)); - $this->assertEquals('FREQ=YEARLY', $cal->VEVENT->RRULE->getValue()); - $this->assertEquals('12345 (*1900)', $cal->VEVENT->SUMMARY->getValue()); - $this->assertEquals('TRANSPARENT', $cal->VEVENT->TRANSP->getValue()); - } - } - - public function testOnCardDeleted() { - $this->cardDav->expects($this->once())->method('getAddressBookById') - ->with(666) - ->willReturn([ - 'principaluri' => 'principals/users/user01', - 'uri' => 'default' - ]); - $this->calDav->expects($this->once())->method('getCalendarByUri') - ->with('principals/users/user01', 'contact_birthdays') - ->willReturn([ - 'id' => 1234 - ]); - $this->calDav->expects($this->once())->method('deleteCalendarObject')->with(1234, 'default-gump.vcf.ics'); - $this->cardDav->expects($this->once())->method('getShares')->willReturn([]); - - $this->service->onCardDeleted(666, 'gump.vcf'); - } - - /** - * @dataProvider providesCardChanges - */ - public function testOnCardChanged($expectedOp) { - $this->cardDav->expects($this->once())->method('getAddressBookById') - ->with(666) - ->willReturn([ - 'principaluri' => 'principals/users/user01', - 'uri' => 'default' - ]); - $this->calDav->expects($this->once())->method('getCalendarByUri') - ->with('principals/users/user01', 'contact_birthdays') - ->willReturn([ - 'id' => 1234 - ]); - $this->cardDav->expects($this->once())->method('getShares')->willReturn([]); - - /** @var BirthdayService | \PHPUnit_Framework_MockObject_MockObject $service */ - $service = $this->getMock('\OCA\DAV\CalDAV\BirthdayService', - ['buildBirthdayFromContact', 'birthdayEvenChanged'], [$this->calDav, $this->cardDav, $this->groupPrincialBackend]); - - if ($expectedOp === 'delete') { - $this->calDav->expects($this->once())->method('getCalendarObject')->willReturn(''); - $service->expects($this->once())->method('buildBirthdayFromContact')->willReturn(null); - $this->calDav->expects($this->once())->method('deleteCalendarObject')->with(1234, 'default-gump.vcf.ics'); - } - if ($expectedOp === 'create') { - $service->expects($this->once())->method('buildBirthdayFromContact')->willReturn(new VCalendar()); - $this->calDav->expects($this->once())->method('createCalendarObject')->with(1234, 'default-gump.vcf.ics', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nEND:VCALENDAR\r\n"); - } - if ($expectedOp === 'update') { - $service->expects($this->once())->method('buildBirthdayFromContact')->willReturn(new VCalendar()); - $service->expects($this->once())->method('birthdayEvenChanged')->willReturn(true); - $this->calDav->expects($this->once())->method('getCalendarObject')->willReturn([ - 'calendardata' => '']); - $this->calDav->expects($this->once())->method('updateCalendarObject')->with(1234, 'default-gump.vcf.ics', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nEND:VCALENDAR\r\n"); - } - - $service->onCardChanged(666, 'gump.vcf', ''); - } - - /** - * @dataProvider providesBirthday - * @param $expected - * @param $old - * @param $new - */ - public function testBirthdayEvenChanged($expected, $old, $new) { - $new = Reader::read($new); - $this->assertEquals($expected, $this->service->birthdayEvenChanged($old, $new)); - } - - public function testGetAllAffectedPrincipals() { - $this->cardDav->expects($this->once())->method('getShares')->willReturn([ - [ - '{http://owncloud.org/ns}group-share' => false, - '{http://owncloud.org/ns}principal' => 'principals/users/user01' - ], - [ - '{http://owncloud.org/ns}group-share' => false, - '{http://owncloud.org/ns}principal' => 'principals/users/user01' - ], - [ - '{http://owncloud.org/ns}group-share' => false, - '{http://owncloud.org/ns}principal' => 'principals/users/user02' - ], - [ - '{http://owncloud.org/ns}group-share' => true, - '{http://owncloud.org/ns}principal' => 'principals/groups/users' - ], - ]); - $this->groupPrincialBackend->expects($this->once())->method('getGroupMemberSet') - ->willReturn([ - [ - 'uri' => 'principals/users/user01', - ], - [ - 'uri' => 'principals/users/user02', - ], - [ - 'uri' => 'principals/users/user03', - ], - ]); - $users = $this->invokePrivate($this->service, 'getAllAffectedPrincipals', [6666]); - $this->assertEquals([ - 'principals/users/user01', - 'principals/users/user02', - 'principals/users/user03' - ], $users); - } - - public function providesBirthday() { - return [ - [true, - '', - "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], - [false, - "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", - "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], - [true, - "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:4567's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", - "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], - [true, - "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000101\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", - "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:12345\r\nDTSTAMP:20160218T133704Z\r\nDTSTART;VALUE=DATE:19000102\r\nDTEND;VALUE=DATE:19000102\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:12345's Birthday (1900)\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"] - ]; - } - - public function providesCardChanges(){ - return[ - ['delete'], - ['create'], - ['update'] - ]; - } - - public function providesVCards() { - return [ - [true, null], - [true, ''], - [true, 'yasfewf'], - [true, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nEND:VCARD\r\n", "Dr. Foo Bar"], - [true, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nBDAY:\r\nEND:VCARD\r\n", "Dr. Foo Bar"], - [true, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nBDAY:someday\r\nEND:VCARD\r\n", "Dr. Foo Bar"], - [false, "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nBDAY:1900-01-01\r\nEND:VCARD\r\n", "Dr. Foo Bar"], - ]; - } -} diff --git a/apps/dav/tests/unit/carddav/carddavbackendtest.php b/apps/dav/tests/unit/carddav/carddavbackendtest.php deleted file mode 100644 index 1ee09260c88..00000000000 --- a/apps/dav/tests/unit/carddav/carddavbackendtest.php +++ /dev/null @@ -1,631 +0,0 @@ - - * @author Björn Schießle - * @author Joas Schilling - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\CardDAV; - -use InvalidArgumentException; -use OCA\DAV\CardDAV\AddressBook; -use OCA\DAV\CardDAV\CardDavBackend; -use OCA\DAV\Connector\Sabre\Principal; -use OCP\DB\QueryBuilder\IQueryBuilder; -use OCP\IDBConnection; -use Sabre\DAV\PropPatch; -use Sabre\VObject\Component\VCard; -use Sabre\VObject\Property\Text; -use Test\TestCase; - -/** - * Class CardDavBackendTest - * - * @group DB - * - * @package OCA\DAV\Tests\Unit\CardDAV - */ -class CardDavBackendTest extends TestCase { - - /** @var CardDavBackend */ - private $backend; - - /** @var Principal | \PHPUnit_Framework_MockObject_MockObject */ - private $principal; - - /** @var IDBConnection */ - private $db; - - /** @var string */ - private $dbCardsTable = 'cards'; - - /** @var string */ - private $dbCardsPropertiesTable = 'cards_properties'; - - const UNIT_TEST_USER = 'principals/users/carddav-unit-test'; - const UNIT_TEST_USER1 = 'principals/users/carddav-unit-test1'; - const UNIT_TEST_GROUP = 'principals/groups/carddav-unit-test-group'; - - public function setUp() { - parent::setUp(); - - $this->principal = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Principal') - ->disableOriginalConstructor() - ->setMethods(['getPrincipalByPath', 'getGroupMembership']) - ->getMock(); - $this->principal->method('getPrincipalByPath') - ->willReturn([ - 'uri' => 'principals/best-friend' - ]); - $this->principal->method('getGroupMembership') - ->withAnyParameters() - ->willReturn([self::UNIT_TEST_GROUP]); - - $this->db = \OC::$server->getDatabaseConnection(); - - $this->backend = new CardDavBackend($this->db, $this->principal, null); - - // start every test with a empty cards_properties and cards table - $query = $this->db->getQueryBuilder(); - $query->delete('cards_properties')->execute(); - $query = $this->db->getQueryBuilder(); - $query->delete('cards')->execute(); - - - $this->tearDown(); - } - - public function tearDown() { - parent::tearDown(); - - if (is_null($this->backend)) { - return; - } - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - foreach ($books as $book) { - $this->backend->deleteAddressBook($book['id']); - } - } - - public function testAddressBookOperations() { - - // create a new address book - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $this->assertEquals('Example', $books[0]['{DAV:}displayname']); - - // update it's display name - $patch = new PropPatch([ - '{DAV:}displayname' => 'Unit test', - '{urn:ietf:params:xml:ns:carddav}addressbook-description' => 'Addressbook used for unit testing' - ]); - $this->backend->updateAddressBook($books[0]['id'], $patch); - $patch->commit(); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $this->assertEquals('Unit test', $books[0]['{DAV:}displayname']); - $this->assertEquals('Addressbook used for unit testing', $books[0]['{urn:ietf:params:xml:ns:carddav}addressbook-description']); - - // delete the address book - $this->backend->deleteAddressBook($books[0]['id']); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(0, count($books)); - } - - public function testAddressBookSharing() { - - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $addressBook = new AddressBook($this->backend, $books[0]); - $this->backend->updateShares($addressBook, [ - [ - 'href' => 'principal:' . self::UNIT_TEST_USER1, - ], - [ - 'href' => 'principal:' . self::UNIT_TEST_GROUP, - ] - ], []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1); - $this->assertEquals(1, count($books)); - - // delete the address book - $this->backend->deleteAddressBook($books[0]['id']); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(0, count($books)); - } - - public function testCardOperations() { - - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') - ->setConstructorArgs([$this->db, $this->principal, null]) - ->setMethods(['updateProperties', 'purgeProperties'])->getMock(); - - // create a new address book - $backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $bookId = $books[0]['id']; - - $uri = $this->getUniqueID('card'); - // updateProperties is expected twice, once for createCard and once for updateCard - $backend->expects($this->at(0))->method('updateProperties')->with($bookId, $uri, ''); - $backend->expects($this->at(1))->method('updateProperties')->with($bookId, $uri, '***'); - // create a card - $backend->createCard($bookId, $uri, ''); - - // get all the cards - $cards = $backend->getCards($bookId); - $this->assertEquals(1, count($cards)); - $this->assertEquals('', $cards[0]['carddata']); - - // get the cards - $card = $backend->getCard($bookId, $uri); - $this->assertNotNull($card); - $this->assertArrayHasKey('id', $card); - $this->assertArrayHasKey('uri', $card); - $this->assertArrayHasKey('lastmodified', $card); - $this->assertArrayHasKey('etag', $card); - $this->assertArrayHasKey('size', $card); - $this->assertEquals('', $card['carddata']); - - // update the card - $backend->updateCard($bookId, $uri, '***'); - $card = $backend->getCard($bookId, $uri); - $this->assertEquals('***', $card['carddata']); - - // delete the card - $backend->expects($this->once())->method('purgeProperties')->with($bookId, $card['id']); - $backend->deleteCard($bookId, $uri); - $cards = $backend->getCards($bookId); - $this->assertEquals(0, count($cards)); - } - - public function testMultiCard() { - - $this->backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') - ->setConstructorArgs([$this->db, $this->principal, null]) - ->setMethods(['updateProperties'])->getMock(); - - // create a new address book - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $bookId = $books[0]['id']; - - // create a card - $uri0 = $this->getUniqueID('card'); - $this->backend->createCard($bookId, $uri0, ''); - $uri1 = $this->getUniqueID('card'); - $this->backend->createCard($bookId, $uri1, ''); - $uri2 = $this->getUniqueID('card'); - $this->backend->createCard($bookId, $uri2, ''); - - // get all the cards - $cards = $this->backend->getCards($bookId); - $this->assertEquals(3, count($cards)); - $this->assertEquals('', $cards[0]['carddata']); - $this->assertEquals('', $cards[1]['carddata']); - $this->assertEquals('', $cards[2]['carddata']); - - // get the cards - $cards = $this->backend->getMultipleCards($bookId, [$uri1, $uri2]); - $this->assertEquals(2, count($cards)); - foreach($cards as $card) { - $this->assertArrayHasKey('id', $card); - $this->assertArrayHasKey('uri', $card); - $this->assertArrayHasKey('lastmodified', $card); - $this->assertArrayHasKey('etag', $card); - $this->assertArrayHasKey('size', $card); - $this->assertEquals('', $card['carddata']); - } - - // delete the card - $this->backend->deleteCard($bookId, $uri0); - $this->backend->deleteCard($bookId, $uri1); - $this->backend->deleteCard($bookId, $uri2); - $cards = $this->backend->getCards($bookId); - $this->assertEquals(0, count($cards)); - } - - public function testDeleteWithoutCard() { - - $this->backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') - ->setConstructorArgs([$this->db, $this->principal, null]) - ->setMethods([ - 'getCardId', - 'addChange', - 'purgeProperties', - 'updateProperties', - ]) - ->getMock(); - - // create a new address book - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - - $bookId = $books[0]['id']; - $uri = $this->getUniqueID('card'); - - // create a new address book - $this->backend->expects($this->once()) - ->method('getCardId') - ->with($bookId, $uri) - ->willThrowException(new \InvalidArgumentException()); - $this->backend->expects($this->exactly(2)) - ->method('addChange') - ->withConsecutive( - [$bookId, $uri, 1], - [$bookId, $uri, 3] - ); - $this->backend->expects($this->never()) - ->method('purgeProperties'); - - // create a card - $this->backend->createCard($bookId, $uri, ''); - - // delete the card - $this->assertTrue($this->backend->deleteCard($bookId, $uri)); - } - - public function testSyncSupport() { - - $this->backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') - ->setConstructorArgs([$this->db, $this->principal, null]) - ->setMethods(['updateProperties'])->getMock(); - - // create a new address book - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $bookId = $books[0]['id']; - - // fist call without synctoken - $changes = $this->backend->getChangesForAddressBook($bookId, '', 1); - $syncToken = $changes['syncToken']; - - // add a change - $uri0 = $this->getUniqueID('card'); - $this->backend->createCard($bookId, $uri0, ''); - - // look for changes - $changes = $this->backend->getChangesForAddressBook($bookId, $syncToken, 1); - $this->assertEquals($uri0, $changes['added'][0]); - } - - public function testSharing() { - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - - $exampleBook = new AddressBook($this->backend, $books[0]); - $this->backend->updateShares($exampleBook, [['href' => 'principal:principals/best-friend']], []); - - $shares = $this->backend->getShares($exampleBook->getResourceId()); - $this->assertEquals(1, count($shares)); - - // adding the same sharee again has no effect - $this->backend->updateShares($exampleBook, [['href' => 'principal:principals/best-friend']], []); - - $shares = $this->backend->getShares($exampleBook->getResourceId()); - $this->assertEquals(1, count($shares)); - - $books = $this->backend->getAddressBooksForUser('principals/best-friend'); - $this->assertEquals(1, count($books)); - - $this->backend->updateShares($exampleBook, [], ['principal:principals/best-friend']); - - $shares = $this->backend->getShares($exampleBook->getResourceId()); - $this->assertEquals(0, count($shares)); - - $books = $this->backend->getAddressBooksForUser('principals/best-friend'); - $this->assertEquals(0, count($books)); - } - - public function testUpdateProperties() { - - $bookId = 42; - $cardUri = 'card-uri'; - $cardId = 2; - - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') - ->setConstructorArgs([$this->db, $this->principal, null]) - ->setMethods(['getCardId'])->getMock(); - - $backend->expects($this->any())->method('getCardId')->willReturn($cardId); - - // add properties for new vCard - $vCard = new VCard(); - $vCard->add(new Text($vCard, 'UID', $cardUri)); - $vCard->add(new Text($vCard, 'FN', 'John Doe')); - $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]); - - $query = $this->db->getQueryBuilder(); - $result = $query->select('*')->from('cards_properties')->execute()->fetchAll(); - - $this->assertSame(2, count($result)); - - $this->assertSame('UID', $result[0]['name']); - $this->assertSame($cardUri, $result[0]['value']); - $this->assertSame($bookId, (int)$result[0]['addressbookid']); - $this->assertSame($cardId, (int)$result[0]['cardid']); - - $this->assertSame('FN', $result[1]['name']); - $this->assertSame('John Doe', $result[1]['value']); - $this->assertSame($bookId, (int)$result[1]['addressbookid']); - $this->assertSame($cardId, (int)$result[1]['cardid']); - - // update properties for existing vCard - $vCard = new VCard(); - $vCard->add(new Text($vCard, 'FN', 'John Doe')); - $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]); - - $query = $this->db->getQueryBuilder(); - $result = $query->select('*')->from('cards_properties')->execute()->fetchAll(); - - $this->assertSame(1, count($result)); - - $this->assertSame('FN', $result[0]['name']); - $this->assertSame('John Doe', $result[0]['value']); - $this->assertSame($bookId, (int)$result[0]['addressbookid']); - $this->assertSame($cardId, (int)$result[0]['cardid']); - } - - public function testPurgeProperties() { - - $query = $this->db->getQueryBuilder(); - $query->insert('cards_properties') - ->values( - [ - 'addressbookid' => $query->createNamedParameter(1), - 'cardid' => $query->createNamedParameter(1), - 'name' => $query->createNamedParameter('name1'), - 'value' => $query->createNamedParameter('value1'), - 'preferred' => $query->createNamedParameter(0) - ] - ); - $query->execute(); - - $query = $this->db->getQueryBuilder(); - $query->insert('cards_properties') - ->values( - [ - 'addressbookid' => $query->createNamedParameter(1), - 'cardid' => $query->createNamedParameter(2), - 'name' => $query->createNamedParameter('name2'), - 'value' => $query->createNamedParameter('value2'), - 'preferred' => $query->createNamedParameter(0) - ] - ); - $query->execute(); - - $this->invokePrivate($this->backend, 'purgeProperties', [1, 1]); - - $query = $this->db->getQueryBuilder(); - $result = $query->select('*')->from('cards_properties')->execute()->fetchAll(); - $this->assertSame(1, count($result)); - $this->assertSame(1 ,(int)$result[0]['addressbookid']); - $this->assertSame(2 ,(int)$result[0]['cardid']); - - } - - public function testGetCardId() { - $query = $this->db->getQueryBuilder(); - - $query->insert('cards') - ->values( - [ - 'addressbookid' => $query->createNamedParameter(1), - 'carddata' => $query->createNamedParameter(''), - 'uri' => $query->createNamedParameter('uri'), - 'lastmodified' => $query->createNamedParameter(4738743), - 'etag' => $query->createNamedParameter('etag'), - 'size' => $query->createNamedParameter(120) - ] - ); - $query->execute(); - $id = $query->getLastInsertId(); - - $this->assertSame($id, - $this->invokePrivate($this->backend, 'getCardId', [1, 'uri'])); - } - - /** - * @expectedException InvalidArgumentException - */ - public function testGetCardIdFailed() { - $this->invokePrivate($this->backend, 'getCardId', [1, 'uri']); - } - - /** - * @dataProvider dataTestSearch - * - * @param string $pattern - * @param array $properties - * @param array $expected - */ - public function testSearch($pattern, $properties, $expected) { - /** @var VCard $vCards */ - $vCards = []; - $vCards[0] = new VCard(); - $vCards[0]->add(new Text($vCards[0], 'UID', 'uid')); - $vCards[0]->add(new Text($vCards[0], 'FN', 'John Doe')); - $vCards[0]->add(new Text($vCards[0], 'CLOUD', 'john@owncloud.org')); - $vCards[1] = new VCard(); - $vCards[1]->add(new Text($vCards[1], 'UID', 'uid')); - $vCards[1]->add(new Text($vCards[1], 'FN', 'John M. Doe')); - - $vCardIds = []; - $query = $this->db->getQueryBuilder(); - for($i=0; $i<2; $i++) { - $query->insert($this->dbCardsTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter(0), - 'carddata' => $query->createNamedParameter($vCards[$i]->serialize(), IQueryBuilder::PARAM_LOB), - 'uri' => $query->createNamedParameter('uri' . $i), - 'lastmodified' => $query->createNamedParameter(time()), - 'etag' => $query->createNamedParameter('etag' . $i), - 'size' => $query->createNamedParameter(120), - ] - ); - $query->execute(); - $vCardIds[] = $query->getLastInsertId(); - } - - $query->insert($this->dbCardsPropertiesTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter(0), - 'cardid' => $query->createNamedParameter($vCardIds[0]), - 'name' => $query->createNamedParameter('FN'), - 'value' => $query->createNamedParameter('John Doe'), - 'preferred' => $query->createNamedParameter(0) - ] - ); - $query->execute(); - $query->insert($this->dbCardsPropertiesTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter(0), - 'cardid' => $query->createNamedParameter($vCardIds[0]), - 'name' => $query->createNamedParameter('CLOUD'), - 'value' => $query->createNamedParameter('John@owncloud.org'), - 'preferred' => $query->createNamedParameter(0) - ] - ); - $query->execute(); - $query->insert($this->dbCardsPropertiesTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter(0), - 'cardid' => $query->createNamedParameter($vCardIds[1]), - 'name' => $query->createNamedParameter('FN'), - 'value' => $query->createNamedParameter('John M. Doe'), - 'preferred' => $query->createNamedParameter(0) - ] - ); - $query->execute(); - - $result = $this->backend->search(0, $pattern, $properties); - - // check result - $this->assertSame(count($expected), count($result)); - $found = []; - foreach ($result as $r) { - foreach ($expected as $exp) { - if (strpos($r, $exp) > 0) { - $found[$exp] = true; - break; - } - } - } - - $this->assertSame(count($expected), count($found)); - } - - public function dataTestSearch() { - return [ - ['John', ['FN'], ['John Doe', 'John M. Doe']], - ['M. Doe', ['FN'], ['John M. Doe']], - ['Do', ['FN'], ['John Doe', 'John M. Doe']], - 'check if duplicates are handled correctly' => ['John', ['FN', 'CLOUD'], ['John Doe', 'John M. Doe']], - 'case insensitive' => ['john', ['FN'], ['John Doe', 'John M. Doe']] - ]; - } - - public function testGetCardUri() { - $query = $this->db->getQueryBuilder(); - $query->insert($this->dbCardsTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter(1), - 'carddata' => $query->createNamedParameter('carddata', IQueryBuilder::PARAM_LOB), - 'uri' => $query->createNamedParameter('uri'), - 'lastmodified' => $query->createNamedParameter(5489543), - 'etag' => $query->createNamedParameter('etag'), - 'size' => $query->createNamedParameter(120), - ] - ); - $query->execute(); - - $id = $query->getLastInsertId(); - - $this->assertSame('uri', $this->backend->getCardUri($id)); - } - - /** - * @expectedException InvalidArgumentException - */ - public function testGetCardUriFailed() { - $this->backend->getCardUri(1); - } - - public function testGetContact() { - $query = $this->db->getQueryBuilder(); - for($i=0; $i<2; $i++) { - $query->insert($this->dbCardsTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter($i), - 'carddata' => $query->createNamedParameter('carddata' . $i, IQueryBuilder::PARAM_LOB), - 'uri' => $query->createNamedParameter('uri' . $i), - 'lastmodified' => $query->createNamedParameter(5489543), - 'etag' => $query->createNamedParameter('etag' . $i), - 'size' => $query->createNamedParameter(120), - ] - ); - $query->execute(); - } - - $result = $this->backend->getContact(0, 'uri0'); - $this->assertSame(7, count($result)); - $this->assertSame(0, (int)$result['addressbookid']); - $this->assertSame('uri0', $result['uri']); - $this->assertSame(5489543, (int)$result['lastmodified']); - $this->assertSame('etag0', $result['etag']); - $this->assertSame(120, (int)$result['size']); - } - - public function testGetContactFail() { - $this->assertEmpty($this->backend->getContact(0, 'uri')); - } - - public function testCollectCardProperties() { - $query = $this->db->getQueryBuilder(); - $query->insert($this->dbCardsPropertiesTable) - ->values( - [ - 'addressbookid' => $query->createNamedParameter(666), - 'cardid' => $query->createNamedParameter(777), - 'name' => $query->createNamedParameter('FN'), - 'value' => $query->createNamedParameter('John Doe'), - 'preferred' => $query->createNamedParameter(0) - ] - ) - ->execute(); - - $result = $this->backend->collectCardProperties(666, 'FN'); - $this->assertEquals(['John Doe'], $result); - } -} diff --git a/apps/dav/tests/unit/carddav/contactsmanagertest.php b/apps/dav/tests/unit/carddav/contactsmanagertest.php deleted file mode 100644 index 5a384550df5..00000000000 --- a/apps/dav/tests/unit/carddav/contactsmanagertest.php +++ /dev/null @@ -1,43 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\CardDAV; - -use OCA\DAV\CardDAV\CardDavBackend; -use OCA\DAV\CardDAV\ContactsManager; -use OCP\Contacts\IManager; -use Test\TestCase; - -class ContactsManagerTest extends TestCase { - public function test() { - /** @var IManager | \PHPUnit_Framework_MockObject_MockObject $cm */ - $cm = $this->getMockBuilder('OCP\Contacts\IManager')->disableOriginalConstructor()->getMock(); - $cm->expects($this->exactly(2))->method('registerAddressBook'); - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backEnd */ - $backEnd = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend')->disableOriginalConstructor()->getMock(); - $backEnd->method('getAddressBooksForUser')->willReturn([ - [] - ]); - - $app = new ContactsManager($backEnd); - $app->setupContactsProvider($cm, 'user01'); - } -} diff --git a/apps/dav/tests/unit/carddav/convertertest.php b/apps/dav/tests/unit/carddav/convertertest.php deleted file mode 100644 index ba71b75686a..00000000000 --- a/apps/dav/tests/unit/carddav/convertertest.php +++ /dev/null @@ -1,137 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit; - -use OCA\DAV\CardDAV\Converter; -use Test\TestCase; - -class ConverterTests extends TestCase { - - /** - * @dataProvider providesNewUsers - */ - public function testCreation($expectedVCard, $displayName = null, $eMailAddress = null, $cloudId = null) { - $user = $this->getUserMock($displayName, $eMailAddress, $cloudId); - - $converter = new Converter(); - $vCard = $converter->createCardFromUser($user); - $cardData = $vCard->serialize(); - - $this->assertEquals($expectedVCard, $cardData); - } - - public function providesNewUsers() { - return [ - ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nPHOTO;ENCODING=b;TYPE=JPEG:MTIzNDU2Nzg5\r\nEND:VCARD\r\n"], - ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:Dr. Foo Bar\r\nN:Bar;Dr.;Foo;;\r\nPHOTO;ENCODING=b;TYPE=JPEG:MTIzNDU2Nzg5\r\nEND:VCARD\r\n", "Dr. Foo Bar"], - ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:Dr. Foo Bar\r\nN:Bar;Dr.;Foo;;\r\nEMAIL;TYPE=OTHER:foo@bar.net\r\nPHOTO;ENCODING=b;TYPE=JPEG:MTIzNDU2Nzg5\r\nEND:VCARD\r\n", "Dr. Foo Bar", "foo@bar.net"], - ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:Dr. Foo Bar\r\nN:Bar;Dr.;Foo;;\r\nCLOUD:foo@bar.net\r\nPHOTO;ENCODING=b;TYPE=JPEG:MTIzNDU2Nzg5\r\nEND:VCARD\r\n", "Dr. Foo Bar", null, "foo@bar.net"], - ]; - } - - /** - * @dataProvider providesNewUsers - */ - public function testUpdateOfUnchangedUser($expectedVCard, $displayName = null, $eMailAddress = null, $cloudId = null) { - $user = $this->getUserMock($displayName, $eMailAddress, $cloudId); - - $converter = new Converter(); - $vCard = $converter->createCardFromUser($user); - $updated = $converter->updateCard($vCard, $user); - $this->assertFalse($updated); - $cardData = $vCard->serialize(); - - $this->assertEquals($expectedVCard, $cardData); - } - - /** - * @dataProvider providesUsersForUpdateOfRemovedElement - */ - public function testUpdateOfRemovedElement($expectedVCard, $displayName = null, $eMailAddress = null, $cloudId = null) { - $user = $this->getUserMock($displayName, $eMailAddress, $cloudId); - - $converter = new Converter(); - $vCard = $converter->createCardFromUser($user); - - $user1 = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); - $user1->method('getUID')->willReturn('12345'); - $user1->method('getDisplayName')->willReturn(null); - $user1->method('getEMailAddress')->willReturn(null); - $user1->method('getCloudId')->willReturn(null); - $user1->method('getAvatarImage')->willReturn(null); - - $updated = $converter->updateCard($vCard, $user1); - $this->assertTrue($updated); - $cardData = $vCard->serialize(); - - $this->assertEquals($expectedVCard, $cardData); - } - - public function providesUsersForUpdateOfRemovedElement() { - return [ - ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nEND:VCARD\r\n", "Dr. Foo Bar"], - ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nEND:VCARD\r\n", "Dr. Foo Bar", "foo@bar.net"], - ["BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.5.0//EN\r\nUID:12345\r\nFN:12345\r\nN:12345;;;;\r\nEND:VCARD\r\n", "Dr. Foo Bar", null, "foo@bar.net"], - ]; - } - - /** - * @dataProvider providesNames - * @param $expected - * @param $fullName - */ - public function testNameSplitter($expected, $fullName) { - - $converter = new Converter(); - $r = $converter->splitFullName($fullName); - $r = implode(';', $r); - $this->assertEquals($expected, $r); - } - - public function providesNames() { - return [ - ['Sauron;;;;', 'Sauron'], - ['Baggins;Bilbo;;;', 'Bilbo Baggins'], - ['Tolkien;John;Ronald Reuel;;', 'John Ronald Reuel Tolkien'], - ]; - } - - /** - * @param $displayName - * @param $eMailAddress - * @param $cloudId - * @return \PHPUnit_Framework_MockObject_MockObject - */ - protected function getUserMock($displayName, $eMailAddress, $cloudId) { - $image0 = $this->getMockBuilder('OCP\IImage')->disableOriginalConstructor()->getMock(); - $image0->method('mimeType')->willReturn('JPEG'); - $image0->method('data')->willReturn('123456789'); - $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); - $user->method('getUID')->willReturn('12345'); - $user->method('getDisplayName')->willReturn($displayName); - $user->method('getEMailAddress')->willReturn($eMailAddress); - $user->method('getCloudId')->willReturn($cloudId); - $user->method('getAvatarImage')->willReturn($image0); - return $user; - } -} diff --git a/apps/dav/tests/unit/carddav/sharing/plugintest.php b/apps/dav/tests/unit/carddav/sharing/plugintest.php deleted file mode 100644 index f7159c2d22d..00000000000 --- a/apps/dav/tests/unit/carddav/sharing/plugintest.php +++ /dev/null @@ -1,81 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\CardDAV; - - -use OCA\DAV\DAV\Sharing\IShareable; -use OCA\DAV\DAV\Sharing\Plugin; -use OCA\DAV\Connector\Sabre\Auth; -use OCP\IRequest; -use Sabre\DAV\Server; -use Sabre\DAV\SimpleCollection; -use Sabre\HTTP\Request; -use Sabre\HTTP\Response; -use Test\TestCase; - -class PluginTest extends TestCase { - - /** @var Plugin */ - private $plugin; - /** @var Server */ - private $server; - /** @var IShareable | \PHPUnit_Framework_MockObject_MockObject */ - private $book; - - public function setUp() { - parent::setUp(); - - /** @var Auth | \PHPUnit_Framework_MockObject_MockObject $authBackend */ - $authBackend = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Auth')->disableOriginalConstructor()->getMock(); - $authBackend->method('isDavAuthenticated')->willReturn(true); - - /** @var IRequest $request */ - $request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); - $this->plugin = new Plugin($authBackend, $request); - - $root = new SimpleCollection('root'); - $this->server = new \Sabre\DAV\Server($root); - /** @var SimpleCollection $node */ - $this->book = $this->getMockBuilder('OCA\DAV\DAV\Sharing\IShareable')->disableOriginalConstructor()->getMock(); - $this->book->method('getName')->willReturn('addressbook1.vcf'); - $root->addChild($this->book); - $this->plugin->initialize($this->server); - } - - public function testSharing() { - - $this->book->expects($this->once())->method('updateShares')->with([[ - 'href' => 'principal:principals/admin', - 'commonName' => null, - 'summary' => null, - 'readOnly' => false - ]], ['mailto:wilfredo@example.com']); - - // setup request - $request = new Request(); - $request->addHeader('Content-Type', 'application/xml'); - $request->setUrl('addressbook1.vcf'); - $request->setBody('principal:principals/admin mailto:wilfredo@example.com'); - $response = new Response(); - $this->plugin->httpPost($request, $response); - } -} diff --git a/apps/dav/tests/unit/carddav/syncservicetest.php b/apps/dav/tests/unit/carddav/syncservicetest.php deleted file mode 100644 index e3ffaf472ed..00000000000 --- a/apps/dav/tests/unit/carddav/syncservicetest.php +++ /dev/null @@ -1,142 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\CardDAV; - -use OCP\IUser; -use OCP\IUserManager; -use Test\TestCase; - -class SyncServiceTest extends TestCase { - public function testEmptySync() { - $backend = $this->getBackendMock(0, 0, 0); - - $ss = $this->getSyncServiceMock($backend, []); - $return = $ss->syncRemoteAddressBook('', 'system', '1234567890', null, '1', 'principals/system/system', []); - $this->assertEquals('sync-token-1', $return); - } - - public function testSyncWithNewElement() { - $backend = $this->getBackendMock(1, 0, 0); - $backend->method('getCard')->willReturn(false); - - $ss = $this->getSyncServiceMock($backend, ['0' => [200 => '']]); - $return = $ss->syncRemoteAddressBook('', 'system', '1234567890', null, '1', 'principals/system/system', []); - $this->assertEquals('sync-token-1', $return); - } - - public function testSyncWithUpdatedElement() { - $backend = $this->getBackendMock(0, 1, 0); - $backend->method('getCard')->willReturn(true); - - $ss = $this->getSyncServiceMock($backend, ['0' => [200 => '']]); - $return = $ss->syncRemoteAddressBook('', 'system', '1234567890', null, '1', 'principals/system/system', []); - $this->assertEquals('sync-token-1', $return); - } - - public function testSyncWithDeletedElement() { - $backend = $this->getBackendMock(0, 0, 1); - - $ss = $this->getSyncServiceMock($backend, ['0' => [404 => '']]); - $return = $ss->syncRemoteAddressBook('', 'system', '1234567890', null, '1', 'principals/system/system', []); - $this->assertEquals('sync-token-1', $return); - } - - public function testEnsureSystemAddressBookExists() { - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDAVBackend')->disableOriginalConstructor()->getMock(); - $backend->expects($this->exactly(1))->method('createAddressBook'); - $backend->expects($this->at(0))->method('getAddressBooksByUri')->willReturn(null); - $backend->expects($this->at(1))->method('getAddressBooksByUri')->willReturn([]); - - /** @var IUserManager $userManager */ - $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); - $ss = new SyncService($backend, $userManager, $logger); - $book = $ss->ensureSystemAddressBookExists('principals/users/adam', 'contacts', []); - } - - public function testUpdateAndDeleteUser() { - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backend */ - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDAVBackend')->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); - - $backend->expects($this->once())->method('createCard'); - $backend->expects($this->once())->method('updateCard'); - $backend->expects($this->once())->method('deleteCard'); - - $backend->method('getCard')->willReturnOnConsecutiveCalls(false, [ - 'carddata' => "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Sabre//Sabre VObject 3.4.8//EN\r\nUID:test-user\r\nFN:test-user\r\nN:test-user;;;;\r\nEND:VCARD\r\n\r\n" - ]); - - /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ - $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); - - /** @var IUser | \PHPUnit_Framework_MockObject_MockObject $user */ - $user = $this->getMockBuilder('OCP\IUser')->disableOriginalConstructor()->getMock(); - $user->method('getBackendClassName')->willReturn('unittest'); - $user->method('getUID')->willReturn('test-user'); - - $ss = new SyncService($backend, $userManager, $logger); - $ss->updateUser($user); - - $user->method('getDisplayName')->willReturn('A test user for unit testing'); - - $ss->updateUser($user); - - $ss->deleteUser($user); - } - - /** - * @param int $createCount - * @param int $updateCount - * @param int $deleteCount - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function getBackendMock($createCount, $updateCount, $deleteCount) { - $backend = $this->getMockBuilder('OCA\DAV\CardDAV\CardDAVBackend')->disableOriginalConstructor()->getMock(); - $backend->expects($this->exactly($createCount))->method('createCard'); - $backend->expects($this->exactly($updateCount))->method('updateCard'); - $backend->expects($this->exactly($deleteCount))->method('deleteCard'); - return $backend; - } - - /** - * @param $backend - * @param $response - * @return SyncService|\PHPUnit_Framework_MockObject_MockObject - */ - private function getSyncServiceMock($backend, $response) { - $userManager = $this->getMockBuilder('OCP\IUserManager')->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder('OCP\ILogger')->disableOriginalConstructor()->getMock(); - /** @var SyncService | \PHPUnit_Framework_MockObject_MockObject $ss */ - $ss = $this->getMock('OCA\DAV\CardDAV\SyncService', ['ensureSystemAddressBookExists', 'requestSyncReport', 'download'], [$backend, $userManager, $logger]); - $ss->method('requestSyncReport')->withAnyParameters()->willReturn(['response' => $response, 'token' => 'sync-token-1']); - $ss->method('ensureSystemAddressBookExists')->willReturn(['id' => 1]); - $ss->method('download')->willReturn([ - 'body' => '', - 'statusCode' => 200, - 'headers' => [] - ]); - return $ss; - } - -} diff --git a/apps/dav/tests/unit/comments/commentnode.php b/apps/dav/tests/unit/comments/commentnode.php deleted file mode 100644 index 8ebc5c2ff2c..00000000000 --- a/apps/dav/tests/unit/comments/commentnode.php +++ /dev/null @@ -1,459 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Comments; - -use OCA\DAV\Comments\CommentNode; -use OCP\Comments\IComment; -use OCP\Comments\MessageTooLongException; - -class CommentsNode extends \Test\TestCase { - - protected $commentsManager; - protected $comment; - protected $node; - protected $userManager; - protected $logger; - protected $userSession; - - public function setUp() { - parent::setUp(); - - $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); - $this->comment = $this->getMock('\OCP\Comments\IComment'); - $this->userManager = $this->getMock('\OCP\IUserManager'); - $this->userSession = $this->getMock('\OCP\IUserSession'); - $this->logger = $this->getMock('\OCP\ILogger'); - - $this->node = new CommentNode( - $this->commentsManager, - $this->comment, - $this->userManager, - $this->userSession, - $this->logger - ); - } - - public function testDelete() { - $user = $this->getMock('\OCP\IUser'); - - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('alice')); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->comment->expects($this->once()) - ->method('getId') - ->will($this->returnValue('19')); - - $this->comment->expects($this->any()) - ->method('getActorType') - ->will($this->returnValue('users')); - - $this->comment->expects($this->any()) - ->method('getActorId') - ->will($this->returnValue('alice')); - - $this->commentsManager->expects($this->once()) - ->method('delete') - ->with('19'); - - $this->node->delete(); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteForbidden() { - $user = $this->getMock('\OCP\IUser'); - - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('mallory')); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->comment->expects($this->never()) - ->method('getId'); - - $this->comment->expects($this->any()) - ->method('getActorType') - ->will($this->returnValue('users')); - - $this->comment->expects($this->any()) - ->method('getActorId') - ->will($this->returnValue('alice')); - - $this->commentsManager->expects($this->never()) - ->method('delete'); - - $this->node->delete(); - } - - public function testGetName() { - $id = '19'; - $this->comment->expects($this->once()) - ->method('getId') - ->will($this->returnValue($id)); - - $this->assertSame($this->node->getName(), $id); - } - - /** - * @expectedException \Sabre\DAV\Exception\MethodNotAllowed - */ - public function testSetName() { - $this->node->setName('666'); - } - - public function testGetLastModified() { - $this->assertSame($this->node->getLastModified(), null); - } - - public function testUpdateComment() { - $msg = 'Hello Earth'; - - $user = $this->getMock('\OCP\IUser'); - - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('alice')); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->comment->expects($this->once()) - ->method('setMessage') - ->with($msg); - - $this->comment->expects($this->any()) - ->method('getActorType') - ->will($this->returnValue('users')); - - $this->comment->expects($this->any()) - ->method('getActorId') - ->will($this->returnValue('alice')); - - $this->commentsManager->expects($this->once()) - ->method('save') - ->with($this->comment); - - $this->assertTrue($this->node->updateComment($msg)); - } - - public function testUpdateCommentLogException() { - $msg = null; - - $user = $this->getMock('\OCP\IUser'); - - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('alice')); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->comment->expects($this->once()) - ->method('setMessage') - ->with($msg) - ->will($this->throwException(new \Exception('buh!'))); - - $this->comment->expects($this->any()) - ->method('getActorType') - ->will($this->returnValue('users')); - - $this->comment->expects($this->any()) - ->method('getActorId') - ->will($this->returnValue('alice')); - - $this->commentsManager->expects($this->never()) - ->method('save'); - - $this->logger->expects($this->once()) - ->method('logException'); - - $this->assertFalse($this->node->updateComment($msg)); - } - - /** - * @expectedException \Sabre\DAV\Exception\BadRequest - * @expectedExceptionMessage Message exceeds allowed character limit of - */ - public function testUpdateCommentMessageTooLongException() { - $user = $this->getMock('\OCP\IUser'); - - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('alice')); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->comment->expects($this->once()) - ->method('setMessage') - ->will($this->throwException(new MessageTooLongException())); - - $this->comment->expects($this->any()) - ->method('getActorType') - ->will($this->returnValue('users')); - - $this->comment->expects($this->any()) - ->method('getActorId') - ->will($this->returnValue('alice')); - - $this->commentsManager->expects($this->never()) - ->method('save'); - - $this->logger->expects($this->once()) - ->method('logException'); - - // imagine 'foo' has >1k characters. comment is mocked anyway. - $this->node->updateComment('foo'); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testUpdateForbiddenByUser() { - $msg = 'HaXX0r'; - - $user = $this->getMock('\OCP\IUser'); - - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('mallory')); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->comment->expects($this->never()) - ->method('setMessage'); - - $this->comment->expects($this->any()) - ->method('getActorType') - ->will($this->returnValue('users')); - - $this->comment->expects($this->any()) - ->method('getActorId') - ->will($this->returnValue('alice')); - - $this->commentsManager->expects($this->never()) - ->method('save'); - - $this->node->updateComment($msg); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testUpdateForbiddenByType() { - $msg = 'HaXX0r'; - - $user = $this->getMock('\OCP\IUser'); - - $user->expects($this->never()) - ->method('getUID'); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->comment->expects($this->never()) - ->method('setMessage'); - - $this->comment->expects($this->any()) - ->method('getActorType') - ->will($this->returnValue('bots')); - - $this->commentsManager->expects($this->never()) - ->method('save'); - - $this->node->updateComment($msg); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testUpdateForbiddenByNotLoggedIn() { - $msg = 'HaXX0r'; - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue(null)); - - $this->comment->expects($this->never()) - ->method('setMessage'); - - $this->comment->expects($this->any()) - ->method('getActorType') - ->will($this->returnValue('users')); - - $this->commentsManager->expects($this->never()) - ->method('save'); - - $this->node->updateComment($msg); - } - - public function testPropPatch() { - $propPatch = $this->getMockBuilder('Sabre\DAV\PropPatch') - ->disableOriginalConstructor() - ->getMock(); - - $propPatch->expects($this->once()) - ->method('handle') - ->with('{http://owncloud.org/ns}message'); - - $this->node->propPatch($propPatch); - } - - public function testGetProperties() { - $ns = '{http://owncloud.org/ns}'; - $expected = [ - $ns . 'id' => '123', - $ns . 'parentId' => '12', - $ns . 'topmostParentId' => '2', - $ns . 'childrenCount' => 3, - $ns . 'message' => 'such a nice file you have…', - $ns . 'verb' => 'comment', - $ns . 'actorType' => 'users', - $ns . 'actorId' => 'alice', - $ns . 'actorDisplayName' => 'Alice of Wonderland', - $ns . 'creationDateTime' => new \DateTime('2016-01-10 18:48:00'), - $ns . 'latestChildDateTime' => new \DateTime('2016-01-12 18:48:00'), - $ns . 'objectType' => 'files', - $ns . 'objectId' => '1848', - $ns . 'isUnread' => null, - ]; - - $this->comment->expects($this->once()) - ->method('getId') - ->will($this->returnValue($expected[$ns . 'id'])); - - $this->comment->expects($this->once()) - ->method('getParentId') - ->will($this->returnValue($expected[$ns . 'parentId'])); - - $this->comment->expects($this->once()) - ->method('getTopmostParentId') - ->will($this->returnValue($expected[$ns . 'topmostParentId'])); - - $this->comment->expects($this->once()) - ->method('getChildrenCount') - ->will($this->returnValue($expected[$ns . 'childrenCount'])); - - $this->comment->expects($this->once()) - ->method('getMessage') - ->will($this->returnValue($expected[$ns . 'message'])); - - $this->comment->expects($this->once()) - ->method('getVerb') - ->will($this->returnValue($expected[$ns . 'verb'])); - - $this->comment->expects($this->exactly(2)) - ->method('getActorType') - ->will($this->returnValue($expected[$ns . 'actorType'])); - - $this->comment->expects($this->exactly(2)) - ->method('getActorId') - ->will($this->returnValue($expected[$ns . 'actorId'])); - - $this->comment->expects($this->once()) - ->method('getCreationDateTime') - ->will($this->returnValue($expected[$ns . 'creationDateTime'])); - - $this->comment->expects($this->once()) - ->method('getLatestChildDateTime') - ->will($this->returnValue($expected[$ns . 'latestChildDateTime'])); - - $this->comment->expects($this->once()) - ->method('getObjectType') - ->will($this->returnValue($expected[$ns . 'objectType'])); - - $this->comment->expects($this->once()) - ->method('getObjectId') - ->will($this->returnValue($expected[$ns . 'objectId'])); - - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->once()) - ->method('getDisplayName') - ->will($this->returnValue($expected[$ns . 'actorDisplayName'])); - - $this->userManager->expects($this->once()) - ->method('get') - ->with('alice') - ->will($this->returnValue($user)); - - $properties = $this->node->getProperties(null); - - foreach($properties as $name => $value) { - $this->assertTrue(array_key_exists($name, $expected)); - $this->assertSame($expected[$name], $value); - unset($expected[$name]); - } - $this->assertTrue(empty($expected)); - } - - public function readCommentProvider() { - $creationDT = new \DateTime('2016-01-19 18:48:00'); - $diff = new \DateInterval('PT2H'); - $readDT1 = clone $creationDT; $readDT1->sub($diff); - $readDT2 = clone $creationDT; $readDT2->add($diff); - return [ - [$creationDT, $readDT1, 'true'], - [$creationDT, $readDT2, 'false'], - [$creationDT, null, 'true'], - ]; - } - - /** - * @dataProvider readCommentProvider - * @param $expected - */ - public function testGetPropertiesUnreadProperty($creationDT, $readDT, $expected) { - $this->comment->expects($this->any()) - ->method('getCreationDateTime') - ->will($this->returnValue($creationDT)); - - $this->commentsManager->expects($this->once()) - ->method('getReadMark') - ->will($this->returnValue($readDT)); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($this->getMock('\OCP\IUser'))); - - $properties = $this->node->getProperties(null); - - $this->assertTrue(array_key_exists(CommentNode::PROPERTY_NAME_UNREAD, $properties)); - $this->assertSame($properties[CommentNode::PROPERTY_NAME_UNREAD], $expected); - } -} diff --git a/apps/dav/tests/unit/comments/commentsplugin.php b/apps/dav/tests/unit/comments/commentsplugin.php deleted file mode 100644 index c909f6a61ab..00000000000 --- a/apps/dav/tests/unit/comments/commentsplugin.php +++ /dev/null @@ -1,742 +0,0 @@ - - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Comments; - -use OC\Comments\Comment; -use OCA\DAV\Comments\CommentsPlugin as CommentsPluginImplementation; -use OCP\Comments\IComment; -use Sabre\DAV\Exception\NotFound; - -class CommentsPlugin extends \Test\TestCase { - /** @var \Sabre\DAV\Server */ - private $server; - - /** @var \Sabre\DAV\Tree */ - private $tree; - - /** @var \OCP\Comments\ICommentsManager */ - private $commentsManager; - - /** @var \OCP\IUserSession */ - private $userSession; - - /** @var CommentsPluginImplementation */ - private $plugin; - - public function setUp() { - parent::setUp(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') - ->disableOriginalConstructor() - ->getMock(); - - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') - ->setConstructorArgs([$this->tree]) - ->setMethods(['getRequestUri']) - ->getMock(); - - $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); - $this->userSession = $this->getMock('\OCP\IUserSession'); - - $this->plugin = new CommentsPluginImplementation($this->commentsManager, $this->userSession); - } - - public function testCreateComment() { - $commentData = [ - 'actorType' => 'users', - 'verb' => 'comment', - 'message' => 'my first comment', - ]; - - $comment = new Comment([ - 'objectType' => 'files', - 'objectId' => '42', - 'actorType' => 'users', - 'actorId' => 'alice' - ] + $commentData); - $comment->setId('23'); - - $path = 'comments/files/42'; - - $requestData = json_encode($commentData); - - $user = $this->getMock('OCP\IUser'); - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('alice')); - - $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->once()) - ->method('getName') - ->will($this->returnValue('files')); - $node->expects($this->once()) - ->method('getId') - ->will($this->returnValue('42')); - - $node->expects($this->once()) - ->method('setReadMarker') - ->with(null); - - $this->commentsManager->expects($this->once()) - ->method('create') - ->with('users', 'alice', 'files', '42') - ->will($this->returnValue($comment)); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - // technically, this is a shortcut. Inbetween EntityTypeCollection would - // be returned, but doing it exactly right would not be really - // unit-testing like, as it would require to haul in a lot of other - // things. - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/' . $path)); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $request->expects($this->once()) - ->method('getUrl') - ->will($this->returnValue('http://example.com/dav/' . $path)); - - $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Location', 'http://example.com/dav/' . $path . '/23'); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->httpPost($request, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotFound - */ - public function testCreateCommentInvalidObject() { - $commentData = [ - 'actorType' => 'users', - 'verb' => 'comment', - 'message' => 'my first comment', - ]; - - $comment = new Comment([ - 'objectType' => 'files', - 'objectId' => '666', - 'actorType' => 'users', - 'actorId' => 'alice' - ] + $commentData); - $comment->setId('23'); - - $path = 'comments/files/666'; - - $user = $this->getMock('OCP\IUser'); - $user->expects($this->never()) - ->method('getUID'); - - $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->never()) - ->method('getName'); - $node->expects($this->never()) - ->method('getId'); - - $this->commentsManager->expects($this->never()) - ->method('create'); - - $this->userSession->expects($this->never()) - ->method('getUser'); - - // technically, this is a shortcut. Inbetween EntityTypeCollection would - // be returned, but doing it exactly right would not be really - // unit-testing like, as it would require to haul in a lot of other - // things. - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/' . $path)); - - $request->expects($this->never()) - ->method('getBodyAsString'); - - $request->expects($this->never()) - ->method('getHeader') - ->with('Content-Type'); - - $request->expects($this->never()) - ->method('getUrl'); - - $response->expects($this->never()) - ->method('setHeader'); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->httpPost($request, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\BadRequest - */ - public function testCreateCommentInvalidActor() { - $commentData = [ - 'actorType' => 'robots', - 'verb' => 'comment', - 'message' => 'my first comment', - ]; - - $comment = new Comment([ - 'objectType' => 'files', - 'objectId' => '42', - 'actorType' => 'users', - 'actorId' => 'alice' - ] + $commentData); - $comment->setId('23'); - - $path = 'comments/files/42'; - - $requestData = json_encode($commentData); - - $user = $this->getMock('OCP\IUser'); - $user->expects($this->never()) - ->method('getUID'); - - $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->once()) - ->method('getName') - ->will($this->returnValue('files')); - $node->expects($this->once()) - ->method('getId') - ->will($this->returnValue('42')); - - $this->commentsManager->expects($this->never()) - ->method('create'); - - $this->userSession->expects($this->never()) - ->method('getUser'); - - // technically, this is a shortcut. Inbetween EntityTypeCollection would - // be returned, but doing it exactly right would not be really - // unit-testing like, as it would require to haul in a lot of other - // things. - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/' . $path)); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $request->expects($this->never()) - ->method('getUrl'); - - $response->expects($this->never()) - ->method('setHeader'); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->httpPost($request, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\UnsupportedMediaType - */ - public function testCreateCommentUnsupportedMediaType() { - $commentData = [ - 'actorType' => 'users', - 'verb' => 'comment', - 'message' => 'my first comment', - ]; - - $comment = new Comment([ - 'objectType' => 'files', - 'objectId' => '42', - 'actorType' => 'users', - 'actorId' => 'alice' - ] + $commentData); - $comment->setId('23'); - - $path = 'comments/files/42'; - - $requestData = json_encode($commentData); - - $user = $this->getMock('OCP\IUser'); - $user->expects($this->never()) - ->method('getUID'); - - $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->once()) - ->method('getName') - ->will($this->returnValue('files')); - $node->expects($this->once()) - ->method('getId') - ->will($this->returnValue('42')); - - $this->commentsManager->expects($this->never()) - ->method('create'); - - $this->userSession->expects($this->never()) - ->method('getUser'); - - // technically, this is a shortcut. Inbetween EntityTypeCollection would - // be returned, but doing it exactly right would not be really - // unit-testing like, as it would require to haul in a lot of other - // things. - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/' . $path)); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/trumpscript')); - - $request->expects($this->never()) - ->method('getUrl'); - - $response->expects($this->never()) - ->method('setHeader'); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->httpPost($request, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\BadRequest - */ - public function testCreateCommentInvalidPayload() { - $commentData = [ - 'actorType' => 'users', - 'verb' => '', - 'message' => '', - ]; - - $comment = new Comment([ - 'objectType' => 'files', - 'objectId' => '42', - 'actorType' => 'users', - 'actorId' => 'alice', - 'message' => 'dummy', - 'verb' => 'dummy' - ]); - $comment->setId('23'); - - $path = 'comments/files/42'; - - $requestData = json_encode($commentData); - - $user = $this->getMock('OCP\IUser'); - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('alice')); - - $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->once()) - ->method('getName') - ->will($this->returnValue('files')); - $node->expects($this->once()) - ->method('getId') - ->will($this->returnValue('42')); - - $this->commentsManager->expects($this->once()) - ->method('create') - ->with('users', 'alice', 'files', '42') - ->will($this->returnValue($comment)); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - // technically, this is a shortcut. Inbetween EntityTypeCollection would - // be returned, but doing it exactly right would not be really - // unit-testing like, as it would require to haul in a lot of other - // things. - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/' . $path)); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $request->expects($this->never()) - ->method('getUrl'); - - $response->expects($this->never()) - ->method('setHeader'); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->httpPost($request, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\BadRequest - * @expectedExceptionMessage Message exceeds allowed character limit of - */ - public function testCreateCommentMessageTooLong() { - $commentData = [ - 'actorType' => 'users', - 'verb' => 'comment', - 'message' => str_pad('', IComment::MAX_MESSAGE_LENGTH + 1, 'x'), - ]; - - $comment = new Comment([ - 'objectType' => 'files', - 'objectId' => '42', - 'actorType' => 'users', - 'actorId' => 'alice', - 'verb' => 'comment', - ]); - $comment->setId('23'); - - $path = 'comments/files/42'; - - $requestData = json_encode($commentData); - - $user = $this->getMock('OCP\IUser'); - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('alice')); - - $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->once()) - ->method('getName') - ->will($this->returnValue('files')); - $node->expects($this->once()) - ->method('getId') - ->will($this->returnValue('42')); - - $node->expects($this->never()) - ->method('setReadMarker'); - - $this->commentsManager->expects($this->once()) - ->method('create') - ->with('users', 'alice', 'files', '42') - ->will($this->returnValue($comment)); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - // technically, this is a shortcut. Inbetween EntityTypeCollection would - // be returned, but doing it exactly right would not be really - // unit-testing like, as it would require to haul in a lot of other - // things. - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/' . $path)); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $response->expects($this->never()) - ->method('setHeader'); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->httpPost($request, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\ReportNotSupported - */ - public function testOnReportInvalidNode() { - $path = 'totally/unrelated/13'; - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($this->getMock('\Sabre\DAV\INode'))); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, [], '/' . $path); - } - - /** - * @expectedException \Sabre\DAV\Exception\ReportNotSupported - */ - public function testOnReportInvalidReportName() { - $path = 'comments/files/42'; - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($this->getMock('\Sabre\DAV\INode'))); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->onReport('{whoever}whatever', [], '/' . $path); - } - - public function testOnReportDateTimeEmpty() { - $path = 'comments/files/42'; - - $parameters = [ - [ - 'name' => '{http://owncloud.org/ns}limit', - 'value' => 5, - ], - [ - 'name' => '{http://owncloud.org/ns}offset', - 'value' => 10, - ], - [ - 'name' => '{http://owncloud.org/ns}datetime', - 'value' => '', - ] - ]; - - $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->once()) - ->method('findChildren') - ->with(5, 10, null) - ->will($this->returnValue([])); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Type', 'application/xml; charset=utf-8'); - - $response->expects($this->once()) - ->method('setStatus') - ->with(207); - - $response->expects($this->once()) - ->method('setBody'); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($node)); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->server->httpResponse = $response; - $this->plugin->initialize($this->server); - - $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, $parameters, '/' . $path); - } - - public function testOnReport() { - $path = 'comments/files/42'; - - $parameters = [ - [ - 'name' => '{http://owncloud.org/ns}limit', - 'value' => 5, - ], - [ - 'name' => '{http://owncloud.org/ns}offset', - 'value' => 10, - ], - [ - 'name' => '{http://owncloud.org/ns}datetime', - 'value' => '2016-01-10 18:48:00', - ] - ]; - - $node = $this->getMockBuilder('\OCA\DAV\Comments\EntityCollection') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->once()) - ->method('findChildren') - ->with(5, 10, new \DateTime($parameters[2]['value'])) - ->will($this->returnValue([])); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Type', 'application/xml; charset=utf-8'); - - $response->expects($this->once()) - ->method('setStatus') - ->with(207); - - $response->expects($this->once()) - ->method('setBody'); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($node)); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->server->httpResponse = $response; - $this->plugin->initialize($this->server); - - $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, $parameters, '/' . $path); - } - - - -} diff --git a/apps/dav/tests/unit/comments/entitycollection.php b/apps/dav/tests/unit/comments/entitycollection.php deleted file mode 100644 index bc009e92549..00000000000 --- a/apps/dav/tests/unit/comments/entitycollection.php +++ /dev/null @@ -1,118 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Comments; - -class EntityCollection extends \Test\TestCase { - - /** @var \OCP\Comments\ICommentsManager|\PHPUnit_Framework_MockObject_MockObject */ - protected $commentsManager; - /** @var \OCP\IUserManager|\PHPUnit_Framework_MockObject_MockObject */ - protected $userManager; - /** @var \OCP\ILogger|\PHPUnit_Framework_MockObject_MockObject */ - protected $logger; - /** @var \OCA\DAV\Comments\EntityCollection */ - protected $collection; - /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject */ - protected $userSession; - - public function setUp() { - parent::setUp(); - - $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); - $this->userManager = $this->getMock('\OCP\IUserManager'); - $this->userSession = $this->getMock('\OCP\IUserSession'); - $this->logger = $this->getMock('\OCP\ILogger'); - - $this->collection = new \OCA\DAV\Comments\EntityCollection( - '19', - 'files', - $this->commentsManager, - $this->userManager, - $this->userSession, - $this->logger - ); - } - - public function testGetId() { - $this->assertSame($this->collection->getId(), '19'); - } - - public function testGetChild() { - $this->commentsManager->expects($this->once()) - ->method('get') - ->with('55') - ->will($this->returnValue($this->getMock('\OCP\Comments\IComment'))); - - $node = $this->collection->getChild('55'); - $this->assertTrue($node instanceof \OCA\DAV\Comments\CommentNode); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotFound - */ - public function testGetChildException() { - $this->commentsManager->expects($this->once()) - ->method('get') - ->with('55') - ->will($this->throwException(new \OCP\Comments\NotFoundException())); - - $this->collection->getChild('55'); - } - - public function testGetChildren() { - $this->commentsManager->expects($this->once()) - ->method('getForObject') - ->with('files', '19') - ->will($this->returnValue([$this->getMock('\OCP\Comments\IComment')])); - - $result = $this->collection->getChildren(); - - $this->assertSame(count($result), 1); - $this->assertTrue($result[0] instanceof \OCA\DAV\Comments\CommentNode); - } - - public function testFindChildren() { - $dt = new \DateTime('2016-01-10 18:48:00'); - $this->commentsManager->expects($this->once()) - ->method('getForObject') - ->with('files', '19', 5, 15, $dt) - ->will($this->returnValue([$this->getMock('\OCP\Comments\IComment')])); - - $result = $this->collection->findChildren(5, 15, $dt); - - $this->assertSame(count($result), 1); - $this->assertTrue($result[0] instanceof \OCA\DAV\Comments\CommentNode); - } - - public function testChildExistsTrue() { - $this->assertTrue($this->collection->childExists('44')); - } - - public function testChildExistsFalse() { - $this->commentsManager->expects($this->once()) - ->method('get') - ->with('44') - ->will($this->throwException(new \OCP\Comments\NotFoundException())); - - $this->assertFalse($this->collection->childExists('44')); - } -} diff --git a/apps/dav/tests/unit/comments/entitytypecollection.php b/apps/dav/tests/unit/comments/entitytypecollection.php deleted file mode 100644 index 96b1cad8373..00000000000 --- a/apps/dav/tests/unit/comments/entitytypecollection.php +++ /dev/null @@ -1,92 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Comments; - -use OCA\DAV\Comments\EntityCollection as EntityCollectionImplemantation; - -class EntityTypeCollection extends \Test\TestCase { - - /** @var \OCP\Comments\ICommentsManager|\PHPUnit_Framework_MockObject_MockObject */ - protected $commentsManager; - /** @var \OCP\IUserManager|\PHPUnit_Framework_MockObject_MockObject */ - protected $userManager; - /** @var \OCP\ILogger|\PHPUnit_Framework_MockObject_MockObject */ - protected $logger; - /** @var \OCA\DAV\Comments\EntityTypeCollection */ - protected $collection; - /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject */ - protected $userSession; - - protected $childMap = []; - - public function setUp() { - parent::setUp(); - - $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); - $this->userManager = $this->getMock('\OCP\IUserManager'); - $this->userSession = $this->getMock('\OCP\IUserSession'); - $this->logger = $this->getMock('\OCP\ILogger'); - - $instance = $this; - - $this->collection = new \OCA\DAV\Comments\EntityTypeCollection( - 'files', - $this->commentsManager, - $this->userManager, - $this->userSession, - $this->logger, - function ($child) use ($instance) { - return !empty($instance->childMap[$child]); - } - ); - } - - public function testChildExistsYes() { - $this->childMap[17] = true; - $this->assertTrue($this->collection->childExists('17')); - } - - public function testChildExistsNo() { - $this->assertFalse($this->collection->childExists('17')); - } - - public function testGetChild() { - $this->childMap[17] = true; - - $ec = $this->collection->getChild('17'); - $this->assertTrue($ec instanceof EntityCollectionImplemantation); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotFound - */ - public function testGetChildException() { - $this->collection->getChild('17'); - } - - /** - * @expectedException \Sabre\DAV\Exception\MethodNotAllowed - */ - public function testGetChildren() { - $this->collection->getChildren(); - } -} diff --git a/apps/dav/tests/unit/comments/rootcollection.php b/apps/dav/tests/unit/comments/rootcollection.php deleted file mode 100644 index a59482fba73..00000000000 --- a/apps/dav/tests/unit/comments/rootcollection.php +++ /dev/null @@ -1,170 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Comments; - -use OCA\DAV\Comments\EntityTypeCollection as EntityTypeCollectionImplementation; -use OCP\Comments\CommentsEntityEvent; -use Symfony\Component\EventDispatcher\EventDispatcher; - -class RootCollection extends \Test\TestCase { - - /** @var \OCP\Comments\ICommentsManager|\PHPUnit_Framework_MockObject_MockObject */ - protected $commentsManager; - /** @var \OCP\IUserManager|\PHPUnit_Framework_MockObject_MockObject */ - protected $userManager; - /** @var \OCP\ILogger|\PHPUnit_Framework_MockObject_MockObject */ - protected $logger; - /** @var \OCA\DAV\Comments\RootCollection */ - protected $collection; - /** @var \OCP\IUserSession|\PHPUnit_Framework_MockObject_MockObject */ - protected $userSession; - /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ - protected $dispatcher; - /** @var \OCP\IUser|\PHPUnit_Framework_MockObject_MockObject */ - protected $user; - - public function setUp() { - parent::setUp(); - - $this->user = $this->getMock('\OCP\IUser'); - - $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); - $this->userManager = $this->getMock('\OCP\IUserManager'); - $this->userSession = $this->getMock('\OCP\IUserSession'); - $this->dispatcher = new EventDispatcher(); - $this->logger = $this->getMock('\OCP\ILogger'); - - $this->collection = new \OCA\DAV\Comments\RootCollection( - $this->commentsManager, - $this->userManager, - $this->userSession, - $this->dispatcher, - $this->logger - ); - } - - protected function prepareForInitCollections() { - $this->user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('alice')); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($this->user)); - - $this->dispatcher->addListener(CommentsEntityEvent::EVENT_ENTITY, function(CommentsEntityEvent $event) { - $event->addEntityCollection('files', function() { - return true; - }); - }); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testCreateFile() { - $this->collection->createFile('foo'); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testCreateDirectory() { - $this->collection->createDirectory('foo'); - } - - public function testGetChild() { - $this->prepareForInitCollections(); - $etc = $this->collection->getChild('files'); - $this->assertTrue($etc instanceof EntityTypeCollectionImplementation); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotFound - */ - public function testGetChildInvalid() { - $this->prepareForInitCollections(); - $this->collection->getChild('robots'); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotAuthenticated - */ - public function testGetChildNoAuth() { - $this->collection->getChild('files'); - } - - public function testGetChildren() { - $this->prepareForInitCollections(); - $children = $this->collection->getChildren(); - $this->assertFalse(empty($children)); - foreach($children as $child) { - $this->assertTrue($child instanceof EntityTypeCollectionImplementation); - } - } - - /** - * @expectedException \Sabre\DAV\Exception\NotAuthenticated - */ - public function testGetChildrenNoAuth() { - $this->collection->getChildren(); - } - - public function testChildExistsYes() { - $this->prepareForInitCollections(); - $this->assertTrue($this->collection->childExists('files')); - } - - public function testChildExistsNo() { - $this->prepareForInitCollections(); - $this->assertFalse($this->collection->childExists('robots')); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotAuthenticated - */ - public function testChildExistsNoAuth() { - $this->collection->childExists('files'); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDelete() { - $this->collection->delete(); - } - - public function testGetName() { - $this->assertSame('comments', $this->collection->getName()); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testSetName() { - $this->collection->setName('foobar'); - } - - public function testGetLastModified() { - $this->assertSame(null, $this->collection->getLastModified()); - } -} diff --git a/apps/dav/tests/unit/connector/publicauth.php b/apps/dav/tests/unit/connector/publicauth.php deleted file mode 100644 index 76a6e1ac6a1..00000000000 --- a/apps/dav/tests/unit/connector/publicauth.php +++ /dev/null @@ -1,177 +0,0 @@ -session = $this->getMock('\OCP\ISession'); - $this->request = $this->getMock('\OCP\IRequest'); - $this->shareManager = $this->getMock('\OCP\Share\IManager'); - - $this->auth = new \OCA\DAV\Connector\PublicAuth( - $this->request, - $this->shareManager, - $this->session - ); - - // Store current user - $this->oldUser = \OC_User::getUser(); - } - - protected function tearDown() { - \OC_User::setIncognitoMode(false); - - // Set old user - \OC_User::setUserId($this->oldUser); - \OC_Util::setupFS($this->oldUser); - - parent::tearDown(); - } - - public function testNoShare() { - $this->shareManager->expects($this->once()) - ->method('getShareByToken') - ->willThrowException(new ShareNotFound()); - - $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); - - $this->assertFalse($result); - } - - public function testShareNoPassword() { - $share = $this->getMock('OCP\Share\IShare'); - $share->method('getPassword')->willReturn(null); - - $this->shareManager->expects($this->once()) - ->method('getShareByToken') - ->willReturn($share); - - $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); - - $this->assertTrue($result); - } - - public function testSharePasswordFancyShareType() { - $share = $this->getMock('OCP\Share\IShare'); - $share->method('getPassword')->willReturn('password'); - $share->method('getShareType')->willReturn(42); - - $this->shareManager->expects($this->once()) - ->method('getShareByToken') - ->willReturn($share); - - $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); - - $this->assertFalse($result); - } - - - public function testSharePasswordRemote() { - $share = $this->getMock('OCP\Share\IShare'); - $share->method('getPassword')->willReturn('password'); - $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_REMOTE); - - $this->shareManager->expects($this->once()) - ->method('getShareByToken') - ->willReturn($share); - - $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); - - $this->assertTrue($result); - } - - public function testSharePasswordLinkValidPassword() { - $share = $this->getMock('OCP\Share\IShare'); - $share->method('getPassword')->willReturn('password'); - $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); - - $this->shareManager->expects($this->once()) - ->method('getShareByToken') - ->willReturn($share); - - $this->shareManager->expects($this->once()) - ->method('checkPassword')->with( - $this->equalTo($share), - $this->equalTo('password') - )->willReturn(true); - - $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); - - $this->assertTrue($result); - } - - public function testSharePasswordLinkValidSession() { - $share = $this->getMock('OCP\Share\IShare'); - $share->method('getPassword')->willReturn('password'); - $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); - $share->method('getId')->willReturn('42'); - - $this->shareManager->expects($this->once()) - ->method('getShareByToken') - ->willReturn($share); - - $this->shareManager->method('checkPassword') - ->with( - $this->equalTo($share), - $this->equalTo('password') - )->willReturn(false); - - $this->session->method('exists')->with('public_link_authenticated')->willReturn(true); - $this->session->method('get')->with('public_link_authenticated')->willReturn('42'); - - $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); - - $this->assertTrue($result); - } - - public function testSharePasswordLinkInvalidSession() { - $share = $this->getMock('OCP\Share\IShare'); - $share->method('getPassword')->willReturn('password'); - $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); - $share->method('getId')->willReturn('42'); - - $this->shareManager->expects($this->once()) - ->method('getShareByToken') - ->willReturn($share); - - $this->shareManager->method('checkPassword') - ->with( - $this->equalTo($share), - $this->equalTo('password') - )->willReturn(false); - - $this->session->method('exists')->with('public_link_authenticated')->willReturn(true); - $this->session->method('get')->with('public_link_authenticated')->willReturn('43'); - - $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); - - $this->assertFalse($result); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/BlockLegacyClientPluginTest.php b/apps/dav/tests/unit/connector/sabre/BlockLegacyClientPluginTest.php deleted file mode 100644 index d02064531ab..00000000000 --- a/apps/dav/tests/unit/connector/sabre/BlockLegacyClientPluginTest.php +++ /dev/null @@ -1,130 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin; -use Test\TestCase; -use OCP\IConfig; - -/** - * Class BlockLegacyClientPluginTest - * - * @package Test\Connector\Sabre - */ -class BlockLegacyClientPluginTest extends TestCase { - /** @var IConfig */ - private $config; - /** @var BlockLegacyClientPlugin */ - private $blockLegacyClientVersionPlugin; - - public function setUp() { - parent::setUp(); - - $this->config = $this->getMock('\OCP\IConfig'); - $this->blockLegacyClientVersionPlugin = new BlockLegacyClientPlugin($this->config); - } - - /** - * @return array - */ - public function oldDesktopClientProvider() { - return [ - ['Mozilla/5.0 (1.5.0) mirall/1.5.0'], - ['mirall/1.5.0'], - ['mirall/1.5.4'], - ['mirall/1.6.0'], - ['Mozilla/5.0 (Bogus Text) mirall/1.6.9'], - ]; - } - - /** - * @dataProvider oldDesktopClientProvider - * @param string $userAgent - * @expectedException \Sabre\DAV\Exception\Forbidden - * @expectedExceptionMessage Unsupported client version. - */ - public function testBeforeHandlerException($userAgent) { - /** @var \Sabre\HTTP\RequestInterface $request */ - $request = $this->getMock('\Sabre\HTTP\RequestInterface'); - $request - ->expects($this->once()) - ->method('getHeader') - ->with('User-Agent') - ->will($this->returnValue($userAgent)); - - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->with('minimum.supported.desktop.version', '1.7.0') - ->will($this->returnValue('1.7.0')); - - $this->blockLegacyClientVersionPlugin->beforeHandler($request); - } - - /** - * @return array - */ - public function newAndAlternateDesktopClientProvider() { - return [ - ['Mozilla/5.0 (1.7.0) mirall/1.7.0'], - ['mirall/1.8.3'], - ['mirall/1.7.2'], - ['mirall/1.7.0'], - ['Mozilla/5.0 (Bogus Text) mirall/1.9.3'], - ]; - } - - /** - * @dataProvider newAndAlternateDesktopClientProvider - * @param string $userAgent - */ - public function testBeforeHandlerSuccess($userAgent) { - /** @var \Sabre\HTTP\RequestInterface $request */ - $request = $this->getMock('\Sabre\HTTP\RequestInterface'); - $request - ->expects($this->once()) - ->method('getHeader') - ->with('User-Agent') - ->will($this->returnValue($userAgent)); - - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->with('minimum.supported.desktop.version', '1.7.0') - ->will($this->returnValue('1.7.0')); - - $this->blockLegacyClientVersionPlugin->beforeHandler($request); - } - - public function testBeforeHandlerNoUserAgent() { - /** @var \Sabre\HTTP\RequestInterface $request */ - $request = $this->getMock('\Sabre\HTTP\RequestInterface'); - $request - ->expects($this->once()) - ->method('getHeader') - ->with('User-Agent') - ->will($this->returnValue(null)); - $this->blockLegacyClientVersionPlugin->beforeHandler($request); - } - -} diff --git a/apps/dav/tests/unit/connector/sabre/DummyGetResponsePluginTest.php b/apps/dav/tests/unit/connector/sabre/DummyGetResponsePluginTest.php deleted file mode 100644 index 0ead617f461..00000000000 --- a/apps/dav/tests/unit/connector/sabre/DummyGetResponsePluginTest.php +++ /dev/null @@ -1,70 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCA\DAV\Connector\Sabre\DummyGetResponsePlugin; -use Test\TestCase; - -/** - * Class DummyGetResponsePluginTest - * - * @package Test\Connector\Sabre - */ -class DummyGetResponsePluginTest extends TestCase { - /** @var DummyGetResponsePlugin */ - private $dummyGetResponsePlugin; - - public function setUp() { - parent::setUp(); - - $this->dummyGetResponsePlugin = new DummyGetResponsePlugin(); - } - - public function testInitialize() { - /** @var \Sabre\DAV\Server $server */ - $server = $this->getMock('\Sabre\DAV\Server'); - $server - ->expects($this->once()) - ->method('on') - ->with('method:GET', [$this->dummyGetResponsePlugin, 'httpGet'], 200); - - $this->dummyGetResponsePlugin->initialize($server); - } - - - public function testHttpGet() { - /** @var \Sabre\HTTP\RequestInterface $request */ - $request = $this->getMock('\Sabre\HTTP\RequestInterface'); - /** @var \Sabre\HTTP\ResponseInterface $response */ - $response = $server = $this->getMock('\Sabre\HTTP\ResponseInterface'); - $response - ->expects($this->once()) - ->method('setBody'); - $response - ->expects($this->once()) - ->method('setStatus') - ->with(200); - - $this->assertSame(false, $this->dummyGetResponsePlugin->httpGet($request, $response)); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/FakeLockerPluginTest.php b/apps/dav/tests/unit/connector/sabre/FakeLockerPluginTest.php deleted file mode 100644 index 30d2bf41810..00000000000 --- a/apps/dav/tests/unit/connector/sabre/FakeLockerPluginTest.php +++ /dev/null @@ -1,174 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCA\DAV\Connector\Sabre\FakeLockerPlugin; -use Sabre\HTTP\Response; -use Test\TestCase; - -/** - * Class FakeLockerPluginTest - * - * @package OCA\DAV\Tests\Unit\Connector\Sabre - */ -class FakeLockerPluginTest extends TestCase { - /** @var FakeLockerPlugin */ - private $fakeLockerPlugin; - - public function setUp() { - parent::setUp(); - $this->fakeLockerPlugin = new FakeLockerPlugin(); - } - - public function testInitialize() { - /** @var \Sabre\DAV\Server $server */ - $server = $this->getMock('\Sabre\DAV\Server'); - $server - ->expects($this->at(0)) - ->method('on') - ->with('method:LOCK', [$this->fakeLockerPlugin, 'fakeLockProvider'], 1); - $server - ->expects($this->at(1)) - ->method('on') - ->with('method:UNLOCK', [$this->fakeLockerPlugin, 'fakeUnlockProvider'], 1); - $server - ->expects($this->at(2)) - ->method('on') - ->with('propFind', [$this->fakeLockerPlugin, 'propFind']); - $server - ->expects($this->at(3)) - ->method('on') - ->with('validateTokens', [$this->fakeLockerPlugin, 'validateTokens']); - - $this->fakeLockerPlugin->initialize($server); - } - - public function testGetHTTPMethods() { - $expected = [ - 'LOCK', - 'UNLOCK', - ]; - $this->assertSame($expected, $this->fakeLockerPlugin->getHTTPMethods('Test')); - } - - public function testGetFeatures() { - $expected = [ - 2, - ]; - $this->assertSame($expected, $this->fakeLockerPlugin->getFeatures()); - } - - public function testPropFind() { - $propFind = $this->getMockBuilder('\Sabre\DAV\PropFind') - ->disableOriginalConstructor() - ->getMock(); - $node = $this->getMock('\Sabre\DAV\INode'); - - $propFind->expects($this->at(0)) - ->method('handle') - ->with('{DAV:}supportedlock'); - $propFind->expects($this->at(1)) - ->method('handle') - ->with('{DAV:}lockdiscovery'); - - $this->fakeLockerPlugin->propFind($propFind, $node); - } - - public function tokenDataProvider() { - return [ - [ - [ - [ - 'tokens' => [ - [ - 'token' => 'aToken', - 'validToken' => false, - ], - [], - [ - 'token' => 'opaquelocktoken:asdf', - 'validToken' => false, - ] - ], - ] - ], - [ - [ - 'tokens' => [ - [ - 'token' => 'aToken', - 'validToken' => false, - ], - [], - [ - 'token' => 'opaquelocktoken:asdf', - 'validToken' => true, - ] - ], - ] - ], - ] - ]; - } - - /** - * @dataProvider tokenDataProvider - * @param array $input - * @param array $expected - */ - public function testValidateTokens(array $input, array $expected) { - $request = $this->getMock('\Sabre\HTTP\RequestInterface'); - $this->fakeLockerPlugin->validateTokens($request, $input); - $this->assertSame($expected, $input); - } - - public function testFakeLockProvider() { - $request = $this->getMock('\Sabre\HTTP\RequestInterface'); - $response = new Response(); - $server = $this->getMock('\Sabre\DAV\Server'); - $this->fakeLockerPlugin->initialize($server); - - $request->expects($this->exactly(2)) - ->method('getPath') - ->will($this->returnValue('MyPath')); - - $this->assertSame(false, $this->fakeLockerPlugin->fakeLockProvider($request, $response)); - - $expectedXml = 'MyPathinfinitySecond-1800opaquelocktoken:fe4f7f2437b151fbcb4e9f5c8118c6b1'; - - $this->assertXmlStringEqualsXmlString($expectedXml, $response->getBody()); - } - - public function testFakeUnlockProvider() { - $request = $this->getMock('\Sabre\HTTP\RequestInterface'); - $response = $this->getMock('\Sabre\HTTP\ResponseInterface'); - - $response->expects($this->once()) - ->method('setStatus') - ->with('204'); - $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Length', '0'); - - $this->assertSame(false, $this->fakeLockerPlugin->fakeUnlockProvider($request, $response)); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/MaintenancePluginTest.php b/apps/dav/tests/unit/connector/sabre/MaintenancePluginTest.php deleted file mode 100644 index dea1e64db1d..00000000000 --- a/apps/dav/tests/unit/connector/sabre/MaintenancePluginTest.php +++ /dev/null @@ -1,73 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCA\DAV\Connector\Sabre\MaintenancePlugin; -use Test\TestCase; -use OCP\IConfig; - -/** - * Class MaintenancePluginTest - * - * @package Test\Connector\Sabre - */ -class MaintenancePluginTest extends TestCase { - /** @var IConfig */ - private $config; - /** @var MaintenancePlugin */ - private $maintenancePlugin; - - public function setUp() { - parent::setUp(); - - $this->config = $this->getMock('\OCP\IConfig'); - $this->maintenancePlugin = new MaintenancePlugin($this->config); - } - - /** - * @expectedException \Sabre\DAV\Exception\ServiceUnavailable - * @expectedExceptionMessage System in single user mode. - */ - public function testSingleUserMode() { - $this->config - ->expects($this->once()) - ->method('getSystemValue') - ->with('singleuser', false) - ->will($this->returnValue(true)); - - $this->maintenancePlugin->checkMaintenanceMode(); - } - - /** - * @expectedException \Sabre\DAV\Exception\ServiceUnavailable - * @expectedExceptionMessage System in single user mode. - */ - public function testMaintenanceMode() { - $this->config - ->expects($this->exactly(1)) - ->method('getSystemValue') - ->will($this->onConsecutiveCalls([false, true])); - - $this->maintenancePlugin->checkMaintenanceMode(); - } - -} diff --git a/apps/dav/tests/unit/connector/sabre/auth.php b/apps/dav/tests/unit/connector/sabre/auth.php deleted file mode 100644 index d3f697ba8e6..00000000000 --- a/apps/dav/tests/unit/connector/sabre/auth.php +++ /dev/null @@ -1,611 +0,0 @@ - - * @author Roeland Jago Douma - * @author Thomas Müller - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCP\IRequest; -use OCP\IUser; -use Test\TestCase; -use OCP\ISession; -use OC\User\Session; - -/** - * Class Auth - * - * @package OCA\DAV\Connector\Sabre - * @group DB - */ -class Auth extends TestCase { - /** @var ISession */ - private $session; - /** @var \OCA\DAV\Connector\Sabre\Auth */ - private $auth; - /** @var Session */ - private $userSession; - /** @var IRequest */ - private $request; - - public function setUp() { - parent::setUp(); - $this->session = $this->getMockBuilder('\OCP\ISession') - ->disableOriginalConstructor()->getMock(); - $this->userSession = $this->getMockBuilder('\OC\User\Session') - ->disableOriginalConstructor()->getMock(); - $this->request = $this->getMockBuilder('\OCP\IRequest') - ->disableOriginalConstructor()->getMock(); - $this->auth = new \OCA\DAV\Connector\Sabre\Auth( - $this->session, - $this->userSession, - $this->request - ); - } - - public function testIsDavAuthenticatedWithoutDavSession() { - $this->session - ->expects($this->once()) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue(null)); - - $this->assertFalse($this->invokePrivate($this->auth, 'isDavAuthenticated', ['MyTestUser'])); - } - - public function testIsDavAuthenticatedWithWrongDavSession() { - $this->session - ->expects($this->exactly(2)) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue('AnotherUser')); - - $this->assertFalse($this->invokePrivate($this->auth, 'isDavAuthenticated', ['MyTestUser'])); - } - - public function testIsDavAuthenticatedWithCorrectDavSession() { - $this->session - ->expects($this->exactly(2)) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue('MyTestUser')); - - $this->assertTrue($this->invokePrivate($this->auth, 'isDavAuthenticated', ['MyTestUser'])); - } - - public function testValidateUserPassOfAlreadyDAVAuthenticatedUser() { - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->exactly(2)) - ->method('getUID') - ->will($this->returnValue('MyTestUser')); - $this->userSession - ->expects($this->once()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->userSession - ->expects($this->exactly(2)) - ->method('getUser') - ->will($this->returnValue($user)); - $this->session - ->expects($this->exactly(2)) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue('MyTestUser')); - $this->session - ->expects($this->once()) - ->method('close'); - - $this->assertTrue($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); - } - - public function testValidateUserPassOfInvalidDAVAuthenticatedUser() { - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('MyTestUser')); - $this->userSession - ->expects($this->once()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->userSession - ->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - $this->session - ->expects($this->exactly(2)) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue('AnotherUser')); - $this->session - ->expects($this->once()) - ->method('close'); - - $this->assertFalse($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); - } - - public function testValidateUserPassOfInvalidDAVAuthenticatedUserWithValidPassword() { - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->exactly(4)) - ->method('getUID') - ->will($this->returnValue('MyTestUser')); - $this->userSession - ->expects($this->once()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->userSession - ->expects($this->exactly(4)) - ->method('getUser') - ->will($this->returnValue($user)); - $this->session - ->expects($this->exactly(2)) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue('AnotherUser')); - $this->userSession - ->expects($this->once()) - ->method('logClientIn') - ->with('MyTestUser', 'MyTestPassword') - ->will($this->returnValue(true)); - $this->userSession - ->expects($this->once()) - ->method('createSessionToken') - ->with($this->request, 'MyTestUser', 'MyTestUser', 'MyTestPassword'); - $this->session - ->expects($this->once()) - ->method('set') - ->with('AUTHENTICATED_TO_DAV_BACKEND', 'MyTestUser'); - $this->session - ->expects($this->once()) - ->method('close'); - - $this->assertTrue($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); - } - - public function testValidateUserPassWithInvalidPassword() { - $this->userSession - ->expects($this->once()) - ->method('isLoggedIn') - ->will($this->returnValue(false)); - $this->userSession - ->expects($this->once()) - ->method('logClientIn') - ->with('MyTestUser', 'MyTestPassword') - ->will($this->returnValue(false)); - $this->session - ->expects($this->once()) - ->method('close'); - - $this->assertFalse($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); - } - - - public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGet() { - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->request - ->expects($this->any()) - ->method('getMethod') - ->willReturn('POST'); - $this->session - ->expects($this->any()) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue(null)); - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('MyWrongDavUser')); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); - $this->request - ->expects($this->once()) - ->method('passesCSRFCheck') - ->willReturn(false); - - $expectedResponse = [ - false, - "No 'Authorization: Basic' header found. Either the client didn't send one, or the server is mis-configured", - ]; - $response = $this->auth->check($request, $response); - $this->assertSame($expectedResponse, $response); - } - - public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndCorrectlyDavAuthenticated() { - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->willReturn(true); - $this->request - ->expects($this->any()) - ->method('getMethod') - ->willReturn('PROPFIND'); - $this->request - ->expects($this->any()) - ->method('isUserAgent') - ->with([ - '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/', - '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/', - '/^Mozilla\/5\.0 \(iOS\) ownCloud\-iOS.*$/', - ]) - ->willReturn(false); - $this->session - ->expects($this->any()) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue('LoggedInUser')); - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('LoggedInUser')); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); - $this->request - ->expects($this->once()) - ->method('passesCSRFCheck') - ->willReturn(false); - $this->auth->check($request, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotAuthenticated - * @expectedExceptionMessage CSRF check not passed. - */ - public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndIncorrectlyDavAuthenticated() { - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->willReturn(true); - $this->request - ->expects($this->any()) - ->method('getMethod') - ->willReturn('PROPFIND'); - $this->request - ->expects($this->any()) - ->method('isUserAgent') - ->with([ - '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/', - '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/', - '/^Mozilla\/5\.0 \(iOS\) ownCloud\-iOS.*$/', - ]) - ->willReturn(false); - $this->session - ->expects($this->any()) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue('AnotherUser')); - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('LoggedInUser')); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); - $this->request - ->expects($this->once()) - ->method('passesCSRFCheck') - ->willReturn(false); - $this->auth->check($request, $response); - } - - public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGetAndDesktopClient() { - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->request - ->expects($this->any()) - ->method('getMethod') - ->willReturn('POST'); - $this->request - ->expects($this->any()) - ->method('isUserAgent') - ->with([ - '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/', - '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/', - '/^Mozilla\/5\.0 \(iOS\) ownCloud\-iOS.*$/', - ]) - ->willReturn(true); - $this->session - ->expects($this->any()) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue(null)); - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('MyWrongDavUser')); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); - $this->request - ->expects($this->once()) - ->method('passesCSRFCheck') - ->willReturn(false); - - $this->auth->check($request, $response); - } - - public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForGet() { - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->session - ->expects($this->any()) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue(null)); - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('MyWrongDavUser')); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); - $this->request - ->expects($this->any()) - ->method('getMethod') - ->willReturn('GET'); - - $response = $this->auth->check($request, $response); - $this->assertEquals([true, 'principals/users/MyWrongDavUser'], $response); - } - - public function testAuthenticateAlreadyLoggedInWithCsrfTokenForGet() { - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->session - ->expects($this->any()) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue(null)); - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('MyWrongDavUser')); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); - $this->request - ->expects($this->once()) - ->method('passesCSRFCheck') - ->willReturn(true); - - $response = $this->auth->check($request, $response); - $this->assertEquals([true, 'principals/users/MyWrongDavUser'], $response); - } - - public function testAuthenticateNoBasicAuthenticateHeadersProvided() { - $server = $this->getMockBuilder('\Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $server->httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->auth->check($server->httpRequest, $server->httpResponse); - $this->assertEquals([false, 'No \'Authorization: Basic\' header found. Either the client didn\'t send one, or the server is mis-configured'], $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotAuthenticated - * @expectedExceptionMessage Cannot authenticate over ajax calls - */ - public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjax() { - /** @var \Sabre\HTTP\RequestInterface $httpRequest */ - $httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - /** @var \Sabre\HTTP\ResponseInterface $httpResponse */ - $httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->will($this->returnValue(false)); - $httpRequest - ->expects($this->once()) - ->method('getHeader') - ->with('X-Requested-With') - ->will($this->returnValue('XMLHttpRequest')); - $this->auth->check($httpRequest, $httpResponse); - } - - public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjaxButUserIsStillLoggedIn() { - /** @var \Sabre\HTTP\RequestInterface $httpRequest */ - $httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - /** @var \Sabre\HTTP\ResponseInterface $httpResponse */ - $httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - /** @var IUser */ - $user = $this->getMock('OCP\IUser'); - $user->method('getUID')->willReturn('MyTestUser'); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->will($this->returnValue(true)); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->willReturn($user); - $this->session - ->expects($this->atLeastOnce()) - ->method('get') - ->with('AUTHENTICATED_TO_DAV_BACKEND') - ->will($this->returnValue('MyTestUser')); - $this->request - ->expects($this->once()) - ->method('getMethod') - ->willReturn('GET'); - $httpRequest - ->expects($this->atLeastOnce()) - ->method('getHeader') - ->with('Authorization') - ->will($this->returnValue(null)); - $this->assertEquals( - [true, 'principals/users/MyTestUser'], - $this->auth->check($httpRequest, $httpResponse) - ); - } - - public function testAuthenticateValidCredentials() { - $server = $this->getMockBuilder('\Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest - ->expects($this->at(0)) - ->method('getHeader') - ->with('X-Requested-With') - ->will($this->returnValue(null)); - $server->httpRequest - ->expects($this->at(1)) - ->method('getHeader') - ->with('Authorization') - ->will($this->returnValue('basic dXNlcm5hbWU6cGFzc3dvcmQ=')); - $server->httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->once()) - ->method('logClientIn') - ->with('username', 'password') - ->will($this->returnValue(true)); - $this->userSession - ->expects($this->once()) - ->method('createSessionToken'); - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->exactly(4)) - ->method('getUID') - ->will($this->returnValue('MyTestUser')); - $this->userSession - ->expects($this->exactly(4)) - ->method('getUser') - ->will($this->returnValue($user)); - $response = $this->auth->check($server->httpRequest, $server->httpResponse); - $this->assertEquals([true, 'principals/users/MyTestUser'], $response); - } - - public function testAuthenticateInvalidCredentials() { - $server = $this->getMockBuilder('\Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest = $this->getMockBuilder('\Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest - ->expects($this->at(0)) - ->method('getHeader') - ->with('X-Requested-With') - ->will($this->returnValue(null)); - $server->httpRequest - ->expects($this->at(1)) - ->method('getHeader') - ->with('Authorization') - ->will($this->returnValue('basic dXNlcm5hbWU6cGFzc3dvcmQ=')); - $server->httpResponse = $this->getMockBuilder('\Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - $this->userSession - ->expects($this->once()) - ->method('logClientIn') - ->with('username', 'password') - ->will($this->returnValue(false)); - $response = $this->auth->check($server->httpRequest, $server->httpResponse); - $this->assertEquals([false, 'Username or password was incorrect'], $response); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/commentpropertiesplugin.php b/apps/dav/tests/unit/connector/sabre/commentpropertiesplugin.php deleted file mode 100644 index f7f87e01544..00000000000 --- a/apps/dav/tests/unit/connector/sabre/commentpropertiesplugin.php +++ /dev/null @@ -1,149 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin as CommentPropertiesPluginImplementation; - -class CommentsPropertiesPlugin extends \Test\TestCase { - - /** @var CommentPropertiesPluginImplementation */ - protected $plugin; - protected $commentsManager; - protected $userSession; - protected $server; - - public function setUp() { - parent::setUp(); - - $this->commentsManager = $this->getMock('\OCP\Comments\ICommentsManager'); - $this->userSession = $this->getMock('\OCP\IUserSession'); - - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); - - $this->plugin = new CommentPropertiesPluginImplementation($this->commentsManager, $this->userSession); - $this->plugin->initialize($this->server); - } - - public function nodeProvider() { - $mocks = []; - foreach(['\OCA\DAV\Connector\Sabre\File', '\OCA\DAV\Connector\Sabre\Directory', '\Sabre\DAV\INode'] as $class) { - $mocks[] = $this->getMockBuilder($class) - ->disableOriginalConstructor() - ->getMock(); - } - - return [ - [$mocks[0], true], - [$mocks[1], true], - [$mocks[2], false] - ]; - } - - /** - * @dataProvider nodeProvider - * @param $node - * @param $expectedSuccessful - */ - public function testHandleGetProperties($node, $expectedSuccessful) { - $propFind = $this->getMockBuilder('\Sabre\DAV\PropFind') - ->disableOriginalConstructor() - ->getMock(); - - if($expectedSuccessful) { - $propFind->expects($this->exactly(3)) - ->method('handle'); - } else { - $propFind->expects($this->never()) - ->method('handle'); - } - - $this->plugin->handleGetProperties($propFind, $node); - } - - public function baseUriProvider() { - return [ - ['owncloud/remote.php/webdav/', '4567', 'owncloud/remote.php/dav/comments/files/4567'], - ['owncloud/remote.php/files/', '4567', 'owncloud/remote.php/dav/comments/files/4567'], - ['owncloud/wicked.php/files/', '4567', null] - ]; - } - - /** - * @dataProvider baseUriProvider - * @param $baseUri - * @param $fid - * @param $expectedHref - */ - public function testGetCommentsLink($baseUri, $fid, $expectedHref) { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue($fid)); - - $this->server->expects($this->once()) - ->method('getBaseUri') - ->will($this->returnValue($baseUri)); - - $href = $this->plugin->getCommentsLink($node); - $this->assertSame($expectedHref, $href); - } - - public function userProvider() { - return [ - [$this->getMock('\OCP\IUser')], - [null] - ]; - } - - /** - * @dataProvider userProvider - * @param $user - */ - public function testGetUnreadCount($user) { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue('4567')); - - $this->userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->commentsManager->expects($this->any()) - ->method('getNumberOfCommentsForObject') - ->will($this->returnValue(42)); - - $unread = $this->plugin->getUnreadCount($node); - if(is_null($user)) { - $this->assertNull($unread); - } else { - $this->assertSame($unread, 42); - } - } - -} diff --git a/apps/dav/tests/unit/connector/sabre/copyetagheaderplugintest.php b/apps/dav/tests/unit/connector/sabre/copyetagheaderplugintest.php deleted file mode 100644 index 7f6fb26e4d1..00000000000 --- a/apps/dav/tests/unit/connector/sabre/copyetagheaderplugintest.php +++ /dev/null @@ -1,62 +0,0 @@ - - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -/** - * Copyright (c) 2015 Vincent Petry - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -class CopyEtagPluginTest extends \Test\TestCase { - - /** - * @var \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin - */ - private $plugin; - - public function setUp() { - parent::setUp(); - $this->server = new \Sabre\DAV\Server(); - $this->plugin = new \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin(); - $this->plugin->initialize($this->server); - } - - public function testCopyEtag() { - $request = new \Sabre\Http\Request(); - $response = new \Sabre\Http\Response(); - $response->setHeader('Etag', 'abcd'); - - $this->plugin->afterMethod($request, $response); - - $this->assertEquals('abcd', $response->getHeader('OC-Etag')); - } - - public function testNoopWhenEmpty() { - $request = new \Sabre\Http\Request(); - $response = new \Sabre\Http\Response(); - - $this->plugin->afterMethod($request, $response); - - $this->assertNull($response->getHeader('OC-Etag')); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/custompropertiesbackend.php b/apps/dav/tests/unit/connector/sabre/custompropertiesbackend.php deleted file mode 100644 index e0ba61e9134..00000000000 --- a/apps/dav/tests/unit/connector/sabre/custompropertiesbackend.php +++ /dev/null @@ -1,313 +0,0 @@ - - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -/** - * Copyright (c) 2015 Vincent Petry - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ - -/** - * Class CustomPropertiesBackend - * - * @group DB - * - * @package Tests\Connector\Sabre - */ -class CustomPropertiesBackend extends \Test\TestCase { - - /** - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var \Sabre\DAV\Tree - */ - private $tree; - - /** - * @var \OCA\DAV\Connector\Sabre\CustomPropertiesBackend - */ - private $plugin; - - /** - * @var \OCP\IUser - */ - private $user; - - public function setUp() { - parent::setUp(); - $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') - ->disableOriginalConstructor() - ->getMock(); - - $userId = $this->getUniqueID('testcustompropertiesuser'); - - $this->user = $this->getMock('\OCP\IUser'); - $this->user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue($userId)); - - $this->plugin = new \OCA\DAV\Connector\Sabre\CustomPropertiesBackend( - $this->tree, - \OC::$server->getDatabaseConnection(), - $this->user - ); - } - - public function tearDown() { - $connection = \OC::$server->getDatabaseConnection(); - $deleteStatement = $connection->prepare( - 'DELETE FROM `*PREFIX*properties`' . - ' WHERE `userid` = ?' - ); - $deleteStatement->execute( - array( - $this->user->getUID(), - ) - ); - $deleteStatement->closeCursor(); - } - - private function createTestNode($class) { - $node = $this->getMockBuilder($class) - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - - $node->expects($this->any()) - ->method('getPath') - ->will($this->returnValue('/dummypath')); - - return $node; - } - - private function applyDefaultProps($path = '/dummypath') { - // properties to set - $propPatch = new \Sabre\DAV\PropPatch(array( - 'customprop' => 'value1', - 'customprop2' => 'value2', - )); - - $this->plugin->propPatch( - $path, - $propPatch - ); - - $propPatch->commit(); - - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertEquals(200, $result['customprop']); - $this->assertEquals(200, $result['customprop2']); - } - - /** - * Test that propFind on a missing file soft fails - */ - public function testPropFindMissingFileSoftFail() { - $this->tree->expects($this->at(0)) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); - - $this->tree->expects($this->at(1)) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->throwException(new \Sabre\DAV\Exception\ServiceUnavailable())); - - $propFind = new \Sabre\DAV\PropFind( - '/dummypath', - array( - 'customprop', - 'customprop2', - 'unsetprop', - ), - 0 - ); - - $this->plugin->propFind( - '/dummypath', - $propFind - ); - - $this->plugin->propFind( - '/dummypath', - $propFind - ); - - // no exception, soft fail - $this->assertTrue(true); - } - - /** - * Test setting/getting properties - */ - public function testSetGetPropertiesForFile() { - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->returnValue($node)); - - $this->applyDefaultProps(); - - $propFind = new \Sabre\DAV\PropFind( - '/dummypath', - array( - 'customprop', - 'customprop2', - 'unsetprop', - ), - 0 - ); - - $this->plugin->propFind( - '/dummypath', - $propFind - ); - - $this->assertEquals('value1', $propFind->get('customprop')); - $this->assertEquals('value2', $propFind->get('customprop2')); - $this->assertEquals(array('unsetprop'), $propFind->get404Properties()); - } - - /** - * Test getting properties from directory - */ - public function testGetPropertiesForDirectory() { - $rootNode = $this->createTestNode('\OCA\DAV\Connector\Sabre\Directory'); - - $nodeSub = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') - ->disableOriginalConstructor() - ->getMock(); - $nodeSub->expects($this->any()) - ->method('getId') - ->will($this->returnValue(456)); - - $nodeSub->expects($this->any()) - ->method('getPath') - ->will($this->returnValue('/dummypath/test.txt')); - - $rootNode->expects($this->once()) - ->method('getChildren') - ->will($this->returnValue(array($nodeSub))); - - $this->tree->expects($this->at(0)) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->returnValue($rootNode)); - - $this->tree->expects($this->at(1)) - ->method('getNodeForPath') - ->with('/dummypath/test.txt') - ->will($this->returnValue($nodeSub)); - - $this->tree->expects($this->at(2)) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->returnValue($rootNode)); - - $this->tree->expects($this->at(3)) - ->method('getNodeForPath') - ->with('/dummypath/test.txt') - ->will($this->returnValue($nodeSub)); - - $this->applyDefaultProps('/dummypath'); - $this->applyDefaultProps('/dummypath/test.txt'); - - $propNames = array( - 'customprop', - 'customprop2', - 'unsetprop', - ); - - $propFindRoot = new \Sabre\DAV\PropFind( - '/dummypath', - $propNames, - 1 - ); - - $propFindSub = new \Sabre\DAV\PropFind( - '/dummypath/test.txt', - $propNames, - 0 - ); - - $this->plugin->propFind( - '/dummypath', - $propFindRoot - ); - - $this->plugin->propFind( - '/dummypath/test.txt', - $propFindSub - ); - - // TODO: find a way to assert that no additional SQL queries were - // run while doing the second propFind - - $this->assertEquals('value1', $propFindRoot->get('customprop')); - $this->assertEquals('value2', $propFindRoot->get('customprop2')); - $this->assertEquals(array('unsetprop'), $propFindRoot->get404Properties()); - - $this->assertEquals('value1', $propFindSub->get('customprop')); - $this->assertEquals('value2', $propFindSub->get('customprop2')); - $this->assertEquals(array('unsetprop'), $propFindSub->get404Properties()); - } - - /** - * Test delete property - */ - public function testDeleteProperty() { - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->returnValue($node)); - - $this->applyDefaultProps(); - - $propPatch = new \Sabre\DAV\PropPatch(array( - 'customprop' => null, - )); - - $this->plugin->propPatch( - '/dummypath', - $propPatch - ); - - $propPatch->commit(); - - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertEquals(204, $result['customprop']); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/directory.php b/apps/dav/tests/unit/connector/sabre/directory.php deleted file mode 100644 index e25a82c4876..00000000000 --- a/apps/dav/tests/unit/connector/sabre/directory.php +++ /dev/null @@ -1,267 +0,0 @@ - - * @author Robin Appelman - * @author Thomas Müller - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCP\Files\ForbiddenException; - -/** - * @group DB - */ -class Directory extends \Test\TestCase { - - /** @var \OC\Files\View | \PHPUnit_Framework_MockObject_MockObject */ - private $view; - /** @var \OC\Files\FileInfo | \PHPUnit_Framework_MockObject_MockObject */ - private $info; - - protected function setUp() { - parent::setUp(); - - $this->view = $this->getMock('OC\Files\View', array(), array(), '', false); - $this->info = $this->getMock('OC\Files\FileInfo', array(), array(), '', false); - } - - private function getDir($path = '/') { - $this->view->expects($this->once()) - ->method('getRelativePath') - ->will($this->returnValue($path)); - - $this->info->expects($this->once()) - ->method('getPath') - ->will($this->returnValue($path)); - - return new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteRootFolderFails() { - $this->info->expects($this->any()) - ->method('isDeletable') - ->will($this->returnValue(true)); - $this->view->expects($this->never()) - ->method('rmdir'); - $dir = $this->getDir(); - $dir->delete(); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\Forbidden - */ - public function testDeleteForbidden() { - // deletion allowed - $this->info->expects($this->once()) - ->method('isDeletable') - ->will($this->returnValue(true)); - - // but fails - $this->view->expects($this->once()) - ->method('rmdir') - ->with('sub') - ->willThrowException(new ForbiddenException('', true)); - - $dir = $this->getDir('sub'); - $dir->delete(); - } - - /** - * - */ - public function testDeleteFolderWhenAllowed() { - // deletion allowed - $this->info->expects($this->once()) - ->method('isDeletable') - ->will($this->returnValue(true)); - - // but fails - $this->view->expects($this->once()) - ->method('rmdir') - ->with('sub') - ->will($this->returnValue(true)); - - $dir = $this->getDir('sub'); - $dir->delete(); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteFolderFailsWhenNotAllowed() { - $this->info->expects($this->once()) - ->method('isDeletable') - ->will($this->returnValue(false)); - - $dir = $this->getDir('sub'); - $dir->delete(); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteFolderThrowsWhenDeletionFailed() { - // deletion allowed - $this->info->expects($this->once()) - ->method('isDeletable') - ->will($this->returnValue(true)); - - // but fails - $this->view->expects($this->once()) - ->method('rmdir') - ->with('sub') - ->will($this->returnValue(false)); - - $dir = $this->getDir('sub'); - $dir->delete(); - } - - public function testGetChildren() { - $info1 = $this->getMockBuilder('OC\Files\FileInfo') - ->disableOriginalConstructor() - ->getMock(); - $info2 = $this->getMockBuilder('OC\Files\FileInfo') - ->disableOriginalConstructor() - ->getMock(); - $info1->expects($this->any()) - ->method('getName') - ->will($this->returnValue('first')); - $info1->expects($this->any()) - ->method('getEtag') - ->will($this->returnValue('abc')); - $info2->expects($this->any()) - ->method('getName') - ->will($this->returnValue('second')); - $info2->expects($this->any()) - ->method('getEtag') - ->will($this->returnValue('def')); - - $this->view->expects($this->once()) - ->method('getDirectoryContent') - ->with('') - ->will($this->returnValue(array($info1, $info2))); - - $this->view->expects($this->any()) - ->method('getRelativePath') - ->will($this->returnValue('')); - - $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); - $nodes = $dir->getChildren(); - - $this->assertEquals(2, count($nodes)); - - // calling a second time just returns the cached values, - // does not call getDirectoryContents again - $dir->getChildren(); - } - - /** - * @expectedException \Sabre\DAV\Exception\ServiceUnavailable - */ - public function testGetChildThrowStorageNotAvailableException() { - $this->view->expects($this->once()) - ->method('getFileInfo') - ->willThrowException(new \OCP\Files\StorageNotAvailableException()); - - $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); - $dir->getChild('.'); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\InvalidPath - */ - public function testGetChildThrowInvalidPath() { - $this->view->expects($this->once()) - ->method('verifyPath') - ->willThrowException(new \OCP\Files\InvalidPathException()); - $this->view->expects($this->never()) - ->method('getFileInfo'); - - $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); - $dir->getChild('.'); - } - - public function testGetQuotaInfoUnlimited() { - $storage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Quota') - ->disableOriginalConstructor() - ->getMock(); - - $storage->expects($this->any()) - ->method('instanceOfStorage') - ->will($this->returnValueMap([ - '\OC\Files\Storage\Shared' => false, - '\OC\Files\Storage\Wrapper\Quota' => false, - ])); - - $storage->expects($this->never()) - ->method('getQuota'); - - $storage->expects($this->once()) - ->method('free_space') - ->will($this->returnValue(800)); - - $this->info->expects($this->once()) - ->method('getSize') - ->will($this->returnValue(200)); - - $this->info->expects($this->once()) - ->method('getStorage') - ->will($this->returnValue($storage)); - - $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); - $this->assertEquals([200, -3], $dir->getQuotaInfo()); //200 used, unlimited - } - - public function testGetQuotaInfoSpecific() { - $storage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Quota') - ->disableOriginalConstructor() - ->getMock(); - - $storage->expects($this->any()) - ->method('instanceOfStorage') - ->will($this->returnValueMap([ - ['\OC\Files\Storage\Shared', false], - ['\OC\Files\Storage\Wrapper\Quota', true], - ])); - - $storage->expects($this->once()) - ->method('getQuota') - ->will($this->returnValue(1000)); - - $storage->expects($this->once()) - ->method('free_space') - ->will($this->returnValue(800)); - - $this->info->expects($this->once()) - ->method('getSize') - ->will($this->returnValue(200)); - - $this->info->expects($this->once()) - ->method('getStorage') - ->will($this->returnValue($storage)); - - $dir = new \OCA\DAV\Connector\Sabre\Directory($this->view, $this->info); - $this->assertEquals([200, 800], $dir->getQuotaInfo()); //200 used, 800 free - } -} diff --git a/apps/dav/tests/unit/connector/sabre/exception/forbiddentest.php b/apps/dav/tests/unit/connector/sabre/exception/forbiddentest.php deleted file mode 100644 index 36ea97df9f7..00000000000 --- a/apps/dav/tests/unit/connector/sabre/exception/forbiddentest.php +++ /dev/null @@ -1,57 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\Exception; - -use OCA\DAV\Connector\Sabre\Exception\Forbidden; - -class ForbiddenTest extends \Test\TestCase { - - public function testSerialization() { - - // create xml doc - $DOM = new \DOMDocument('1.0','utf-8'); - $DOM->formatOutput = true; - $error = $DOM->createElementNS('DAV:','d:error'); - $error->setAttribute('xmlns:s', \Sabre\DAV\Server::NS_SABREDAV); - $DOM->appendChild($error); - - // serialize the exception - $message = "1234567890"; - $retry = false; - $expectedXml = << - - false - 1234567890 - - -EOD; - - $ex = new Forbidden($message, $retry); - $server = $this->getMock('Sabre\DAV\Server'); - $ex->serialize($server, $error); - - // assert - $xml = $DOM->saveXML(); - $this->assertEquals($expectedXml, $xml); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/exception/invalidpathtest.php b/apps/dav/tests/unit/connector/sabre/exception/invalidpathtest.php deleted file mode 100644 index 431a0484d65..00000000000 --- a/apps/dav/tests/unit/connector/sabre/exception/invalidpathtest.php +++ /dev/null @@ -1,58 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\Exception; - -use OCA\DAV\Connector\Sabre\Exception\InvalidPath; - -class InvalidPathTest extends \Test\TestCase { - - public function testSerialization() { - - // create xml doc - $DOM = new \DOMDocument('1.0','utf-8'); - $DOM->formatOutput = true; - $error = $DOM->createElementNS('DAV:','d:error'); - $error->setAttribute('xmlns:s', \Sabre\DAV\Server::NS_SABREDAV); - $DOM->appendChild($error); - - // serialize the exception - $message = "1234567890"; - $retry = false; - $expectedXml = << - - false - 1234567890 - - -EOD; - - $ex = new InvalidPath($message, $retry); - $server = $this->getMock('Sabre\DAV\Server'); - $ex->serialize($server, $error); - - // assert - $xml = $DOM->saveXML(); - $this->assertEquals($expectedXml, $xml); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/exceptionloggerplugin.php b/apps/dav/tests/unit/connector/sabre/exceptionloggerplugin.php deleted file mode 100644 index b76285be336..00000000000 --- a/apps/dav/tests/unit/connector/sabre/exceptionloggerplugin.php +++ /dev/null @@ -1,83 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCA\DAV\Connector\Sabre\Exception\InvalidPath; -use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin as PluginToTest; -use OC\Log; -use OCP\ILogger; -use PHPUnit_Framework_MockObject_MockObject; -use Sabre\DAV\Exception\NotFound; -use Sabre\DAV\Server; -use Test\TestCase; - -class TestLogger extends Log { - public $message; - public $level; - - public function __construct($logger = null) { - //disable original constructor - } - - public function log($level, $message, array $context = array()) { - $this->level = $level; - $this->message = $message; - } -} - -class ExceptionLoggerPlugin extends TestCase { - - /** @var Server */ - private $server; - - /** @var PluginToTest */ - private $plugin; - - /** @var TestLogger | PHPUnit_Framework_MockObject_MockObject */ - private $logger; - - private function init() { - $this->server = new Server(); - $this->logger = new TestLogger(); - $this->plugin = new PluginToTest('unit-test', $this->logger); - $this->plugin->initialize($this->server); - } - - /** - * @dataProvider providesExceptions - */ - public function testLogging($expectedLogLevel, $expectedMessage, $exception) { - $this->init(); - $this->plugin->logException($exception); - - $this->assertEquals($expectedLogLevel, $this->logger->level); - $this->assertStringStartsWith('Exception: {"Message":"' . $expectedMessage, $this->logger->message); - } - - public function providesExceptions() { - return [ - [0, 'HTTP\/1.1 404 Not Found', new NotFound()], - [4, 'HTTP\/1.1 400 This path leads to nowhere', new InvalidPath('This path leads to nowhere')] - ]; - } - -} diff --git a/apps/dav/tests/unit/connector/sabre/file.php b/apps/dav/tests/unit/connector/sabre/file.php deleted file mode 100644 index eab7ece159c..00000000000 --- a/apps/dav/tests/unit/connector/sabre/file.php +++ /dev/null @@ -1,987 +0,0 @@ - - * @author Robin Appelman - * @author Thomas Müller - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OC\Files\Storage\Local; -use OCP\Files\ForbiddenException; -use Test\HookHelper; -use OC\Files\Filesystem; -use OCP\Lock\ILockingProvider; - -/** - * Class File - * - * @group DB - * - * @package Test\Connector\Sabre - */ -class File extends \Test\TestCase { - - /** - * @var string - */ - private $user; - - public function setUp() { - parent::setUp(); - - \OC_Hook::clear(); - - $this->user = $this->getUniqueID('user_'); - $userManager = \OC::$server->getUserManager(); - $userManager->createUser($this->user, 'pass'); - - $this->loginAsUser($this->user); - } - - public function tearDown() { - $userManager = \OC::$server->getUserManager(); - $userManager->get($this->user)->delete(); - unset($_SERVER['HTTP_OC_CHUNKED']); - - parent::tearDown(); - } - - private function getMockStorage() { - $storage = $this->getMock('\OCP\Files\Storage'); - $storage->expects($this->any()) - ->method('getId') - ->will($this->returnValue('home::someuser')); - return $storage; - } - - /** - * @param string $string - */ - private function getStream($string) { - $stream = fopen('php://temp', 'r+'); - fwrite($stream, $string); - fseek($stream, 0); - return $stream; - } - - - public function fopenFailuresProvider() { - return [ - [ - // return false - null, - '\Sabre\Dav\Exception', - false - ], - [ - new \OCP\Files\NotPermittedException(), - 'Sabre\DAV\Exception\Forbidden' - ], - [ - new \OCP\Files\EntityTooLargeException(), - 'OCA\DAV\Connector\Sabre\Exception\EntityTooLarge' - ], - [ - new \OCP\Files\InvalidContentException(), - 'OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType' - ], - [ - new \OCP\Files\InvalidPathException(), - 'Sabre\DAV\Exception\Forbidden' - ], - [ - new \OCP\Files\ForbiddenException('', true), - 'OCA\DAV\Connector\Sabre\Exception\Forbidden' - ], - [ - new \OCP\Files\LockNotAcquiredException('/test.txt', 1), - 'OCA\DAV\Connector\Sabre\Exception\FileLocked' - ], - [ - new \OCP\Lock\LockedException('/test.txt'), - 'OCA\DAV\Connector\Sabre\Exception\FileLocked' - ], - [ - new \OCP\Encryption\Exceptions\GenericEncryptionException(), - 'Sabre\DAV\Exception\ServiceUnavailable' - ], - [ - new \OCP\Files\StorageNotAvailableException(), - 'Sabre\DAV\Exception\ServiceUnavailable' - ], - [ - new \Sabre\DAV\Exception('Generic sabre exception'), - 'Sabre\DAV\Exception', - false - ], - [ - new \Exception('Generic exception'), - 'Sabre\DAV\Exception' - ], - ]; - } - - /** - * @dataProvider fopenFailuresProvider - */ - public function testSimplePutFails($thrownException, $expectedException, $checkPreviousClass = true) { - // setup - $storage = $this->getMock( - '\OC\Files\Storage\Local', - ['fopen'], - [['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]] - ); - \OC\Files\Filesystem::mount($storage, [], $this->user . '/'); - $view = $this->getMock('\OC\Files\View', array('getRelativePath', 'resolvePath'), array()); - $view->expects($this->atLeastOnce()) - ->method('resolvePath') - ->will($this->returnCallback( - function ($path) use ($storage) { - return [$storage, $path]; - } - )); - - if ($thrownException !== null) { - $storage->expects($this->once()) - ->method('fopen') - ->will($this->throwException($thrownException)); - } else { - $storage->expects($this->once()) - ->method('fopen') - ->will($this->returnValue(false)); - } - - $view->expects($this->any()) - ->method('getRelativePath') - ->will($this->returnArgument(0)); - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $caughtException = null; - try { - $file->put('test data'); - } catch (\Exception $e) { - $caughtException = $e; - } - - $this->assertInstanceOf($expectedException, $caughtException); - if ($checkPreviousClass) { - $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious()); - } - - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); - } - - /** - * Test putting a file using chunking - * - * @dataProvider fopenFailuresProvider - */ - public function testChunkedPutFails($thrownException, $expectedException, $checkPreviousClass = false) { - // setup - $storage = $this->getMock( - '\OC\Files\Storage\Local', - ['fopen'], - [['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]] - ); - \OC\Files\Filesystem::mount($storage, [], $this->user . '/'); - $view = $this->getMock('\OC\Files\View', ['getRelativePath', 'resolvePath'], []); - $view->expects($this->atLeastOnce()) - ->method('resolvePath') - ->will($this->returnCallback( - function ($path) use ($storage) { - return [$storage, $path]; - } - )); - - if ($thrownException !== null) { - $storage->expects($this->once()) - ->method('fopen') - ->will($this->throwException($thrownException)); - } else { - $storage->expects($this->once()) - ->method('fopen') - ->will($this->returnValue(false)); - } - - $view->expects($this->any()) - ->method('getRelativePath') - ->will($this->returnArgument(0)); - - $_SERVER['HTTP_OC_CHUNKED'] = true; - - $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL - ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // put first chunk - $file->acquireLock(ILockingProvider::LOCK_SHARED); - $this->assertNull($file->put('test data one')); - $file->releaseLock(ILockingProvider::LOCK_SHARED); - - $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL - ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $caughtException = null; - try { - // last chunk - $file->acquireLock(ILockingProvider::LOCK_SHARED); - $file->put('test data two'); - $file->releaseLock(ILockingProvider::LOCK_SHARED); - } catch (\Exception $e) { - $caughtException = $e; - } - - $this->assertInstanceOf($expectedException, $caughtException); - if ($checkPreviousClass) { - $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious()); - } - - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); - } - - /** - * Simulate putting a file to the given path. - * - * @param string $path path to put the file into - * @param string $viewRoot root to use for the view - * - * @return null|string of the PUT operaiton which is usually the etag - */ - private function doPut($path, $viewRoot = null) { - $view = \OC\Files\Filesystem::getView(); - if (!is_null($viewRoot)) { - $view = new \OC\Files\View($viewRoot); - } else { - $viewRoot = '/' . $this->user . '/files'; - } - - $info = new \OC\Files\FileInfo( - $viewRoot . '/' . ltrim($path, '/'), - $this->getMockStorage(), - null, - ['permissions' => \OCP\Constants::PERMISSION_ALL], - null - ); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // beforeMethod locks - $view->lockFile($path, ILockingProvider::LOCK_SHARED); - - $result = $file->put($this->getStream('test data')); - - // afterMethod unlocks - $view->unlockFile($path, ILockingProvider::LOCK_SHARED); - - return $result; - } - - /** - * Test putting a single file - */ - public function testPutSingleFile() { - $this->assertNotEmpty($this->doPut('/foo.txt')); - } - - /** - * Test putting a file using chunking - */ - public function testChunkedPut() { - $_SERVER['HTTP_OC_CHUNKED'] = true; - $this->assertNull($this->doPut('/test.txt-chunking-12345-2-0')); - $this->assertNotEmpty($this->doPut('/test.txt-chunking-12345-2-1')); - } - - /** - * Test that putting a file triggers create hooks - */ - public function testPutSingleFileTriggersHooks() { - HookHelper::setUpHooks(); - - $this->assertNotEmpty($this->doPut('/foo.txt')); - - $this->assertCount(4, HookHelper::$hookCalls); - $this->assertHookCall( - HookHelper::$hookCalls[0], - Filesystem::signal_create, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[1], - Filesystem::signal_write, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[2], - Filesystem::signal_post_create, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[3], - Filesystem::signal_post_write, - '/foo.txt' - ); - } - - /** - * Test that putting a file triggers update hooks - */ - public function testPutOverwriteFileTriggersHooks() { - $view = \OC\Files\Filesystem::getView(); - $view->file_put_contents('/foo.txt', 'some content that will be replaced'); - - HookHelper::setUpHooks(); - - $this->assertNotEmpty($this->doPut('/foo.txt')); - - $this->assertCount(4, HookHelper::$hookCalls); - $this->assertHookCall( - HookHelper::$hookCalls[0], - Filesystem::signal_update, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[1], - Filesystem::signal_write, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[2], - Filesystem::signal_post_update, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[3], - Filesystem::signal_post_write, - '/foo.txt' - ); - } - - /** - * Test that putting a file triggers hooks with the correct path - * if the passed view was chrooted (can happen with public webdav - * where the root is the share root) - */ - public function testPutSingleFileTriggersHooksDifferentRoot() { - $view = \OC\Files\Filesystem::getView(); - $view->mkdir('noderoot'); - - HookHelper::setUpHooks(); - - // happens with public webdav where the view root is the share root - $this->assertNotEmpty($this->doPut('/foo.txt', '/' . $this->user . '/files/noderoot')); - - $this->assertCount(4, HookHelper::$hookCalls); - $this->assertHookCall( - HookHelper::$hookCalls[0], - Filesystem::signal_create, - '/noderoot/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[1], - Filesystem::signal_write, - '/noderoot/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[2], - Filesystem::signal_post_create, - '/noderoot/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[3], - Filesystem::signal_post_write, - '/noderoot/foo.txt' - ); - } - - /** - * Test that putting a file with chunks triggers create hooks - */ - public function testPutChunkedFileTriggersHooks() { - HookHelper::setUpHooks(); - - $_SERVER['HTTP_OC_CHUNKED'] = true; - $this->assertNull($this->doPut('/foo.txt-chunking-12345-2-0')); - $this->assertNotEmpty($this->doPut('/foo.txt-chunking-12345-2-1')); - - $this->assertCount(4, HookHelper::$hookCalls); - $this->assertHookCall( - HookHelper::$hookCalls[0], - Filesystem::signal_create, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[1], - Filesystem::signal_write, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[2], - Filesystem::signal_post_create, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[3], - Filesystem::signal_post_write, - '/foo.txt' - ); - } - - /** - * Test that putting a chunked file triggers update hooks - */ - public function testPutOverwriteChunkedFileTriggersHooks() { - $view = \OC\Files\Filesystem::getView(); - $view->file_put_contents('/foo.txt', 'some content that will be replaced'); - - HookHelper::setUpHooks(); - - $_SERVER['HTTP_OC_CHUNKED'] = true; - $this->assertNull($this->doPut('/foo.txt-chunking-12345-2-0')); - $this->assertNotEmpty($this->doPut('/foo.txt-chunking-12345-2-1')); - - $this->assertCount(4, HookHelper::$hookCalls); - $this->assertHookCall( - HookHelper::$hookCalls[0], - Filesystem::signal_update, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[1], - Filesystem::signal_write, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[2], - Filesystem::signal_post_update, - '/foo.txt' - ); - $this->assertHookCall( - HookHelper::$hookCalls[3], - Filesystem::signal_post_write, - '/foo.txt' - ); - } - - public static function cancellingHook($params) { - self::$hookCalls[] = array( - 'signal' => Filesystem::signal_post_create, - 'params' => $params - ); - } - - /** - * Test put file with cancelled hook - */ - public function testPutSingleFileCancelPreHook() { - \OCP\Util::connectHook( - Filesystem::CLASSNAME, - Filesystem::signal_create, - '\Test\HookHelper', - 'cancellingCallback' - ); - - // action - $thrown = false; - try { - $this->doPut('/foo.txt'); - } catch (\Sabre\DAV\Exception $e) { - $thrown = true; - } - - $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles(), 'No stray part files'); - } - - /** - * Test exception when the uploaded size did not match - */ - public function testSimplePutFailsSizeCheck() { - // setup - $view = $this->getMock('\OC\Files\View', - array('rename', 'getRelativePath', 'filesize')); - $view->expects($this->any()) - ->method('rename') - ->withAnyParameters() - ->will($this->returnValue(false)); - $view->expects($this->any()) - ->method('getRelativePath') - ->will($this->returnArgument(0)); - - $view->expects($this->any()) - ->method('filesize') - ->will($this->returnValue(123456)); - - $_SERVER['CONTENT_LENGTH'] = 123456; - $_SERVER['REQUEST_METHOD'] = 'PUT'; - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $thrown = false; - try { - // beforeMethod locks - $file->acquireLock(ILockingProvider::LOCK_SHARED); - - $file->put($this->getStream('test data')); - - // afterMethod unlocks - $file->releaseLock(ILockingProvider::LOCK_SHARED); - } catch (\Sabre\DAV\Exception\BadRequest $e) { - $thrown = true; - } - - $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); - } - - /** - * Test exception during final rename in simple upload mode - */ - public function testSimplePutFailsMoveFromStorage() { - $view = new \OC\Files\View('/' . $this->user . '/files'); - - // simulate situation where the target file is locked - $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE); - - $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $thrown = false; - try { - // beforeMethod locks - $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - - $file->put($this->getStream('test data')); - - // afterMethod unlocks - $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { - $thrown = true; - } - - $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); - } - - /** - * Test exception during final rename in chunk upload mode - */ - public function testChunkedPutFailsFinalRename() { - $view = new \OC\Files\View('/' . $this->user . '/files'); - - // simulate situation where the target file is locked - $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE); - - $_SERVER['HTTP_OC_CHUNKED'] = true; - - $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL - ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - $file->acquireLock(ILockingProvider::LOCK_SHARED); - $this->assertNull($file->put('test data one')); - $file->releaseLock(ILockingProvider::LOCK_SHARED); - - $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL - ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $thrown = false; - try { - $file->acquireLock(ILockingProvider::LOCK_SHARED); - $file->put($this->getStream('test data')); - $file->releaseLock(ILockingProvider::LOCK_SHARED); - } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { - $thrown = true; - } - - $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); - } - - /** - * Test put file with invalid chars - */ - public function testSimplePutInvalidChars() { - // setup - $view = $this->getMock('\OC\Files\View', array('getRelativePath')); - $view->expects($this->any()) - ->method('getRelativePath') - ->will($this->returnArgument(0)); - - $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $thrown = false; - try { - // beforeMethod locks - $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - - $file->put($this->getStream('test data')); - - // afterMethod unlocks - $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - } catch (\OCA\DAV\Connector\Sabre\Exception\InvalidPath $e) { - $thrown = true; - } - - $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); - } - - /** - * Test setting name with setName() with invalid chars - * - * @expectedException \OCA\DAV\Connector\Sabre\Exception\InvalidPath - */ - public function testSetNameInvalidChars() { - // setup - $view = $this->getMock('\OC\Files\View', array('getRelativePath')); - - $view->expects($this->any()) - ->method('getRelativePath') - ->will($this->returnArgument(0)); - - $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - $file->setName('/super*star.txt'); - } - - /** - */ - public function testUploadAbort() { - // setup - $view = $this->getMock('\OC\Files\View', - array('rename', 'getRelativePath', 'filesize')); - $view->expects($this->any()) - ->method('rename') - ->withAnyParameters() - ->will($this->returnValue(false)); - $view->expects($this->any()) - ->method('getRelativePath') - ->will($this->returnArgument(0)); - $view->expects($this->any()) - ->method('filesize') - ->will($this->returnValue(123456)); - - $_SERVER['CONTENT_LENGTH'] = 12345; - $_SERVER['REQUEST_METHOD'] = 'PUT'; - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $thrown = false; - try { - // beforeMethod locks - $view->lockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - - $file->put($this->getStream('test data')); - - // afterMethod unlocks - $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - } catch (\Sabre\DAV\Exception\BadRequest $e) { - $thrown = true; - } - - $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); - } - - /** - * - */ - public function testDeleteWhenAllowed() { - // setup - $view = $this->getMock('\OC\Files\View', - array()); - - $view->expects($this->once()) - ->method('unlink') - ->will($this->returnValue(true)); - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $file->delete(); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteThrowsWhenDeletionNotAllowed() { - // setup - $view = $this->getMock('\OC\Files\View', - array()); - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => 0 - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $file->delete(); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testDeleteThrowsWhenDeletionFailed() { - // setup - $view = $this->getMock('\OC\Files\View', - array()); - - // but fails - $view->expects($this->once()) - ->method('unlink') - ->will($this->returnValue(false)); - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $file->delete(); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\Forbidden - */ - public function testDeleteThrowsWhenDeletionThrows() { - // setup - $view = $this->getMock('\OC\Files\View', - array()); - - // but fails - $view->expects($this->once()) - ->method('unlink') - ->willThrowException(new ForbiddenException('', true)); - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - // action - $file->delete(); - } - - /** - * Asserts hook call - * - * @param array $callData hook call data to check - * @param string $signal signal name - * @param string $hookPath hook path - */ - protected function assertHookCall($callData, $signal, $hookPath) { - $this->assertEquals($signal, $callData['signal']); - $params = $callData['params']; - $this->assertEquals( - $hookPath, - $params[Filesystem::signal_param_path] - ); - } - - /** - * Test whether locks are set before and after the operation - */ - public function testPutLocking() { - $view = new \OC\Files\View('/' . $this->user . '/files/'); - - $path = 'test-locking.txt'; - $info = new \OC\Files\FileInfo( - '/' . $this->user . '/files/' . $path, - $this->getMockStorage(), - null, - ['permissions' => \OCP\Constants::PERMISSION_ALL], - null - ); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - $this->assertFalse( - $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED), - 'File unlocked before put' - ); - $this->assertFalse( - $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE), - 'File unlocked before put' - ); - - $wasLockedPre = false; - $wasLockedPost = false; - $eventHandler = $this->getMockBuilder('\stdclass') - ->setMethods(['writeCallback', 'postWriteCallback']) - ->getMock(); - - // both pre and post hooks might need access to the file, - // so only shared lock is acceptable - $eventHandler->expects($this->once()) - ->method('writeCallback') - ->will($this->returnCallback( - function () use ($view, $path, &$wasLockedPre) { - $wasLockedPre = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED); - $wasLockedPre = $wasLockedPre && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE); - } - )); - $eventHandler->expects($this->once()) - ->method('postWriteCallback') - ->will($this->returnCallback( - function () use ($view, $path, &$wasLockedPost) { - $wasLockedPost = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED); - $wasLockedPost = $wasLockedPost && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE); - } - )); - - \OCP\Util::connectHook( - Filesystem::CLASSNAME, - Filesystem::signal_write, - $eventHandler, - 'writeCallback' - ); - \OCP\Util::connectHook( - Filesystem::CLASSNAME, - Filesystem::signal_post_write, - $eventHandler, - 'postWriteCallback' - ); - - // beforeMethod locks - $view->lockFile($path, ILockingProvider::LOCK_SHARED); - - $this->assertNotEmpty($file->put($this->getStream('test data'))); - - // afterMethod unlocks - $view->unlockFile($path, ILockingProvider::LOCK_SHARED); - - $this->assertTrue($wasLockedPre, 'File was locked during pre-hooks'); - $this->assertTrue($wasLockedPost, 'File was locked during post-hooks'); - - $this->assertFalse( - $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED), - 'File unlocked after put' - ); - $this->assertFalse( - $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE), - 'File unlocked after put' - ); - } - - /** - * Returns part files in the given path - * - * @param \OC\Files\View view which root is the current user's "files" folder - * @param string $path path for which to list part files - * - * @return array list of part files - */ - private function listPartFiles(\OC\Files\View $userView = null, $path = '') { - if ($userView === null) { - $userView = \OC\Files\Filesystem::getView(); - } - $files = []; - list($storage, $internalPath) = $userView->resolvePath($path); - if($storage instanceof Local) { - $realPath = $storage->getSourcePath($internalPath); - $dh = opendir($realPath); - while (($file = readdir($dh)) !== false) { - if (substr($file, strlen($file) - 5, 5) === '.part') { - $files[] = $file; - } - } - closedir($dh); - } - return $files; - } - - /** - * @expectedException \Sabre\DAV\Exception\ServiceUnavailable - */ - public function testGetFopenFails() { - $view = $this->getMock('\OC\Files\View', ['fopen'], array()); - $view->expects($this->atLeastOnce()) - ->method('fopen') - ->will($this->returnValue(false)); - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - $file->get(); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\Forbidden - */ - public function testGetFopenThrows() { - $view = $this->getMock('\OC\Files\View', ['fopen'], array()); - $view->expects($this->atLeastOnce()) - ->method('fopen') - ->willThrowException(new ForbiddenException('', true)); - - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, array( - 'permissions' => \OCP\Constants::PERMISSION_ALL - ), null); - - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); - - $file->get(); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/filesplugin.php b/apps/dav/tests/unit/connector/sabre/filesplugin.php deleted file mode 100644 index fb5d658b39c..00000000000 --- a/apps/dav/tests/unit/connector/sabre/filesplugin.php +++ /dev/null @@ -1,469 +0,0 @@ - - * @author Thomas Müller - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCP\Files\StorageNotAvailableException; -use Sabre\DAV\PropFind; -use Sabre\DAV\PropPatch; -use Test\TestCase; - -/** - * Copyright (c) 2015 Vincent Petry - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -class FilesPlugin extends TestCase { - const GETETAG_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::GETETAG_PROPERTYNAME; - const FILEID_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::FILEID_PROPERTYNAME; - const INTERNAL_FILEID_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::INTERNAL_FILEID_PROPERTYNAME; - const SIZE_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::SIZE_PROPERTYNAME; - const PERMISSIONS_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::PERMISSIONS_PROPERTYNAME; - const LASTMODIFIED_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::LASTMODIFIED_PROPERTYNAME; - const DOWNLOADURL_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::DOWNLOADURL_PROPERTYNAME; - const OWNER_ID_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::OWNER_ID_PROPERTYNAME; - const OWNER_DISPLAY_NAME_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::OWNER_DISPLAY_NAME_PROPERTYNAME; - const DATA_FINGERPRINT_PROPERTYNAME = \OCA\DAV\Connector\Sabre\FilesPlugin::DATA_FINGERPRINT_PROPERTYNAME; - - /** - * @var \Sabre\DAV\Server | \PHPUnit_Framework_MockObject_MockObject - */ - private $server; - - /** - * @var \Sabre\DAV\Tree | \PHPUnit_Framework_MockObject_MockObject - */ - private $tree; - - /** - * @var \OCA\DAV\Connector\Sabre\FilesPlugin - */ - private $plugin; - - /** - * @var \OC\Files\View | \PHPUnit_Framework_MockObject_MockObject - */ - private $view; - - /** - * @var \OCP\IConfig | \PHPUnit_Framework_MockObject_MockObject - */ - private $config; - - public function setUp() { - parent::setUp(); - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') - ->disableOriginalConstructor() - ->getMock(); - $this->view = $this->getMockBuilder('\OC\Files\View') - ->disableOriginalConstructor() - ->getMock(); - $this->config = $this->getMock('\OCP\IConfig'); - $this->config->method('getSystemValue') - ->with($this->equalTo('data-fingerprint'), $this->equalTo('')) - ->willReturn('my_fingerprint'); - - $this->plugin = new \OCA\DAV\Connector\Sabre\FilesPlugin( - $this->tree, - $this->view, - $this->config - ); - $this->plugin->initialize($this->server); - } - - /** - * @param string $class - * @return \PHPUnit_Framework_MockObject_MockObject - */ - private function createTestNode($class) { - $node = $this->getMockBuilder($class) - ->disableOriginalConstructor() - ->getMock(); - - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->returnValue($node)); - - $node->expects($this->any()) - ->method('getFileId') - ->will($this->returnValue('00000123instanceid')); - $node->expects($this->any()) - ->method('getInternalFileId') - ->will($this->returnValue('123')); - $node->expects($this->any()) - ->method('getEtag') - ->will($this->returnValue('"abc"')); - $node->expects($this->any()) - ->method('getDavPermissions') - ->will($this->returnValue('DWCKMSR')); - - return $node; - } - - public function testGetPropertiesForFile() { - /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit_Framework_MockObject_MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); - - $propFind = new PropFind( - '/dummyPath', - array( - self::GETETAG_PROPERTYNAME, - self::FILEID_PROPERTYNAME, - self::INTERNAL_FILEID_PROPERTYNAME, - self::SIZE_PROPERTYNAME, - self::PERMISSIONS_PROPERTYNAME, - self::DOWNLOADURL_PROPERTYNAME, - self::OWNER_ID_PROPERTYNAME, - self::OWNER_DISPLAY_NAME_PROPERTYNAME, - self::DATA_FINGERPRINT_PROPERTYNAME, - ), - 0 - ); - - $user = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $user - ->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('foo')); - $user - ->expects($this->once()) - ->method('getDisplayName') - ->will($this->returnValue('M. Foo')); - - $node->expects($this->once()) - ->method('getDirectDownload') - ->will($this->returnValue(array('url' => 'http://example.com/'))); - $node->expects($this->exactly(2)) - ->method('getOwner') - ->will($this->returnValue($user)); - $node->expects($this->never()) - ->method('getSize'); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - - $this->assertEquals('"abc"', $propFind->get(self::GETETAG_PROPERTYNAME)); - $this->assertEquals('00000123instanceid', $propFind->get(self::FILEID_PROPERTYNAME)); - $this->assertEquals('123', $propFind->get(self::INTERNAL_FILEID_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::SIZE_PROPERTYNAME)); - $this->assertEquals('DWCKMSR', $propFind->get(self::PERMISSIONS_PROPERTYNAME)); - $this->assertEquals('http://example.com/', $propFind->get(self::DOWNLOADURL_PROPERTYNAME)); - $this->assertEquals('foo', $propFind->get(self::OWNER_ID_PROPERTYNAME)); - $this->assertEquals('M. Foo', $propFind->get(self::OWNER_DISPLAY_NAME_PROPERTYNAME)); - $this->assertEquals([self::SIZE_PROPERTYNAME, self::DATA_FINGERPRINT_PROPERTYNAME], $propFind->get404Properties()); - } - - public function testGetPropertiesForFileHome() { - /** @var \OCA\DAV\Files\FilesHome | \PHPUnit_Framework_MockObject_MockObject $node */ - $node = $this->getMockBuilder('\OCA\DAV\Files\FilesHome') - ->disableOriginalConstructor() - ->getMock(); - - $propFind = new PropFind( - '/dummyPath', - array( - self::GETETAG_PROPERTYNAME, - self::FILEID_PROPERTYNAME, - self::INTERNAL_FILEID_PROPERTYNAME, - self::SIZE_PROPERTYNAME, - self::PERMISSIONS_PROPERTYNAME, - self::DOWNLOADURL_PROPERTYNAME, - self::OWNER_ID_PROPERTYNAME, - self::OWNER_DISPLAY_NAME_PROPERTYNAME, - self::DATA_FINGERPRINT_PROPERTYNAME, - ), - 0 - ); - - $user = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $user->expects($this->never())->method('getUID'); - $user->expects($this->never())->method('getDisplayName'); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - - $this->assertEquals(null, $propFind->get(self::GETETAG_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::FILEID_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::INTERNAL_FILEID_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::SIZE_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::PERMISSIONS_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::DOWNLOADURL_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::OWNER_ID_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::OWNER_DISPLAY_NAME_PROPERTYNAME)); - $this->assertEquals(['{DAV:}getetag', - '{http://owncloud.org/ns}id', - '{http://owncloud.org/ns}fileid', - '{http://owncloud.org/ns}size', - '{http://owncloud.org/ns}permissions', - '{http://owncloud.org/ns}downloadURL', - '{http://owncloud.org/ns}owner-id', - '{http://owncloud.org/ns}owner-display-name' - ], $propFind->get404Properties()); - $this->assertEquals('my_fingerprint', $propFind->get(self::DATA_FINGERPRINT_PROPERTYNAME)); - } - - public function testGetPropertiesStorageNotAvailable() { - /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit_Framework_MockObject_MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); - - $propFind = new PropFind( - '/dummyPath', - array( - self::DOWNLOADURL_PROPERTYNAME, - ), - 0 - ); - - $node->expects($this->once()) - ->method('getDirectDownload') - ->will($this->throwException(new StorageNotAvailableException())); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - - $this->assertEquals(null, $propFind->get(self::DOWNLOADURL_PROPERTYNAME)); - } - - public function testGetPublicPermissions() { - $this->plugin = new \OCA\DAV\Connector\Sabre\FilesPlugin( - $this->tree, - $this->view, - $this->config, - true); - $this->plugin->initialize($this->server); - - $propFind = new PropFind( - '/dummyPath', - [ - self::PERMISSIONS_PROPERTYNAME, - ], - 0 - ); - - /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit_Framework_MockObject_MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); - $node->expects($this->any()) - ->method('getDavPermissions') - ->will($this->returnValue('DWCKMSR')); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - - $this->assertEquals('DWCKR', $propFind->get(self::PERMISSIONS_PROPERTYNAME)); - } - - public function testGetPropertiesForDirectory() { - /** @var \OCA\DAV\Connector\Sabre\Directory | \PHPUnit_Framework_MockObject_MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\Directory'); - - $propFind = new PropFind( - '/dummyPath', - array( - self::GETETAG_PROPERTYNAME, - self::FILEID_PROPERTYNAME, - self::SIZE_PROPERTYNAME, - self::PERMISSIONS_PROPERTYNAME, - self::DOWNLOADURL_PROPERTYNAME, - self::DATA_FINGERPRINT_PROPERTYNAME, - ), - 0 - ); - - $node->expects($this->once()) - ->method('getSize') - ->will($this->returnValue(1025)); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - - $this->assertEquals('"abc"', $propFind->get(self::GETETAG_PROPERTYNAME)); - $this->assertEquals('00000123instanceid', $propFind->get(self::FILEID_PROPERTYNAME)); - $this->assertEquals(1025, $propFind->get(self::SIZE_PROPERTYNAME)); - $this->assertEquals('DWCKMSR', $propFind->get(self::PERMISSIONS_PROPERTYNAME)); - $this->assertEquals(null, $propFind->get(self::DOWNLOADURL_PROPERTYNAME)); - $this->assertEquals([self::DOWNLOADURL_PROPERTYNAME, self::DATA_FINGERPRINT_PROPERTYNAME], $propFind->get404Properties()); - } - - public function testGetPropertiesForRootDirectory() { - /** @var \OCA\DAV\Connector\Sabre\Directory | \PHPUnit_Framework_MockObject_MockObject $node */ - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $node->method('getPath')->willReturn('/'); - - $propFind = new PropFind( - '/', - [ - self::DATA_FINGERPRINT_PROPERTYNAME, - ], - 0 - ); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - - $this->assertEquals('my_fingerprint', $propFind->get(self::DATA_FINGERPRINT_PROPERTYNAME)); - } - - public function testUpdateProps() { - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); - - $testDate = 'Fri, 13 Feb 2015 00:01:02 GMT'; - - $node->expects($this->once()) - ->method('touch') - ->with($testDate); - - $node->expects($this->once()) - ->method('setEtag') - ->with('newetag') - ->will($this->returnValue(true)); - - // properties to set - $propPatch = new PropPatch(array( - self::GETETAG_PROPERTYNAME => 'newetag', - self::LASTMODIFIED_PROPERTYNAME => $testDate - )); - - $this->plugin->handleUpdateProperties( - '/dummypath', - $propPatch - ); - - $propPatch->commit(); - - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertEquals(200, $result[self::LASTMODIFIED_PROPERTYNAME]); - $this->assertEquals(200, $result[self::GETETAG_PROPERTYNAME]); - } - - public function testUpdatePropsForbidden() { - $propPatch = new PropPatch(array( - self::OWNER_ID_PROPERTYNAME => 'user2', - self::OWNER_DISPLAY_NAME_PROPERTYNAME => 'User Two', - self::FILEID_PROPERTYNAME => 12345, - self::PERMISSIONS_PROPERTYNAME => 'C', - self::SIZE_PROPERTYNAME => 123, - self::DOWNLOADURL_PROPERTYNAME => 'http://example.com/', - )); - - $this->plugin->handleUpdateProperties( - '/dummypath', - $propPatch - ); - - $propPatch->commit(); - - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertEquals(403, $result[self::OWNER_ID_PROPERTYNAME]); - $this->assertEquals(403, $result[self::OWNER_DISPLAY_NAME_PROPERTYNAME]); - $this->assertEquals(403, $result[self::FILEID_PROPERTYNAME]); - $this->assertEquals(403, $result[self::PERMISSIONS_PROPERTYNAME]); - $this->assertEquals(403, $result[self::SIZE_PROPERTYNAME]); - $this->assertEquals(403, $result[self::DOWNLOADURL_PROPERTYNAME]); - } - - /** - * Testcase from https://github.com/owncloud/core/issues/5251 - * - * |-FolderA - * |-text.txt - * |-test.txt - * - * FolderA is an incoming shared folder and there are no delete permissions. - * Thus moving /FolderA/test.txt to /test.txt should fail already on that check - * - * @expectedException \Sabre\DAV\Exception\Forbidden - * @expectedExceptionMessage FolderA/test.txt cannot be deleted - */ - public function testMoveSrcNotDeletable() { - $fileInfoFolderATestTXT = $this->getMockBuilder('\OCP\Files\FileInfo') - ->disableOriginalConstructor() - ->getMock(); - $fileInfoFolderATestTXT->expects($this->once()) - ->method('isDeletable') - ->willReturn(false); - - $this->view->expects($this->once()) - ->method('getFileInfo') - ->with('FolderA/test.txt') - ->willReturn($fileInfoFolderATestTXT); - - $this->plugin->checkMove('FolderA/test.txt', 'test.txt'); - } - - public function testMoveSrcDeletable() { - $fileInfoFolderATestTXT = $this->getMockBuilder('\OCP\Files\FileInfo') - ->disableOriginalConstructor() - ->getMock(); - $fileInfoFolderATestTXT->expects($this->once()) - ->method('isDeletable') - ->willReturn(true); - - $this->view->expects($this->once()) - ->method('getFileInfo') - ->with('FolderA/test.txt') - ->willReturn($fileInfoFolderATestTXT); - - $this->plugin->checkMove('FolderA/test.txt', 'test.txt'); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotFound - * @expectedExceptionMessage FolderA/test.txt does not exist - */ - public function testMoveSrcNotExist() { - $this->view->expects($this->once()) - ->method('getFileInfo') - ->with('FolderA/test.txt') - ->willReturn(false); - - $this->plugin->checkMove('FolderA/test.txt', 'test.txt'); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/filesreportplugin.php b/apps/dav/tests/unit/connector/sabre/filesreportplugin.php deleted file mode 100644 index ffe1a19ee56..00000000000 --- a/apps/dav/tests/unit/connector/sabre/filesreportplugin.php +++ /dev/null @@ -1,611 +0,0 @@ - - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCA\DAV\Connector\Sabre\FilesReportPlugin as FilesReportPluginImplementation; -use Sabre\DAV\Exception\NotFound; -use OCP\SystemTag\ISystemTagObjectMapper; -use OC\Files\View; -use OCP\Files\Folder; -use OCP\IGroupManager; -use OCP\SystemTag\ISystemTagManager; - -class FilesReportPlugin extends \Test\TestCase { - /** @var \Sabre\DAV\Server|\PHPUnit_Framework_MockObject_MockObject */ - private $server; - - /** @var \Sabre\DAV\Tree|\PHPUnit_Framework_MockObject_MockObject */ - private $tree; - - /** @var ISystemTagObjectMapper|\PHPUnit_Framework_MockObject_MockObject */ - private $tagMapper; - - /** @var ISystemTagManager|\PHPUnit_Framework_MockObject_MockObject */ - private $tagManager; - - /** @var \OCP\IUserSession */ - private $userSession; - - /** @var FilesReportPluginImplementation */ - private $plugin; - - /** @var View|\PHPUnit_Framework_MockObject_MockObject **/ - private $view; - - /** @var IGroupManager|\PHPUnit_Framework_MockObject_MockObject **/ - private $groupManager; - - /** @var Folder|\PHPUnit_Framework_MockObject_MockObject **/ - private $userFolder; - - public function setUp() { - parent::setUp(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') - ->disableOriginalConstructor() - ->getMock(); - - $this->view = $this->getMockBuilder('\OC\Files\View') - ->disableOriginalConstructor() - ->getMock(); - - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') - ->setConstructorArgs([$this->tree]) - ->setMethods(['getRequestUri']) - ->getMock(); - - $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') - ->disableOriginalConstructor() - ->getMock(); - - $this->userFolder = $this->getMockBuilder('\OCP\Files\Folder') - ->disableOriginalConstructor() - ->getMock(); - - $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); - $this->tagMapper = $this->getMock('\OCP\SystemTag\ISystemTagObjectMapper'); - $this->userSession = $this->getMock('\OCP\IUserSession'); - - $user = $this->getMock('\OCP\IUser'); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('testuser')); - $this->userSession->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->plugin = new FilesReportPluginImplementation( - $this->tree, - $this->view, - $this->tagManager, - $this->tagMapper, - $this->userSession, - $this->groupManager, - $this->userFolder - ); - } - - /** - * @expectedException \Sabre\DAV\Exception\ReportNotSupported - */ - public function testOnReportInvalidNode() { - $path = 'totally/unrelated/13'; - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($this->getMock('\Sabre\DAV\INode'))); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->onReport(FilesReportPluginImplementation::REPORT_NAME, [], '/' . $path); - } - - /** - * @expectedException \Sabre\DAV\Exception\ReportNotSupported - */ - public function testOnReportInvalidReportName() { - $path = 'test'; - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($this->getMock('\Sabre\DAV\INode'))); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->plugin->initialize($this->server); - - $this->plugin->onReport('{whoever}whatever', [], '/' . $path); - } - - public function testOnReport() { - $path = 'test'; - - $parameters = [ - [ - 'name' => '{DAV:}prop', - 'value' => [ - ['name' => '{DAV:}getcontentlength', 'value' => ''], - ['name' => '{http://owncloud.org/ns}size', 'value' => ''], - ], - ], - [ - 'name' => '{http://owncloud.org/ns}filter-rules', - 'value' => [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], - ], - ], - ]; - - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(true)); - - $this->tagMapper->expects($this->at(0)) - ->method('getObjectIdsForTags') - ->with('123', 'files') - ->will($this->returnValue(['111', '222'])); - $this->tagMapper->expects($this->at(1)) - ->method('getObjectIdsForTags') - ->with('456', 'files') - ->will($this->returnValue(['111', '222', '333'])); - - $reportTargetNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Type', 'application/xml; charset=utf-8'); - - $response->expects($this->once()) - ->method('setStatus') - ->with(207); - - $response->expects($this->once()) - ->method('setBody'); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/' . $path) - ->will($this->returnValue($reportTargetNode)); - - $filesNode1 = $this->getMockBuilder('\OCP\Files\Folder') - ->disableOriginalConstructor() - ->getMock(); - $filesNode2 = $this->getMockBuilder('\OCP\Files\File') - ->disableOriginalConstructor() - ->getMock(); - - $this->userFolder->expects($this->at(0)) - ->method('getById') - ->with('111') - ->will($this->returnValue([$filesNode1])); - $this->userFolder->expects($this->at(1)) - ->method('getById') - ->with('222') - ->will($this->returnValue([$filesNode2])); - - $this->server->expects($this->any()) - ->method('getRequestUri') - ->will($this->returnValue($path)); - $this->server->httpResponse = $response; - $this->plugin->initialize($this->server); - - $this->plugin->onReport(FilesReportPluginImplementation::REPORT_NAME, $parameters, '/' . $path); - } - - public function testFindNodesByFileIdsRoot() { - $filesNode1 = $this->getMockBuilder('\OCP\Files\Folder') - ->disableOriginalConstructor() - ->getMock(); - $filesNode1->expects($this->once()) - ->method('getName') - ->will($this->returnValue('first node')); - - $filesNode2 = $this->getMockBuilder('\OCP\Files\File') - ->disableOriginalConstructor() - ->getMock(); - $filesNode2->expects($this->once()) - ->method('getName') - ->will($this->returnValue('second node')); - - $reportTargetNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $reportTargetNode->expects($this->any()) - ->method('getPath') - ->will($this->returnValue('/')); - - $this->userFolder->expects($this->at(0)) - ->method('getById') - ->with('111') - ->will($this->returnValue([$filesNode1])); - $this->userFolder->expects($this->at(1)) - ->method('getById') - ->with('222') - ->will($this->returnValue([$filesNode2])); - - /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit_Framework_MockObject_MockObject $reportTargetNode */ - $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); - - $this->assertCount(2, $result); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\Directory', $result[0]); - $this->assertEquals('first node', $result[0]->getName()); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\File', $result[1]); - $this->assertEquals('second node', $result[1]->getName()); - } - - public function testFindNodesByFileIdsSubDir() { - $filesNode1 = $this->getMockBuilder('\OCP\Files\Folder') - ->disableOriginalConstructor() - ->getMock(); - $filesNode1->expects($this->once()) - ->method('getName') - ->will($this->returnValue('first node')); - - $filesNode2 = $this->getMockBuilder('\OCP\Files\File') - ->disableOriginalConstructor() - ->getMock(); - $filesNode2->expects($this->once()) - ->method('getName') - ->will($this->returnValue('second node')); - - $reportTargetNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $reportTargetNode->expects($this->any()) - ->method('getPath') - ->will($this->returnValue('/sub1/sub2')); - - - $subNode = $this->getMockBuilder('\OCP\Files\Folder') - ->disableOriginalConstructor() - ->getMock(); - - $this->userFolder->expects($this->at(0)) - ->method('get') - ->with('/sub1/sub2') - ->will($this->returnValue($subNode)); - - $subNode->expects($this->at(0)) - ->method('getById') - ->with('111') - ->will($this->returnValue([$filesNode1])); - $subNode->expects($this->at(1)) - ->method('getById') - ->with('222') - ->will($this->returnValue([$filesNode2])); - - /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit_Framework_MockObject_MockObject $reportTargetNode */ - $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); - - $this->assertCount(2, $result); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\Directory', $result[0]); - $this->assertEquals('first node', $result[0]->getName()); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\File', $result[1]); - $this->assertEquals('second node', $result[1]->getName()); - } - - public function testPrepareResponses() { - $requestedProps = ['{DAV:}getcontentlength', '{http://owncloud.org/ns}fileid', '{DAV:}resourcetype']; - - $node1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $node2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') - ->disableOriginalConstructor() - ->getMock(); - - $node1->expects($this->once()) - ->method('getInternalFileId') - ->will($this->returnValue('111')); - $node2->expects($this->once()) - ->method('getInternalFileId') - ->will($this->returnValue('222')); - $node2->expects($this->once()) - ->method('getSize') - ->will($this->returnValue(1024)); - - $config = $this->getMock('\OCP\IConfig'); - - $this->server->addPlugin( - new \OCA\DAV\Connector\Sabre\FilesPlugin( - $this->tree, - $this->view, - $config - ) - ); - $this->plugin->initialize($this->server); - $responses = $this->plugin->prepareResponses($requestedProps, [$node1, $node2]); - - $this->assertCount(2, $responses); - - $this->assertEquals(200, $responses[0]->getHttpStatus()); - $this->assertEquals(200, $responses[1]->getHttpStatus()); - - $props1 = $responses[0]->getResponseProperties(); - $this->assertEquals('111', $props1[200]['{http://owncloud.org/ns}fileid']); - $this->assertNull($props1[404]['{DAV:}getcontentlength']); - $this->assertInstanceOf('\Sabre\DAV\Xml\Property\ResourceType', $props1[200]['{DAV:}resourcetype']); - $resourceType1 = $props1[200]['{DAV:}resourcetype']->getValue(); - $this->assertEquals('{DAV:}collection', $resourceType1[0]); - - $props2 = $responses[1]->getResponseProperties(); - $this->assertEquals('1024', $props2[200]['{DAV:}getcontentlength']); - $this->assertEquals('222', $props2[200]['{http://owncloud.org/ns}fileid']); - $this->assertInstanceOf('\Sabre\DAV\Xml\Property\ResourceType', $props2[200]['{DAV:}resourcetype']); - $this->assertCount(0, $props2[200]['{DAV:}resourcetype']->getValue()); - } - - public function testProcessFilterRulesSingle() { - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(true)); - - $this->tagMapper->expects($this->exactly(1)) - ->method('getObjectIdsForTags') - ->withConsecutive( - ['123', 'files'] - ) - ->willReturnMap([ - ['123', 'files', 0, '', ['111', '222']], - ]); - - $rules = [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ]; - - $this->assertEquals(['111', '222'], $this->invokePrivate($this->plugin, 'processFilterRules', [$rules])); - } - - public function testProcessFilterRulesAndCondition() { - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(true)); - - $this->tagMapper->expects($this->exactly(2)) - ->method('getObjectIdsForTags') - ->withConsecutive( - ['123', 'files'], - ['456', 'files'] - ) - ->willReturnMap([ - ['123', 'files', 0, '', ['111', '222']], - ['456', 'files', 0, '', ['222', '333']], - ]); - - $rules = [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], - ]; - - $this->assertEquals(['222'], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); - } - - public function testProcessFilterRulesAndConditionWithOneEmptyResult() { - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(true)); - - $this->tagMapper->expects($this->exactly(2)) - ->method('getObjectIdsForTags') - ->withConsecutive( - ['123', 'files'], - ['456', 'files'] - ) - ->willReturnMap([ - ['123', 'files', 0, '', ['111', '222']], - ['456', 'files', 0, '', []], - ]); - - $rules = [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], - ]; - - $this->assertEquals([], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); - } - - public function testProcessFilterRulesAndConditionWithFirstEmptyResult() { - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(true)); - - $this->tagMapper->expects($this->exactly(1)) - ->method('getObjectIdsForTags') - ->withConsecutive( - ['123', 'files'], - ['456', 'files'] - ) - ->willReturnMap([ - ['123', 'files', 0, '', []], - ['456', 'files', 0, '', ['111', '222']], - ]); - - $rules = [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], - ]; - - $this->assertEquals([], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); - } - - public function testProcessFilterRulesAndConditionWithEmptyMidResult() { - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(true)); - - $this->tagMapper->expects($this->exactly(2)) - ->method('getObjectIdsForTags') - ->withConsecutive( - ['123', 'files'], - ['456', 'files'], - ['789', 'files'] - ) - ->willReturnMap([ - ['123', 'files', 0, '', ['111', '222']], - ['456', 'files', 0, '', ['333']], - ['789', 'files', 0, '', ['111', '222']], - ]); - - $rules = [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '789'], - ]; - - $this->assertEquals([], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); - } - - public function testProcessFilterRulesInvisibleTagAsAdmin() { - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(true)); - - $tag1 = $this->getMock('\OCP\SystemTag\ISystemTag'); - $tag1->expects($this->any()) - ->method('getId') - ->will($this->returnValue('123')); - $tag1->expects($this->any()) - ->method('isUserVisible') - ->will($this->returnValue(true)); - - $tag2 = $this->getMock('\OCP\SystemTag\ISystemTag'); - $tag2->expects($this->any()) - ->method('getId') - ->will($this->returnValue('123')); - $tag2->expects($this->any()) - ->method('isUserVisible') - ->will($this->returnValue(false)); - - // no need to fetch tags to check permissions - $this->tagManager->expects($this->never()) - ->method('getTagsByIds'); - - $this->tagMapper->expects($this->at(0)) - ->method('getObjectIdsForTags') - ->with('123') - ->will($this->returnValue(['111', '222'])); - $this->tagMapper->expects($this->at(1)) - ->method('getObjectIdsForTags') - ->with('456') - ->will($this->returnValue(['222', '333'])); - - $rules = [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], - ]; - - $this->assertEquals(['222'], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); - } - - /** - * @expectedException \OCP\SystemTag\TagNotFoundException - */ - public function testProcessFilterRulesInvisibleTagAsUser() { - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(false)); - - $tag1 = $this->getMock('\OCP\SystemTag\ISystemTag'); - $tag1->expects($this->any()) - ->method('getId') - ->will($this->returnValue('123')); - $tag1->expects($this->any()) - ->method('isUserVisible') - ->will($this->returnValue(true)); - - $tag2 = $this->getMock('\OCP\SystemTag\ISystemTag'); - $tag2->expects($this->any()) - ->method('getId') - ->will($this->returnValue('123')); - $tag2->expects($this->any()) - ->method('isUserVisible') - ->will($this->returnValue(false)); // invisible - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['123', '456']) - ->will($this->returnValue([$tag1, $tag2])); - - $rules = [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], - ]; - - $this->invokePrivate($this->plugin, 'processFilterRules', [$rules]); - } - - public function testProcessFilterRulesVisibleTagAsUser() { - $this->groupManager->expects($this->any()) - ->method('isAdmin') - ->will($this->returnValue(false)); - - $tag1 = $this->getMock('\OCP\SystemTag\ISystemTag'); - $tag1->expects($this->any()) - ->method('getId') - ->will($this->returnValue('123')); - $tag1->expects($this->any()) - ->method('isUserVisible') - ->will($this->returnValue(true)); - - $tag2 = $this->getMock('\OCP\SystemTag\ISystemTag'); - $tag2->expects($this->any()) - ->method('getId') - ->will($this->returnValue('123')); - $tag2->expects($this->any()) - ->method('isUserVisible') - ->will($this->returnValue(true)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['123', '456']) - ->will($this->returnValue([$tag1, $tag2])); - - $this->tagMapper->expects($this->at(0)) - ->method('getObjectIdsForTags') - ->with('123') - ->will($this->returnValue(['111', '222'])); - $this->tagMapper->expects($this->at(1)) - ->method('getObjectIdsForTags') - ->with('456') - ->will($this->returnValue(['222', '333'])); - - $rules = [ - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], - ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '456'], - ]; - - $this->assertEquals(['222'], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/node.php b/apps/dav/tests/unit/connector/sabre/node.php deleted file mode 100644 index f70d1ee3faf..00000000000 --- a/apps/dav/tests/unit/connector/sabre/node.php +++ /dev/null @@ -1,149 +0,0 @@ - - * @author Robin Appelman - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -/** - * Class Node - * - * @group DB - * @package OCA\DAV\Tests\Unit\Connector\Sabre - */ -class Node extends \Test\TestCase { - public function davPermissionsProvider() { - return array( - array(\OCP\Constants::PERMISSION_ALL, 'file', false, false, 'RDNVW'), - array(\OCP\Constants::PERMISSION_ALL, 'dir', false, false, 'RDNVCK'), - array(\OCP\Constants::PERMISSION_ALL, 'file', true, false, 'SRDNVW'), - array(\OCP\Constants::PERMISSION_ALL, 'file', true, true, 'SRMDNVW'), - array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE, 'file', true, false, 'SDNVW'), - array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_UPDATE, 'file', false, false, 'RD'), - array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_DELETE, 'file', false, false, 'RNVW'), - array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE, 'file', false, false, 'RDNVW'), - array(\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE, 'dir', false, false, 'RDNV'), - ); - } - - /** - * @dataProvider davPermissionsProvider - */ - public function testDavPermissions($permissions, $type, $shared, $mounted, $expected) { - $info = $this->getMockBuilder('\OC\Files\FileInfo') - ->disableOriginalConstructor() - ->setMethods(array('getPermissions', 'isShared', 'isMounted', 'getType')) - ->getMock(); - $info->expects($this->any()) - ->method('getPermissions') - ->will($this->returnValue($permissions)); - $info->expects($this->any()) - ->method('isShared') - ->will($this->returnValue($shared)); - $info->expects($this->any()) - ->method('isMounted') - ->will($this->returnValue($mounted)); - $info->expects($this->any()) - ->method('getType') - ->will($this->returnValue($type)); - $view = $this->getMock('\OC\Files\View'); - - $node = new \OCA\DAV\Connector\Sabre\File($view, $info); - $this->assertEquals($expected, $node->getDavPermissions()); - } - - public function sharePermissionsProvider() { - return [ - [\OCP\Files\FileInfo::TYPE_FILE, null, 1, 1], - [\OCP\Files\FileInfo::TYPE_FILE, null, 3, 3], - [\OCP\Files\FileInfo::TYPE_FILE, null, 5, 1], - [\OCP\Files\FileInfo::TYPE_FILE, null, 7, 3], - [\OCP\Files\FileInfo::TYPE_FILE, null, 9, 1], - [\OCP\Files\FileInfo::TYPE_FILE, null, 11, 3], - [\OCP\Files\FileInfo::TYPE_FILE, null, 13, 1], - [\OCP\Files\FileInfo::TYPE_FILE, null, 15, 3], - [\OCP\Files\FileInfo::TYPE_FILE, null, 17, 17], - [\OCP\Files\FileInfo::TYPE_FILE, null, 19, 19], - [\OCP\Files\FileInfo::TYPE_FILE, null, 21, 17], - [\OCP\Files\FileInfo::TYPE_FILE, null, 23, 19], - [\OCP\Files\FileInfo::TYPE_FILE, null, 25, 17], - [\OCP\Files\FileInfo::TYPE_FILE, null, 27, 19], - [\OCP\Files\FileInfo::TYPE_FILE, null, 29, 17], - [\OCP\Files\FileInfo::TYPE_FILE, null, 30, 18], - [\OCP\Files\FileInfo::TYPE_FILE, null, 31, 19], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 1, 1], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 3, 3], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 5, 5], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 7, 7], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 9, 9], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 11, 11], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 13, 13], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 15, 15], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 17, 17], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 19, 19], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 21, 21], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 23, 23], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 25, 25], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 27, 27], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 29, 29], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 30, 30], - [\OCP\Files\FileInfo::TYPE_FOLDER, null, 31, 31], - [\OCP\Files\FileInfo::TYPE_FOLDER, 'shareToken', 7, 7], - ]; - } - - /** - * @dataProvider sharePermissionsProvider - */ - public function testSharePermissions($type, $user, $permissions, $expected) { - $storage = $this->getMock('\OCP\Files\Storage'); - $storage->method('getPermissions')->willReturn($permissions); - - $mountpoint = $this->getMock('\OCP\Files\Mount\IMountPoint'); - $mountpoint->method('getMountPoint')->willReturn('myPath'); - $shareManager = $this->getMockBuilder('OCP\Share\IManager')->disableOriginalConstructor()->getMock(); - $share = $this->getMockBuilder('OCP\Share\IShare')->disableOriginalConstructor()->getMock(); - - if ($user === null) { - $shareManager->expects($this->never())->method('getShareByToken'); - $share->expects($this->never())->method('getPermissions'); - } else { - $shareManager->expects($this->once())->method('getShareByToken')->with($user) - ->willReturn($share); - $share->expects($this->once())->method('getPermissions')->willReturn($permissions); - } - - $info = $this->getMockBuilder('\OC\Files\FileInfo') - ->disableOriginalConstructor() - ->setMethods(['getStorage', 'getType', 'getMountPoint']) - ->getMock(); - - $info->method('getStorage')->willReturn($storage); - $info->method('getType')->willReturn($type); - $info->method('getMountPoint')->willReturn($mountpoint); - - $view = $this->getMock('\OC\Files\View'); - - $node = new \OCA\DAV\Connector\Sabre\File($view, $info); - $this->invokePrivate($node, 'shareManager', [$shareManager]); - $this->assertEquals($expected, $node->getSharePermissions($user)); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/objecttree.php b/apps/dav/tests/unit/connector/sabre/objecttree.php deleted file mode 100644 index e5e858ef17b..00000000000 --- a/apps/dav/tests/unit/connector/sabre/objecttree.php +++ /dev/null @@ -1,355 +0,0 @@ - - * @author Morris Jobke - * @author Robin Appelman - * @author Thomas Müller - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - - -use OC\Files\FileInfo; -use OC\Files\Storage\Temporary; - -class TestDoubleFileView extends \OC\Files\View { - - public function __construct($updatables, $deletables, $canRename = true) { - $this->updatables = $updatables; - $this->deletables = $deletables; - $this->canRename = $canRename; - } - - public function isUpdatable($path) { - return $this->updatables[$path]; - } - - public function isCreatable($path) { - return $this->updatables[$path]; - } - - public function isDeletable($path) { - return $this->deletables[$path]; - } - - public function rename($path1, $path2) { - return $this->canRename; - } - - public function getRelativePath($path) { - return $path; - } -} - -/** - * Class ObjectTree - * - * @group DB - * - * @package OCA\DAV\Tests\Unit\Connector\Sabre - */ -class ObjectTree extends \Test\TestCase { - - /** - * @dataProvider moveFailedProvider - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testMoveFailed($source, $destination, $updatables, $deletables) { - $this->moveTest($source, $destination, $updatables, $deletables); - } - - /** - * @dataProvider moveSuccessProvider - */ - public function testMoveSuccess($source, $destination, $updatables, $deletables) { - $this->moveTest($source, $destination, $updatables, $deletables); - $this->assertTrue(true); - } - - /** - * @dataProvider moveFailedInvalidCharsProvider - * @expectedException \OCA\DAV\Connector\Sabre\Exception\InvalidPath - */ - public function testMoveFailedInvalidChars($source, $destination, $updatables, $deletables) { - $this->moveTest($source, $destination, $updatables, $deletables); - } - - function moveFailedInvalidCharsProvider() { - return array( - array('a/b', 'a/*', array('a' => true, 'a/b' => true, 'a/c*' => false), array()), - ); - } - - function moveFailedProvider() { - return array( - array('a/b', 'a/c', array('a' => false, 'a/b' => false, 'a/c' => false), array()), - array('a/b', 'b/b', array('a' => false, 'a/b' => false, 'b' => false, 'b/b' => false), array()), - array('a/b', 'b/b', array('a' => false, 'a/b' => true, 'b' => false, 'b/b' => false), array()), - array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => false, 'b/b' => false), array()), - array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false), array('a/b' => false)), - array('a/b', 'a/c', array('a' => false, 'a/b' => true, 'a/c' => false), array()), - ); - } - - function moveSuccessProvider() { - return array( - array('a/b', 'b/b', array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false), array('a/b' => true)), - // older files with special chars can still be renamed to valid names - array('a/b*', 'b/b', array('a' => true, 'a/b*' => true, 'b' => true, 'b/b' => false), array('a/b*' => true)), - ); - } - - /** - * @param $source - * @param $destination - * @param $updatables - */ - private function moveTest($source, $destination, $updatables, $deletables) { - $view = new TestDoubleFileView($updatables, $deletables); - - $info = new FileInfo('', null, null, array(), null); - - $rootDir = new \OCA\DAV\Connector\Sabre\Directory($view, $info); - $objectTree = $this->getMock('\OCA\DAV\Connector\Sabre\ObjectTree', - array('nodeExists', 'getNodeForPath'), - array($rootDir, $view)); - - $objectTree->expects($this->once()) - ->method('getNodeForPath') - ->with($this->identicalTo($source)) - ->will($this->returnValue(false)); - - /** @var $objectTree \OCA\DAV\Connector\Sabre\ObjectTree */ - $mountManager = \OC\Files\Filesystem::getMountManager(); - $objectTree->init($rootDir, $view, $mountManager); - $objectTree->move($source, $destination); - } - - /** - * @dataProvider nodeForPathProvider - */ - public function testGetNodeForPath( - $inputFileName, - $fileInfoQueryPath, - $outputFileName, - $type, - $enableChunkingHeader - ) { - - if ($enableChunkingHeader) { - $_SERVER['HTTP_OC_CHUNKED'] = true; - } - - $rootNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $mountManager = $this->getMock('\OC\Files\Mount\Manager'); - $view = $this->getMock('\OC\Files\View'); - $fileInfo = $this->getMock('\OCP\Files\FileInfo'); - $fileInfo->expects($this->once()) - ->method('getType') - ->will($this->returnValue($type)); - $fileInfo->expects($this->once()) - ->method('getName') - ->will($this->returnValue($outputFileName)); - - $view->expects($this->once()) - ->method('getFileInfo') - ->with($fileInfoQueryPath) - ->will($this->returnValue($fileInfo)); - - $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); - $tree->init($rootNode, $view, $mountManager); - - $node = $tree->getNodeForPath($inputFileName); - - $this->assertNotNull($node); - $this->assertEquals($outputFileName, $node->getName()); - - if ($type === 'file') { - $this->assertTrue($node instanceof \OCA\DAV\Connector\Sabre\File); - } else { - $this->assertTrue($node instanceof \OCA\DAV\Connector\Sabre\Directory); - } - - unset($_SERVER['HTTP_OC_CHUNKED']); - } - - function nodeForPathProvider() { - return array( - // regular file - array( - 'regularfile.txt', - 'regularfile.txt', - 'regularfile.txt', - 'file', - false - ), - // regular directory - array( - 'regulardir', - 'regulardir', - 'regulardir', - 'dir', - false - ), - // regular file with chunking - array( - 'regularfile.txt', - 'regularfile.txt', - 'regularfile.txt', - 'file', - true - ), - // regular directory with chunking - array( - 'regulardir', - 'regulardir', - 'regulardir', - 'dir', - true - ), - // file with chunky file name - array( - 'regularfile.txt-chunking-123566789-10-1', - 'regularfile.txt', - 'regularfile.txt', - 'file', - true - ), - // regular file in subdir - array( - 'subdir/regularfile.txt', - 'subdir/regularfile.txt', - 'regularfile.txt', - 'file', - false - ), - // regular directory in subdir - array( - 'subdir/regulardir', - 'subdir/regulardir', - 'regulardir', - 'dir', - false - ), - // file with chunky file name in subdir - array( - 'subdir/regularfile.txt-chunking-123566789-10-1', - 'subdir/regularfile.txt', - 'regularfile.txt', - 'file', - true - ), - ); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\InvalidPath - */ - public function testGetNodeForPathInvalidPath() { - $path = '/foo\bar'; - - - $storage = new Temporary([]); - - $view = $this->getMock('\OC\Files\View', ['resolvePath']); - $view->expects($this->once()) - ->method('resolvePath') - ->will($this->returnCallback(function($path) use ($storage){ - return [$storage, ltrim($path, '/')]; - })); - - $rootNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $mountManager = $this->getMock('\OC\Files\Mount\Manager'); - - $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); - $tree->init($rootNode, $view, $mountManager); - - $tree->getNodeForPath($path); - } - - public function testGetNodeForPathRoot() { - $path = '/'; - - - $storage = new Temporary([]); - - $view = $this->getMock('\OC\Files\View', ['resolvePath']); - $view->expects($this->any()) - ->method('resolvePath') - ->will($this->returnCallback(function ($path) use ($storage) { - return [$storage, ltrim($path, '/')]; - })); - - $rootNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $mountManager = $this->getMock('\OC\Files\Mount\Manager'); - - $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); - $tree->init($rootNode, $view, $mountManager); - - $this->assertInstanceOf('\Sabre\DAV\INode', $tree->getNodeForPath($path)); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - * @expectedExceptionMessage Could not copy directory nameOfSourceNode, target exists - */ - public function testFailingMove() { - $source = 'a/b'; - $destination = 'b/b'; - $updatables = array('a' => true, 'a/b' => true, 'b' => true, 'b/b' => false); - $deletables = array('a/b' => true); - - $view = new TestDoubleFileView($updatables, $deletables); - - $info = new FileInfo('', null, null, array(), null); - - $rootDir = new \OCA\DAV\Connector\Sabre\Directory($view, $info); - $objectTree = $this->getMock('\OCA\DAV\Connector\Sabre\ObjectTree', - array('nodeExists', 'getNodeForPath'), - array($rootDir, $view)); - - $sourceNode = $this->getMockBuilder('\Sabre\DAV\ICollection') - ->disableOriginalConstructor() - ->getMock(); - $sourceNode->expects($this->once()) - ->method('getName') - ->will($this->returnValue('nameOfSourceNode')); - - $objectTree->expects($this->once()) - ->method('nodeExists') - ->with($this->identicalTo($destination)) - ->will($this->returnValue(true)); - $objectTree->expects($this->once()) - ->method('getNodeForPath') - ->with($this->identicalTo($source)) - ->will($this->returnValue($sourceNode)); - - /** @var $objectTree \OCA\DAV\Connector\Sabre\ObjectTree */ - $mountManager = \OC\Files\Filesystem::getMountManager(); - $objectTree->init($rootDir, $view, $mountManager); - $objectTree->move($source, $destination); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/principal.php b/apps/dav/tests/unit/connector/sabre/principal.php deleted file mode 100644 index 75076e9618b..00000000000 --- a/apps/dav/tests/unit/connector/sabre/principal.php +++ /dev/null @@ -1,273 +0,0 @@ - - * @author Thomas Müller - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -use OCP\IGroupManager; -use \Sabre\DAV\PropPatch; -use OCP\IUserManager; -use Test\TestCase; - -class Principal extends TestCase { - /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */ - private $userManager; - /** @var \OCA\DAV\Connector\Sabre\Principal */ - private $connector; - /** @var IGroupManager | \PHPUnit_Framework_MockObject_MockObject */ - private $groupManager; - - public function setUp() { - $this->userManager = $this->getMockBuilder('\OCP\IUserManager') - ->disableOriginalConstructor()->getMock(); - $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') - ->disableOriginalConstructor()->getMock(); - - $this->connector = new \OCA\DAV\Connector\Sabre\Principal( - $this->userManager, - $this->groupManager); - parent::setUp(); - } - - public function testGetPrincipalsByPrefixWithoutPrefix() { - $response = $this->connector->getPrincipalsByPrefix(''); - $this->assertSame([], $response); - } - - public function testGetPrincipalsByPrefixWithUsers() { - $fooUser = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $fooUser - ->expects($this->exactly(1)) - ->method('getUID') - ->will($this->returnValue('foo')); - $fooUser - ->expects($this->exactly(1)) - ->method('getDisplayName') - ->will($this->returnValue('Dr. Foo-Bar')); - $fooUser - ->expects($this->exactly(1)) - ->method('getEMailAddress') - ->will($this->returnValue('')); - $barUser = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $barUser - ->expects($this->exactly(1)) - ->method('getUID') - ->will($this->returnValue('bar')); - $barUser - ->expects($this->exactly(1)) - ->method('getEMailAddress') - ->will($this->returnValue('bar@owncloud.org')); - $this->userManager - ->expects($this->once()) - ->method('search') - ->with('') - ->will($this->returnValue([$fooUser, $barUser])); - - $expectedResponse = [ - 0 => [ - 'uri' => 'principals/users/foo', - '{DAV:}displayname' => 'Dr. Foo-Bar' - ], - 1 => [ - 'uri' => 'principals/users/bar', - '{DAV:}displayname' => 'bar', - '{http://sabredav.org/ns}email-address' => 'bar@owncloud.org' - ] - ]; - $response = $this->connector->getPrincipalsByPrefix('principals/users'); - $this->assertSame($expectedResponse, $response); - } - - public function testGetPrincipalsByPrefixEmpty() { - $this->userManager - ->expects($this->once()) - ->method('search') - ->with('') - ->will($this->returnValue([])); - - $response = $this->connector->getPrincipalsByPrefix('principals/users'); - $this->assertSame([], $response); - } - - public function testGetPrincipalsByPathWithoutMail() { - $fooUser = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $fooUser - ->expects($this->exactly(1)) - ->method('getUID') - ->will($this->returnValue('foo')); - $this->userManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue($fooUser)); - - $expectedResponse = [ - 'uri' => 'principals/users/foo', - '{DAV:}displayname' => 'foo' - ]; - $response = $this->connector->getPrincipalByPath('principals/users/foo'); - $this->assertSame($expectedResponse, $response); - } - - public function testGetPrincipalsByPathWithMail() { - $fooUser = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $fooUser - ->expects($this->exactly(1)) - ->method('getEMailAddress') - ->will($this->returnValue('foo@owncloud.org')); - $fooUser - ->expects($this->exactly(1)) - ->method('getUID') - ->will($this->returnValue('foo')); - $this->userManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue($fooUser)); - - $expectedResponse = [ - 'uri' => 'principals/users/foo', - '{DAV:}displayname' => 'foo', - '{http://sabredav.org/ns}email-address' => 'foo@owncloud.org' - ]; - $response = $this->connector->getPrincipalByPath('principals/users/foo'); - $this->assertSame($expectedResponse, $response); - } - - public function testGetPrincipalsByPathEmpty() { - $this->userManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue(null)); - - $response = $this->connector->getPrincipalByPath('principals/users/foo'); - $this->assertSame(null, $response); - } - - public function testGetGroupMemberSet() { - $fooUser = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $fooUser - ->expects($this->exactly(1)) - ->method('getUID') - ->will($this->returnValue('foo')); - $this->userManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue($fooUser)); - - $response = $this->connector->getGroupMemberSet('principals/users/foo'); - $this->assertSame(['principals/users/foo'], $response); - } - - /** - * @expectedException \Sabre\DAV\Exception - * @expectedExceptionMessage Principal not found - */ - public function testGetGroupMemberSetEmpty() { - $this->userManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue(null)); - - $this->connector->getGroupMemberSet('principals/users/foo'); - } - - public function testGetGroupMembership() { - $fooUser = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $group = $this->getMockBuilder('\OCP\IGroup') - ->disableOriginalConstructor()->getMock(); - $group->expects($this->once()) - ->method('getGID') - ->willReturn('group1'); - $this->userManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->willReturn($fooUser); - $this->groupManager - ->expects($this->once()) - ->method('getUserGroups') - ->willReturn([ - $group - ]); - - $expectedResponse = [ - 'principals/groups/group1' - ]; - $response = $this->connector->getGroupMembership('principals/users/foo'); - $this->assertSame($expectedResponse, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception - * @expectedExceptionMessage Principal not found - */ - public function testGetGroupMembershipEmpty() { - $this->userManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue(null)); - - $this->connector->getGroupMembership('principals/users/foo'); - } - - /** - * @expectedException \Sabre\DAV\Exception - * @expectedExceptionMessage Setting members of the group is not supported yet - */ - public function testSetGroupMembership() { - $this->connector->setGroupMemberSet('principals/users/foo', ['foo']); - } - - public function testUpdatePrincipal() { - $this->assertSame(0, $this->connector->updatePrincipal('foo', new PropPatch(array()))); - } - - public function testSearchPrincipals() { - $this->assertSame([], $this->connector->searchPrincipals('principals/users', [])); - } - - public function testFindByUri() { - $fooUser = $this->getMockBuilder('\OC\User\User') - ->disableOriginalConstructor()->getMock(); - $fooUser - ->expects($this->exactly(1)) - ->method('getUID') - ->will($this->returnValue('foo')); - - $this->userManager->expects($this->once())->method('getByEmail')->willReturn([ - $fooUser - ]); - $ret = $this->connector->findByUri('mailto:foo@bar.net', 'principals/users'); - $this->assertSame('principals/users/foo', $ret); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/quotaplugin.php b/apps/dav/tests/unit/connector/sabre/quotaplugin.php deleted file mode 100644 index b5a8bfef31c..00000000000 --- a/apps/dav/tests/unit/connector/sabre/quotaplugin.php +++ /dev/null @@ -1,223 +0,0 @@ - - * @author Thomas Müller - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\Connector\Sabre; -/** - * Copyright (c) 2013 Thomas Müller - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -class QuotaPlugin extends \Test\TestCase { - - /** - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var \OCA\DAV\Connector\Sabre\QuotaPlugin - */ - private $plugin; - - private function init($quota, $checkedPath = '') { - $view = $this->buildFileViewMock($quota, $checkedPath); - $this->server = new \Sabre\DAV\Server(); - $this->plugin = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\QuotaPlugin') - ->setConstructorArgs([$view]) - ->setMethods(['getFileChunking']) - ->getMock(); - $this->plugin->initialize($this->server); - } - - /** - * @dataProvider lengthProvider - */ - public function testLength($expected, $headers) { - $this->init(0); - $this->plugin->expects($this->never()) - ->method('getFileChunking'); - $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); - $length = $this->plugin->getLength(); - $this->assertEquals($expected, $length); - } - - /** - * @dataProvider quotaOkayProvider - */ - public function testCheckQuota($quota, $headers) { - $this->init($quota); - $this->plugin->expects($this->never()) - ->method('getFileChunking'); - - $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); - $result = $this->plugin->checkQuota(''); - $this->assertTrue($result); - } - - /** - * @expectedException \Sabre\DAV\Exception\InsufficientStorage - * @dataProvider quotaExceededProvider - */ - public function testCheckExceededQuota($quota, $headers) { - $this->init($quota); - $this->plugin->expects($this->never()) - ->method('getFileChunking'); - - $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); - $this->plugin->checkQuota(''); - } - - /** - * @dataProvider quotaOkayProvider - */ - public function testCheckQuotaOnPath($quota, $headers) { - $this->init($quota, 'sub/test.txt'); - $this->plugin->expects($this->never()) - ->method('getFileChunking'); - - $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); - $result = $this->plugin->checkQuota('/sub/test.txt'); - $this->assertTrue($result); - } - - public function quotaOkayProvider() { - return array( - array(1024, array()), - array(1024, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), - array(1024, array('CONTENT-LENGTH' => '512')), - array(1024, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), - // \OCP\Files\FileInfo::SPACE-UNKNOWN = -2 - array(-2, array()), - array(-2, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), - array(-2, array('CONTENT-LENGTH' => '512')), - array(-2, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), - ); - } - - public function quotaExceededProvider() { - return array( - array(1023, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), - array(511, array('CONTENT-LENGTH' => '512')), - array(2047, array('OC-TOTAL-LENGTH' => '2048', 'CONTENT-LENGTH' => '1024')), - ); - } - - public function lengthProvider() { - return array( - array(null, array()), - array(1024, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), - array(512, array('CONTENT-LENGTH' => '512')), - array(2048, array('OC-TOTAL-LENGTH' => '2048', 'CONTENT-LENGTH' => '1024')), - array(4096, array('OC-TOTAL-LENGTH' => '2048', 'X-EXPECTED-ENTITY-LENGTH' => '4096')), - ); - } - - public function quotaChunkedOkProvider() { - return array( - array(1024, 0, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), - array(1024, 0, array('CONTENT-LENGTH' => '512')), - array(1024, 0, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), - // with existing chunks (allowed size = total length - chunk total size) - array(400, 128, array('X-EXPECTED-ENTITY-LENGTH' => '512')), - array(400, 128, array('CONTENT-LENGTH' => '512')), - array(400, 128, array('OC-TOTAL-LENGTH' => '512', 'CONTENT-LENGTH' => '500')), - // \OCP\Files\FileInfo::SPACE-UNKNOWN = -2 - array(-2, 0, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), - array(-2, 0, array('CONTENT-LENGTH' => '512')), - array(-2, 0, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), - array(-2, 128, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), - array(-2, 128, array('CONTENT-LENGTH' => '512')), - array(-2, 128, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), - ); - } - - /** - * @dataProvider quotaChunkedOkProvider - */ - public function testCheckQuotaChunkedOk($quota, $chunkTotalSize, $headers) { - $this->init($quota, 'sub/test.txt'); - - $mockChunking = $this->getMockBuilder('\OC_FileChunking') - ->disableOriginalConstructor() - ->getMock(); - $mockChunking->expects($this->once()) - ->method('getCurrentSize') - ->will($this->returnValue($chunkTotalSize)); - - $this->plugin->expects($this->once()) - ->method('getFileChunking') - ->will($this->returnValue($mockChunking)); - - $headers['OC-CHUNKED'] = 1; - $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); - $result = $this->plugin->checkQuota('/sub/test.txt-chunking-12345-3-1'); - $this->assertTrue($result); - } - - public function quotaChunkedFailProvider() { - return array( - array(400, 0, array('X-EXPECTED-ENTITY-LENGTH' => '1024')), - array(400, 0, array('CONTENT-LENGTH' => '512')), - array(400, 0, array('OC-TOTAL-LENGTH' => '1024', 'CONTENT-LENGTH' => '512')), - // with existing chunks (allowed size = total length - chunk total size) - array(380, 128, array('X-EXPECTED-ENTITY-LENGTH' => '512')), - array(380, 128, array('CONTENT-LENGTH' => '512')), - array(380, 128, array('OC-TOTAL-LENGTH' => '512', 'CONTENT-LENGTH' => '500')), - ); - } - - /** - * @dataProvider quotaChunkedFailProvider - * @expectedException \Sabre\DAV\Exception\InsufficientStorage - */ - public function testCheckQuotaChunkedFail($quota, $chunkTotalSize, $headers) { - $this->init($quota, 'sub/test.txt'); - - $mockChunking = $this->getMockBuilder('\OC_FileChunking') - ->disableOriginalConstructor() - ->getMock(); - $mockChunking->expects($this->once()) - ->method('getCurrentSize') - ->will($this->returnValue($chunkTotalSize)); - - $this->plugin->expects($this->once()) - ->method('getFileChunking') - ->will($this->returnValue($mockChunking)); - - $headers['OC-CHUNKED'] = 1; - $this->server->httpRequest = new \Sabre\HTTP\Request(null, null, $headers); - $this->plugin->checkQuota('/sub/test.txt-chunking-12345-3-1'); - } - - private function buildFileViewMock($quota, $checkedPath) { - // mock filesysten - $view = $this->getMock('\OC\Files\View', array('free_space'), array(), '', false); - $view->expects($this->any()) - ->method('free_space') - ->with($this->identicalTo($checkedPath)) - ->will($this->returnValue($quota)); - - return $view; - } - -} diff --git a/apps/dav/tests/unit/connector/sabre/requesttest/auth.php b/apps/dav/tests/unit/connector/sabre/requesttest/auth.php deleted file mode 100644 index b728a8f3bd8..00000000000 --- a/apps/dav/tests/unit/connector/sabre/requesttest/auth.php +++ /dev/null @@ -1,117 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest; - -use Sabre\DAV\Auth\Backend\BackendInterface; -use Sabre\HTTP\RequestInterface; -use Sabre\HTTP\ResponseInterface; - -class Auth implements BackendInterface { - /** - * @var string - */ - private $user; - - /** - * @var string - */ - private $password; - - /** - * Auth constructor. - * - * @param string $user - * @param string $password - */ - public function __construct($user, $password) { - $this->user = $user; - $this->password = $password; - } - - /** - * When this method is called, the backend must check if authentication was - * successful. - * - * The returned value must be one of the following - * - * [true, "principals/username"] - * [false, "reason for failure"] - * - * If authentication was successful, it's expected that the authentication - * backend returns a so-called principal url. - * - * Examples of a principal url: - * - * principals/admin - * principals/user1 - * principals/users/joe - * principals/uid/123457 - * - * If you don't use WebDAV ACL (RFC3744) we recommend that you simply - * return a string such as: - * - * principals/users/[username] - * - * @param RequestInterface $request - * @param ResponseInterface $response - * @return array - */ - function check(RequestInterface $request, ResponseInterface $response) { - $userSession = \OC::$server->getUserSession(); - $result = $userSession->login($this->user, $this->password); - if ($result) { - //we need to pass the user name, which may differ from login name - $user = $userSession->getUser()->getUID(); - \OC_Util::setupFS($user); - //trigger creation of user home and /files folder - \OC::$server->getUserFolder($user); - return [true, "principals/$user"]; - } - return [false, "login failed"]; - } - - /** - * This method is called when a user could not be authenticated, and - * authentication was required for the current request. - * - * This gives you the opportunity to set authentication headers. The 401 - * status code will already be set. - * - * In this case of Basic Auth, this would for example mean that the - * following header needs to be set: - * - * $response->addHeader('WWW-Authenticate', 'Basic realm=SabreDAV'); - * - * Keep in mind that in the case of multiple authentication backends, other - * WWW-Authenticate headers may already have been set, and you'll want to - * append your own WWW-Authenticate header instead of overwriting the - * existing one. - * - * @param RequestInterface $request - * @param ResponseInterface $response - * @return void - */ - function challenge(RequestInterface $request, ResponseInterface $response) { - // TODO: Implement challenge() method. - } -} diff --git a/apps/dav/tests/unit/connector/sabre/requesttest/downloadtest.php b/apps/dav/tests/unit/connector/sabre/requesttest/downloadtest.php deleted file mode 100644 index 3d047399a1f..00000000000 --- a/apps/dav/tests/unit/connector/sabre/requesttest/downloadtest.php +++ /dev/null @@ -1,73 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest; - -use OCP\AppFramework\Http; -use OCP\Lock\ILockingProvider; - -/** - * Class DownloadTest - * - * @group DB - * - * @package OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest - */ -class DownloadTest extends RequestTest { - public function testDownload() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $view->file_put_contents('foo.txt', 'bar'); - - $response = $this->request($view, $user, 'pass', 'GET', '/foo.txt'); - $this->assertEquals(Http::STATUS_OK, $response->getStatus()); - $this->assertEquals(stream_get_contents($response->getBody()), 'bar'); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked - */ - public function testDownloadWriteLocked() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $view->file_put_contents('foo.txt', 'bar'); - - $view->lockFile('/foo.txt', ILockingProvider::LOCK_EXCLUSIVE); - - $this->request($view, $user, 'pass', 'GET', '/foo.txt', 'asd'); - } - - public function testDownloadReadLocked() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $view->file_put_contents('foo.txt', 'bar'); - - $view->lockFile('/foo.txt', ILockingProvider::LOCK_SHARED); - - $response = $this->request($view, $user, 'pass', 'GET', '/foo.txt', 'asd'); - $this->assertEquals(Http::STATUS_OK, $response->getStatus()); - $this->assertEquals(stream_get_contents($response->getBody()), 'bar'); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/requesttest/encryptionuploadtest.php b/apps/dav/tests/unit/connector/sabre/requesttest/encryptionuploadtest.php deleted file mode 100644 index c5c6d0da0c2..00000000000 --- a/apps/dav/tests/unit/connector/sabre/requesttest/encryptionuploadtest.php +++ /dev/null @@ -1,46 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest; - -use OC\Files\View; -use Test\Traits\EncryptionTrait; - -/** - * Class EncryptionUploadTest - * - * @group DB - * - * @package OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest - */ -class EncryptionUploadTest extends UploadTest { - use EncryptionTrait; - - protected function setupUser($name, $password) { - $this->createUser($name, $password); - $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); - $this->setupForUser($name, $password); - $this->loginWithEncryption($name); - return new View('/' . $name . '/files'); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/requesttest/exceptionplugin.php b/apps/dav/tests/unit/connector/sabre/requesttest/exceptionplugin.php deleted file mode 100644 index a6a0f9d3b86..00000000000 --- a/apps/dav/tests/unit/connector/sabre/requesttest/exceptionplugin.php +++ /dev/null @@ -1,46 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest; - -use Sabre\DAV\Exception; - -class ExceptionPlugin extends \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin { - /** - * @var \Exception[] - */ - protected $exceptions = []; - - public function logException(\Exception $ex) { - $exceptionClass = get_class($ex); - if (!isset($this->nonFatalExceptions[$exceptionClass])) { - $this->exceptions[] = $ex; - } - } - - /** - * @return \Exception[] - */ - public function getExceptions() { - return $this->exceptions; - } -} diff --git a/apps/dav/tests/unit/connector/sabre/requesttest/partfileinrootupload.php b/apps/dav/tests/unit/connector/sabre/requesttest/partfileinrootupload.php deleted file mode 100644 index 52790c5b00b..00000000000 --- a/apps/dav/tests/unit/connector/sabre/requesttest/partfileinrootupload.php +++ /dev/null @@ -1,56 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest; - -use OC\Files\View; -use Test\Traits\EncryptionTrait; - -/** - * Class EncryptionUploadTest - * - * @group DB - * - * @package OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest - */ -class PartFileInRootUpload extends UploadTest { - protected function setUp() { - $config = \OC::$server->getConfig(); - $mockConfig = $this->getMock('\OCP\IConfig'); - $mockConfig->expects($this->any()) - ->method('getSystemValue') - ->will($this->returnCallback(function ($key, $default) use ($config) { - if ($key === 'part_file_in_storage') { - return false; - } else { - return $config->getSystemValue($key, $default); - } - })); - $this->overwriteService('AllConfig', $mockConfig); - parent::setUp(); - } - - protected function tearDown() { - $this->restoreService('AllConfig'); - return parent::tearDown(); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/requesttest/requesttest.php b/apps/dav/tests/unit/connector/sabre/requesttest/requesttest.php deleted file mode 100644 index e3cdca5abfa..00000000000 --- a/apps/dav/tests/unit/connector/sabre/requesttest/requesttest.php +++ /dev/null @@ -1,146 +0,0 @@ - - * @author Lukas Reschke - * @author Robin Appelman - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest; - -use OCA\DAV\Connector\Sabre\Server; -use OCA\DAV\Connector\Sabre\ServerFactory; -use OC\Files\Mount\MountPoint; -use OC\Files\Storage\StorageFactory; -use OC\Files\Storage\Temporary; -use OC\Files\View; -use OCP\IUser; -use Sabre\HTTP\Request; -use Test\TestCase; -use Test\Traits\MountProviderTrait; -use Test\Traits\UserTrait; - -abstract class RequestTest extends TestCase { - use UserTrait; - use MountProviderTrait; - - /** - * @var \OCA\DAV\Connector\Sabre\ServerFactory - */ - protected $serverFactory; - - protected function getStream($string) { - $stream = fopen('php://temp', 'r+'); - fwrite($stream, $string); - fseek($stream, 0); - return $stream; - } - - protected function setUp() { - parent::setUp(); - - $this->serverFactory = new ServerFactory( - \OC::$server->getConfig(), - \OC::$server->getLogger(), - \OC::$server->getDatabaseConnection(), - \OC::$server->getUserSession(), - \OC::$server->getMountManager(), - \OC::$server->getTagManager(), - $this->getMock('\OCP\IRequest') - ); - } - - protected function setupUser($name, $password) { - $this->createUser($name, $password); - $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); - $this->loginAsUser($name); - return new View('/' . $name . '/files'); - } - - /** - * @param \OC\Files\View $view the view to run the webdav server against - * @param string $user - * @param string $password - * @param string $method - * @param string $url - * @param resource|string|null $body - * @param array|null $headers - * @return \Sabre\HTTP\Response - * @throws \Exception - */ - protected function request($view, $user, $password, $method, $url, $body = null, $headers = null) { - if (is_string($body)) { - $body = $this->getStream($body); - } - $this->logout(); - $exceptionPlugin = new ExceptionPlugin('webdav', null); - $server = $this->getSabreServer($view, $user, $password, $exceptionPlugin); - $request = new Request($method, $url, $headers, $body); - - // since sabre catches all exceptions we need to save them and throw them from outside the sabre server - - $originalServer = $_SERVER; - - if (is_array($headers)) { - foreach ($headers as $header => $value) { - $_SERVER['HTTP_' . strtoupper(str_replace('-', '_', $header))] = $value; - } - } - - $result = $this->makeRequest($server, $request); - - foreach ($exceptionPlugin->getExceptions() as $exception) { - throw $exception; - } - $_SERVER = $originalServer; - return $result; - } - - /** - * @param Server $server - * @param Request $request - * @return \Sabre\HTTP\Response - */ - protected function makeRequest(Server $server, Request $request) { - $sapi = new Sapi($request); - $server->sapi = $sapi; - $server->httpRequest = $request; - $server->exec(); - return $sapi->getResponse(); - } - - /** - * @param View $view - * @param string $user - * @param string $password - * @param ExceptionPlugin $exceptionPlugin - * @return Server - */ - protected function getSabreServer(View $view, $user, $password, ExceptionPlugin $exceptionPlugin) { - $authBackend = new Auth($user, $password); - - $server = $this->serverFactory->createServer('/', 'dummy', $authBackend, function () use ($view) { - return $view; - }); - $server->addPlugin($exceptionPlugin); - - return $server; - } -} diff --git a/apps/dav/tests/unit/connector/sabre/requesttest/sapi.php b/apps/dav/tests/unit/connector/sabre/requesttest/sapi.php deleted file mode 100644 index 6407d9bc28b..00000000000 --- a/apps/dav/tests/unit/connector/sabre/requesttest/sapi.php +++ /dev/null @@ -1,75 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest; - -use Sabre\HTTP\Request; -use Sabre\HTTP\Response; - -class Sapi { - /** - * @var \Sabre\HTTP\Request - */ - private $request; - - /** - * @var \Sabre\HTTP\Response - */ - private $response; - - /** - * This static method will create a new Request object, based on the - * current PHP request. - * - * @return \Sabre\HTTP\Request - */ - public function getRequest() { - return $this->request; - } - - public function __construct(Request $request) { - $this->request = $request; - } - - /** - * @param \Sabre\HTTP\Response $response - * @return void - */ - public function sendResponse(Response $response) { - // we need to copy the body since we close the source stream - $copyStream = fopen('php://temp', 'r+'); - if (is_string($response->getBody())) { - fwrite($copyStream, $response->getBody()); - } else if (is_resource($response->getBody())) { - stream_copy_to_stream($response->getBody(), $copyStream); - } - rewind($copyStream); - $this->response = new Response($response->getStatus(), $response->getHeaders(), $copyStream); - } - - /** - * @return \Sabre\HTTP\Response - */ - public function getResponse() { - return $this->response; - } -} diff --git a/apps/dav/tests/unit/connector/sabre/requesttest/uploadtest.php b/apps/dav/tests/unit/connector/sabre/requesttest/uploadtest.php deleted file mode 100644 index ae30268e366..00000000000 --- a/apps/dav/tests/unit/connector/sabre/requesttest/uploadtest.php +++ /dev/null @@ -1,211 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest; - -use OC\Connector\Sabre\Exception\FileLocked; -use OCP\AppFramework\Http; -use OCP\Lock\ILockingProvider; - -/** - * Class UploadTest - * - * @group DB - * - * @package OCA\DAV\Tests\Unit\Connector\Sabre\RequestTest - */ -class UploadTest extends RequestTest { - public function testBasicUpload() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $this->assertFalse($view->file_exists('foo.txt')); - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt', 'asd'); - - $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); - $this->assertTrue($view->file_exists('foo.txt')); - $this->assertEquals('asd', $view->file_get_contents('foo.txt')); - - $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); - $this->assertEquals(3, $info->getSize()); - } - - public function testUploadOverWrite() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $view->file_put_contents('foo.txt', 'foobar'); - - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt', 'asd'); - - $this->assertEquals(Http::STATUS_NO_CONTENT, $response->getStatus()); - $this->assertEquals('asd', $view->file_get_contents('foo.txt')); - - $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); - $this->assertEquals(3, $info->getSize()); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked - */ - public function testUploadOverWriteReadLocked() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $view->file_put_contents('foo.txt', 'bar'); - - $view->lockFile('/foo.txt', ILockingProvider::LOCK_SHARED); - - $this->request($view, $user, 'pass', 'PUT', '/foo.txt', 'asd'); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked - */ - public function testUploadOverWriteWriteLocked() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $view->file_put_contents('foo.txt', 'bar'); - - $view->lockFile('/foo.txt', ILockingProvider::LOCK_EXCLUSIVE); - - $this->request($view, $user, 'pass', 'PUT', '/foo.txt', 'asd'); - } - - public function testChunkedUpload() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $this->assertFalse($view->file_exists('foo.txt')); - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); - - $this->assertEquals(201, $response->getStatus()); - $this->assertFalse($view->file_exists('foo.txt')); - - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); - - $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); - $this->assertTrue($view->file_exists('foo.txt')); - - $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); - - $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); - $this->assertEquals(6, $info->getSize()); - } - - public function testChunkedUploadOverWrite() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $view->file_put_contents('foo.txt', 'bar'); - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); - - $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); - $this->assertEquals('bar', $view->file_get_contents('foo.txt')); - - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); - - $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); - - $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); - - $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); - $this->assertEquals(6, $info->getSize()); - } - - public function testChunkedUploadOutOfOrder() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $this->assertFalse($view->file_exists('foo.txt')); - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); - - $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); - $this->assertFalse($view->file_exists('foo.txt')); - - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); - - $this->assertEquals(201, $response->getStatus()); - $this->assertTrue($view->file_exists('foo.txt')); - - $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); - - $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); - $this->assertEquals(6, $info->getSize()); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked - */ - public function testChunkedUploadOutOfOrderReadLocked() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $this->assertFalse($view->file_exists('foo.txt')); - - $view->lockFile('/foo.txt', ILockingProvider::LOCK_SHARED); - - try { - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); - } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { - $this->fail('Didn\'t expect locked error for the first chunk on read lock'); - return; - } - - $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); - $this->assertFalse($view->file_exists('foo.txt')); - - // last chunk should trigger the locked error since it tries to assemble - $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); - } - - /** - * @expectedException \OCA\DAV\Connector\Sabre\Exception\FileLocked - */ - public function testChunkedUploadOutOfOrderWriteLocked() { - $user = $this->getUniqueID(); - $view = $this->setupUser($user, 'pass'); - - $this->assertFalse($view->file_exists('foo.txt')); - - $view->lockFile('/foo.txt', ILockingProvider::LOCK_EXCLUSIVE); - - try { - $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); - } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { - $this->fail('Didn\'t expect locked error for the first chunk on write lock'); // maybe forbid this in the future for write locks only? - return; - } - - $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); - $this->assertFalse($view->file_exists('foo.txt')); - - // last chunk should trigger the locked error since it tries to assemble - $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-0', 'asd', ['OC-Chunked' => '1']); - } -} diff --git a/apps/dav/tests/unit/connector/sabre/sharesplugin.php b/apps/dav/tests/unit/connector/sabre/sharesplugin.php deleted file mode 100644 index 42f1b539916..00000000000 --- a/apps/dav/tests/unit/connector/sabre/sharesplugin.php +++ /dev/null @@ -1,259 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -class SharesPlugin extends \Test\TestCase { - - const SHARETYPES_PROPERTYNAME = \OCA\DAV\Connector\Sabre\SharesPlugin::SHARETYPES_PROPERTYNAME; - - /** - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var \Sabre\DAV\Tree - */ - private $tree; - - /** - * @var \OCP\Share\IManager - */ - private $shareManager; - - /** - * @var \OCP\Files\Folder - */ - private $userFolder; - - /** - * @var \OCA\DAV\Connector\Sabre\SharesPlugin - */ - private $plugin; - - public function setUp() { - parent::setUp(); - $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') - ->disableOriginalConstructor() - ->getMock(); - $this->shareManager = $this->getMock('\OCP\Share\IManager'); - $user = $this->getMock('\OCP\IUser'); - $user->expects($this->once()) - ->method('getUID') - ->will($this->returnValue('user1')); - $userSession = $this->getMock('\OCP\IUserSession'); - $userSession->expects($this->once()) - ->method('getUser') - ->will($this->returnValue($user)); - - $this->userFolder = $this->getMock('\OCP\Files\Folder'); - - $this->plugin = new \OCA\DAV\Connector\Sabre\SharesPlugin( - $this->tree, - $userSession, - $this->userFolder, - $this->shareManager - ); - $this->plugin->initialize($this->server); - } - - /** - * @dataProvider sharesGetPropertiesDataProvider - */ - public function testGetProperties($shareTypes) { - $sabreNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') - ->disableOriginalConstructor() - ->getMock(); - $sabreNode->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - $sabreNode->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/subdir')); - - // node API nodes - $node = $this->getMock('\OCP\Files\Folder'); - - $this->userFolder->expects($this->once()) - ->method('get') - ->with('/subdir') - ->will($this->returnValue($node)); - - $this->shareManager->expects($this->any()) - ->method('getSharesBy') - ->with( - $this->equalTo('user1'), - $this->anything(), - $this->anything(), - $this->equalTo(false), - $this->equalTo(1) - ) - ->will($this->returnCallback(function($userId, $requestedShareType, $node, $flag, $limit) use ($shareTypes){ - if (in_array($requestedShareType, $shareTypes)) { - return ['dummyshare']; - } - return []; - })); - - $propFind = new \Sabre\DAV\PropFind( - '/dummyPath', - [self::SHARETYPES_PROPERTYNAME], - 0 - ); - - $this->plugin->handleGetProperties( - $propFind, - $sabreNode - ); - - $result = $propFind->getResultForMultiStatus(); - - $this->assertEmpty($result[404]); - unset($result[404]); - $this->assertEquals($shareTypes, $result[200][self::SHARETYPES_PROPERTYNAME]->getShareTypes()); - } - - /** - * @dataProvider sharesGetPropertiesDataProvider - */ - public function testPreloadThenGetProperties($shareTypes) { - $sabreNode1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') - ->disableOriginalConstructor() - ->getMock(); - $sabreNode1->expects($this->any()) - ->method('getId') - ->will($this->returnValue(111)); - $sabreNode1->expects($this->never()) - ->method('getPath'); - $sabreNode2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') - ->disableOriginalConstructor() - ->getMock(); - $sabreNode2->expects($this->any()) - ->method('getId') - ->will($this->returnValue(222)); - $sabreNode2->expects($this->never()) - ->method('getPath'); - - $sabreNode = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $sabreNode->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - // never, because we use getDirectoryListing from the Node API instead - $sabreNode->expects($this->never()) - ->method('getChildren'); - $sabreNode->expects($this->any()) - ->method('getPath') - ->will($this->returnValue('/subdir')); - - // node API nodes - $node = $this->getMock('\OCP\Files\Folder'); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - $node1 = $this->getMock('\OCP\Files\File'); - $node1->expects($this->any()) - ->method('getId') - ->will($this->returnValue(111)); - $node2 = $this->getMock('\OCP\Files\File'); - $node2->expects($this->any()) - ->method('getId') - ->will($this->returnValue(222)); - $node->expects($this->once()) - ->method('getDirectoryListing') - ->will($this->returnValue([$node1, $node2])); - - $this->userFolder->expects($this->once()) - ->method('get') - ->with('/subdir') - ->will($this->returnValue($node)); - - $this->shareManager->expects($this->any()) - ->method('getSharesBy') - ->with( - $this->equalTo('user1'), - $this->anything(), - $this->anything(), - $this->equalTo(false), - $this->equalTo(1) - ) - ->will($this->returnCallback(function($userId, $requestedShareType, $node, $flag, $limit) use ($shareTypes){ - if ($node->getId() === 111 && in_array($requestedShareType, $shareTypes)) { - return ['dummyshare']; - } - - return []; - })); - - // simulate sabre recursive PROPFIND traversal - $propFindRoot = new \Sabre\DAV\PropFind( - '/subdir', - [self::SHARETYPES_PROPERTYNAME], - 1 - ); - $propFind1 = new \Sabre\DAV\PropFind( - '/subdir/test.txt', - [self::SHARETYPES_PROPERTYNAME], - 0 - ); - $propFind2 = new \Sabre\DAV\PropFind( - '/subdir/test2.txt', - [self::SHARETYPES_PROPERTYNAME], - 0 - ); - - $this->plugin->handleGetProperties( - $propFindRoot, - $sabreNode - ); - $this->plugin->handleGetProperties( - $propFind1, - $sabreNode1 - ); - $this->plugin->handleGetProperties( - $propFind2, - $sabreNode2 - ); - - $result = $propFind1->getResultForMultiStatus(); - - $this->assertEmpty($result[404]); - unset($result[404]); - $this->assertEquals($shareTypes, $result[200][self::SHARETYPES_PROPERTYNAME]->getShareTypes()); - } - - function sharesGetPropertiesDataProvider() { - return [ - [[]], - [[\OCP\Share::SHARE_TYPE_USER]], - [[\OCP\Share::SHARE_TYPE_GROUP]], - [[\OCP\Share::SHARE_TYPE_LINK]], - [[\OCP\Share::SHARE_TYPE_REMOTE]], - [[\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP]], - [[\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK]], - [[\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_LINK]], - [[\OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK]], - [[\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_REMOTE]], - ]; - } -} diff --git a/apps/dav/tests/unit/connector/sabre/tagsplugin.php b/apps/dav/tests/unit/connector/sabre/tagsplugin.php deleted file mode 100644 index 95ba002e393..00000000000 --- a/apps/dav/tests/unit/connector/sabre/tagsplugin.php +++ /dev/null @@ -1,417 +0,0 @@ - - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\Connector\Sabre; - -/** - * Copyright (c) 2014 Vincent Petry - * This file is licensed under the Affero General Public License version 3 or - * later. - * See the COPYING-README file. - */ -class TagsPlugin extends \Test\TestCase { - - const TAGS_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::TAGS_PROPERTYNAME; - const FAVORITE_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::FAVORITE_PROPERTYNAME; - const TAG_FAVORITE = \OCA\DAV\Connector\Sabre\TagsPlugin::TAG_FAVORITE; - - /** - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var \Sabre\DAV\Tree - */ - private $tree; - - /** - * @var \OCP\ITagManager - */ - private $tagManager; - - /** - * @var \OCP\ITags - */ - private $tagger; - - /** - * @var \OCA\DAV\Connector\Sabre\TagsPlugin - */ - private $plugin; - - public function setUp() { - parent::setUp(); - $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') - ->disableOriginalConstructor() - ->getMock(); - $this->tagger = $this->getMock('\OCP\ITags'); - $this->tagManager = $this->getMock('\OCP\ITagManager'); - $this->tagManager->expects($this->any()) - ->method('load') - ->with('files') - ->will($this->returnValue($this->tagger)); - $this->plugin = new \OCA\DAV\Connector\Sabre\TagsPlugin($this->tree, $this->tagManager); - $this->plugin->initialize($this->server); - } - - /** - * @dataProvider tagsGetPropertiesDataProvider - */ - public function testGetProperties($tags, $requestedProperties, $expectedProperties) { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - - $expectedCallCount = 0; - if (count($requestedProperties) > 0) { - $expectedCallCount = 1; - } - - $this->tagger->expects($this->exactly($expectedCallCount)) - ->method('getTagsForObjects') - ->with($this->equalTo(array(123))) - ->will($this->returnValue(array(123 => $tags))); - - $propFind = new \Sabre\DAV\PropFind( - '/dummyPath', - $requestedProperties, - 0 - ); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - - $result = $propFind->getResultForMultiStatus(); - - $this->assertEmpty($result[404]); - unset($result[404]); - $this->assertEquals($expectedProperties, $result); - } - - /** - * @dataProvider tagsGetPropertiesDataProvider - */ - public function testPreloadThenGetProperties($tags, $requestedProperties, $expectedProperties) { - $node1 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') - ->disableOriginalConstructor() - ->getMock(); - $node1->expects($this->any()) - ->method('getId') - ->will($this->returnValue(111)); - $node2 = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\File') - ->disableOriginalConstructor() - ->getMock(); - $node2->expects($this->any()) - ->method('getId') - ->will($this->returnValue(222)); - - $expectedCallCount = 0; - if (count($requestedProperties) > 0) { - // this guarantees that getTagsForObjects - // is only called once and then the tags - // are cached - $expectedCallCount = 1; - } - - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - $node->expects($this->exactly($expectedCallCount)) - ->method('getChildren') - ->will($this->returnValue(array($node1, $node2))); - - $this->tagger->expects($this->exactly($expectedCallCount)) - ->method('getTagsForObjects') - ->with($this->equalTo(array(123, 111, 222))) - ->will($this->returnValue( - array( - 111 => $tags, - 123 => $tags - ) - )); - - // simulate sabre recursive PROPFIND traversal - $propFindRoot = new \Sabre\DAV\PropFind( - '/subdir', - $requestedProperties, - 1 - ); - $propFind1 = new \Sabre\DAV\PropFind( - '/subdir/test.txt', - $requestedProperties, - 0 - ); - $propFind2 = new \Sabre\DAV\PropFind( - '/subdir/test2.txt', - $requestedProperties, - 0 - ); - - $this->plugin->handleGetProperties( - $propFindRoot, - $node - ); - $this->plugin->handleGetProperties( - $propFind1, - $node1 - ); - $this->plugin->handleGetProperties( - $propFind2, - $node2 - ); - - $result = $propFind1->getResultForMultiStatus(); - - $this->assertEmpty($result[404]); - unset($result[404]); - $this->assertEquals($expectedProperties, $result); - } - - function tagsGetPropertiesDataProvider() { - return array( - // request both, receive both - array( - array('tag1', 'tag2', self::TAG_FAVORITE), - array(self::TAGS_PROPERTYNAME, self::FAVORITE_PROPERTYNAME), - array( - 200 => array( - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array('tag1', 'tag2')), - self::FAVORITE_PROPERTYNAME => true, - ) - ) - ), - // request tags alone - array( - array('tag1', 'tag2', self::TAG_FAVORITE), - array(self::TAGS_PROPERTYNAME), - array( - 200 => array( - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array('tag1', 'tag2')), - ) - ) - ), - // request fav alone - array( - array('tag1', 'tag2', self::TAG_FAVORITE), - array(self::FAVORITE_PROPERTYNAME), - array( - 200 => array( - self::FAVORITE_PROPERTYNAME => true, - ) - ) - ), - // request none - array( - array('tag1', 'tag2', self::TAG_FAVORITE), - array(), - array( - 200 => array() - ), - ), - // request both with none set, receive both - array( - array(), - array(self::TAGS_PROPERTYNAME, self::FAVORITE_PROPERTYNAME), - array( - 200 => array( - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array()), - self::FAVORITE_PROPERTYNAME => false, - ) - ) - ), - ); - } - - public function testUpdateTags() { - // this test will replace the existing tags "tagremove" with "tag1" and "tag2" - // and keep "tagkeep" - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->returnValue($node)); - - $this->tagger->expects($this->at(0)) - ->method('getTagsForObjects') - ->with($this->equalTo(array(123))) - ->will($this->returnValue(array(123 => array('tagkeep', 'tagremove', self::TAG_FAVORITE)))); - - // then tag as tag1 and tag2 - $this->tagger->expects($this->at(1)) - ->method('tagAs') - ->with(123, 'tag1'); - $this->tagger->expects($this->at(2)) - ->method('tagAs') - ->with(123, 'tag2'); - - // it will untag tag3 - $this->tagger->expects($this->at(3)) - ->method('unTag') - ->with(123, 'tagremove'); - - // properties to set - $propPatch = new \Sabre\DAV\PropPatch(array( - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array('tag1', 'tag2', 'tagkeep')) - )); - - $this->plugin->handleUpdateProperties( - '/dummypath', - $propPatch - ); - - $propPatch->commit(); - - // all requested properties removed, as they were processed already - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertEquals(200, $result[self::TAGS_PROPERTYNAME]); - $this->assertFalse(isset($result[self::FAVORITE_PROPERTYNAME])); - } - - public function testUpdateTagsFromScratch() { - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->returnValue($node)); - - $this->tagger->expects($this->at(0)) - ->method('getTagsForObjects') - ->with($this->equalTo(array(123))) - ->will($this->returnValue(array())); - - // then tag as tag1 and tag2 - $this->tagger->expects($this->at(1)) - ->method('tagAs') - ->with(123, 'tag1'); - $this->tagger->expects($this->at(2)) - ->method('tagAs') - ->with(123, 'tag2'); - - // properties to set - $propPatch = new \Sabre\DAV\PropPatch(array( - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(array('tag1', 'tag2', 'tagkeep')) - )); - - $this->plugin->handleUpdateProperties( - '/dummypath', - $propPatch - ); - - $propPatch->commit(); - - // all requested properties removed, as they were processed already - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertEquals(200, $result[self::TAGS_PROPERTYNAME]); - $this->assertFalse(false, isset($result[self::FAVORITE_PROPERTYNAME])); - } - - public function testUpdateFav() { - // this test will replace the existing tags "tagremove" with "tag1" and "tag2" - // and keep "tagkeep" - $node = $this->getMockBuilder('\OCA\DAV\Connector\Sabre\Node') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->will($this->returnValue(123)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/dummypath') - ->will($this->returnValue($node)); - - // set favorite tag - $this->tagger->expects($this->once()) - ->method('tagAs') - ->with(123, self::TAG_FAVORITE); - - // properties to set - $propPatch = new \Sabre\DAV\PropPatch(array( - self::FAVORITE_PROPERTYNAME => true - )); - - $this->plugin->handleUpdateProperties( - '/dummypath', - $propPatch - ); - - $propPatch->commit(); - - // all requested properties removed, as they were processed already - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertFalse(false, isset($result[self::TAGS_PROPERTYNAME])); - $this->assertEquals(200, isset($result[self::FAVORITE_PROPERTYNAME])); - - // unfavorite now - // set favorite tag - $this->tagger->expects($this->once()) - ->method('unTag') - ->with(123, self::TAG_FAVORITE); - - // properties to set - $propPatch = new \Sabre\DAV\PropPatch(array( - self::FAVORITE_PROPERTYNAME => false - )); - - $this->plugin->handleUpdateProperties( - '/dummypath', - $propPatch - ); - - $propPatch->commit(); - - // all requested properties removed, as they were processed already - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertFalse(false, isset($result[self::TAGS_PROPERTYNAME])); - $this->assertEquals(200, isset($result[self::FAVORITE_PROPERTYNAME])); - } - -} diff --git a/apps/dav/tests/unit/dav/HookManagerTest.php b/apps/dav/tests/unit/dav/HookManagerTest.php deleted file mode 100644 index 5c36d0d785c..00000000000 --- a/apps/dav/tests/unit/dav/HookManagerTest.php +++ /dev/null @@ -1,152 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\DAV; - -use OCA\DAV\CalDAV\BirthdayService; -use OCA\DAV\CalDAV\CalDavBackend; -use OCA\DAV\CardDAV\CardDavBackend; -use OCA\DAV\CardDAV\SyncService; -use OCA\DAV\HookManager; -use OCP\IUserManager; -use Test\TestCase; - -class HookManagerTest extends TestCase { - public function test() { - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->once())->method('getUID')->willReturn('newUser'); - - /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ - $userManager = $this->getMockBuilder('\OCP\IUserManager') - ->disableOriginalConstructor() - ->getMock(); - $userManager->expects($this->once())->method('get')->willReturn($user); - - /** @var SyncService | \PHPUnit_Framework_MockObject_MockObject $syncService */ - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); - - /** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject $cal */ - $cal = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend') - ->disableOriginalConstructor() - ->getMock(); - $cal->expects($this->once())->method('getCalendarsForUser')->willReturn([]); - $cal->expects($this->once())->method('createCalendar')->with( - 'principals/users/newUser', - 'personal', ['{DAV:}displayname' => 'Personal']); - - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $card */ - $card = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') - ->disableOriginalConstructor() - ->getMock(); - $card->expects($this->once())->method('getAddressBooksForUser')->willReturn([]); - $card->expects($this->once())->method('createAddressBook')->with( - 'principals/users/newUser', - 'contacts', ['{DAV:}displayname' => 'Contacts']); - - $hm = new HookManager($userManager, $syncService, $cal, $card); - $hm->postLogin(['uid' => 'newUser']); - } - - public function testWithExisting() { - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->once())->method('getUID')->willReturn('newUser'); - - /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ - $userManager = $this->getMockBuilder('\OCP\IUserManager') - ->disableOriginalConstructor() - ->getMock(); - $userManager->expects($this->once())->method('get')->willReturn($user); - - /** @var SyncService | \PHPUnit_Framework_MockObject_MockObject $syncService */ - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); - - /** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject $cal */ - $cal = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend') - ->disableOriginalConstructor() - ->getMock(); - $cal->expects($this->once())->method('getCalendarsForUser')->willReturn([ - ['uri' => 'my-events'] - ]); - $cal->expects($this->never())->method('createCalendar'); - - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $card */ - $card = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') - ->disableOriginalConstructor() - ->getMock(); - $card->expects($this->once())->method('getAddressBooksForUser')->willReturn([ - ['uri' => 'my-contacts'] - ]); - $card->expects($this->never())->method('createAddressBook'); - - $hm = new HookManager($userManager, $syncService, $cal, $card); - $hm->postLogin(['uid' => 'newUser']); - } - - public function testWithBirthdayCalendar() { - $user = $this->getMockBuilder('\OCP\IUser') - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->once())->method('getUID')->willReturn('newUser'); - - /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject $userManager */ - $userManager = $this->getMockBuilder('\OCP\IUserManager') - ->disableOriginalConstructor() - ->getMock(); - $userManager->expects($this->once())->method('get')->willReturn($user); - - /** @var SyncService | \PHPUnit_Framework_MockObject_MockObject $syncService */ - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); - - /** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject $cal */ - $cal = $this->getMockBuilder('OCA\DAV\CalDAV\CalDavBackend') - ->disableOriginalConstructor() - ->getMock(); - $cal->expects($this->once())->method('getCalendarsForUser')->willReturn([ - ['uri' => BirthdayService::BIRTHDAY_CALENDAR_URI] - ]); - $cal->expects($this->once())->method('createCalendar')->with( - 'principals/users/newUser', - 'personal', ['{DAV:}displayname' => 'Personal']); - - /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $card */ - $card = $this->getMockBuilder('OCA\DAV\CardDAV\CardDavBackend') - ->disableOriginalConstructor() - ->getMock(); - $card->expects($this->once())->method('getAddressBooksForUser')->willReturn([]); - $card->expects($this->once())->method('createAddressBook')->with( - 'principals/users/newUser', - 'contacts', ['{DAV:}displayname' => 'Contacts']); - - $hm = new HookManager($userManager, $syncService, $cal, $card); - $hm->postLogin(['uid' => 'newUser']); - } -} diff --git a/apps/dav/tests/unit/dav/browsererrorpageplugintest.php b/apps/dav/tests/unit/dav/browsererrorpageplugintest.php deleted file mode 100644 index aeae0e1b152..00000000000 --- a/apps/dav/tests/unit/dav/browsererrorpageplugintest.php +++ /dev/null @@ -1,57 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\DAV; - -use OCA\DAV\Files\BrowserErrorPagePlugin; -use PHPUnit_Framework_MockObject_MockObject; -use Sabre\DAV\Exception\NotFound; - -class BrowserErrorPagePluginTest extends \Test\TestCase { - - /** - * @dataProvider providesExceptions - * @param $expectedCode - * @param $exception - */ - public function test($expectedCode, $exception) { - /** @var BrowserErrorPagePlugin | PHPUnit_Framework_MockObject_MockObject $plugin */ - $plugin = $this->getMockBuilder('OCA\DAV\Files\BrowserErrorPagePlugin')->setMethods(['sendResponse', 'generateBody'])->getMock(); - $plugin->expects($this->once())->method('generateBody')->willReturn(':boom:'); - $plugin->expects($this->once())->method('sendResponse'); - /** @var \Sabre\DAV\Server | PHPUnit_Framework_MockObject_MockObject $server */ - $server = $this->getMockBuilder('Sabre\DAV\Server')->disableOriginalConstructor()->getMock(); - $server->expects($this->once())->method('on'); - $httpResponse = $this->getMockBuilder('Sabre\HTTP\Response')->disableOriginalConstructor()->getMock(); - $httpResponse->expects($this->once())->method('addHeaders'); - $httpResponse->expects($this->once())->method('setStatus')->with($expectedCode); - $httpResponse->expects($this->once())->method('setBody')->with(':boom:'); - $server->httpResponse = $httpResponse; - $plugin->initialize($server); - $plugin->logException($exception); - } - - public function providesExceptions() { - return [ - [ 404, new NotFound()], - [ 500, new \RuntimeException()], - ]; - } -} diff --git a/apps/dav/tests/unit/dav/groupprincipaltest.php b/apps/dav/tests/unit/dav/groupprincipaltest.php deleted file mode 100644 index 9d012639310..00000000000 --- a/apps/dav/tests/unit/dav/groupprincipaltest.php +++ /dev/null @@ -1,164 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit\DAV; - -use OCA\DAV\DAV\GroupPrincipalBackend; -use OCP\IGroupManager; -use PHPUnit_Framework_MockObject_MockObject; -use \Sabre\DAV\PropPatch; - -class GroupPrincipalTest extends \Test\TestCase { - - /** @var IGroupManager | PHPUnit_Framework_MockObject_MockObject */ - private $groupManager; - - /** @var GroupPrincipalBackend */ - private $connector; - - public function setUp() { - $this->groupManager = $this->getMockBuilder('\OCP\IGroupManager') - ->disableOriginalConstructor()->getMock(); - - $this->connector = new GroupPrincipalBackend($this->groupManager); - parent::setUp(); - } - - public function testGetPrincipalsByPrefixWithoutPrefix() { - $response = $this->connector->getPrincipalsByPrefix(''); - $this->assertSame([], $response); - } - - public function testGetPrincipalsByPrefixWithUsers() { - $group1 = $this->mockGroup('foo'); - $group2 = $this->mockGroup('bar'); - $this->groupManager - ->expects($this->once()) - ->method('search') - ->with('') - ->will($this->returnValue([$group1, $group2])); - - $expectedResponse = [ - 0 => [ - 'uri' => 'principals/groups/foo', - '{DAV:}displayname' => 'foo' - ], - 1 => [ - 'uri' => 'principals/groups/bar', - '{DAV:}displayname' => 'bar', - ] - ]; - $response = $this->connector->getPrincipalsByPrefix('principals/groups'); - $this->assertSame($expectedResponse, $response); - } - - public function testGetPrincipalsByPrefixEmpty() { - $this->groupManager - ->expects($this->once()) - ->method('search') - ->with('') - ->will($this->returnValue([])); - - $response = $this->connector->getPrincipalsByPrefix('principals/groups'); - $this->assertSame([], $response); - } - - public function testGetPrincipalsByPathWithoutMail() { - $group1 = $this->mockGroup('foo'); - $this->groupManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue($group1)); - - $expectedResponse = [ - 'uri' => 'principals/groups/foo', - '{DAV:}displayname' => 'foo' - ]; - $response = $this->connector->getPrincipalByPath('principals/groups/foo'); - $this->assertSame($expectedResponse, $response); - } - - public function testGetPrincipalsByPathWithMail() { - $fooUser = $this->mockGroup('foo'); - $this->groupManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue($fooUser)); - - $expectedResponse = [ - 'uri' => 'principals/groups/foo', - '{DAV:}displayname' => 'foo', - ]; - $response = $this->connector->getPrincipalByPath('principals/groups/foo'); - $this->assertSame($expectedResponse, $response); - } - - public function testGetPrincipalsByPathEmpty() { - $this->groupManager - ->expects($this->once()) - ->method('get') - ->with('foo') - ->will($this->returnValue(null)); - - $response = $this->connector->getPrincipalByPath('principals/groups/foo'); - $this->assertSame(null, $response); - } - - public function testGetGroupMemberSet() { - $response = $this->connector->getGroupMemberSet('principals/groups/foo'); - $this->assertSame([], $response); - } - - public function testGetGroupMembership() { - $response = $this->connector->getGroupMembership('principals/groups/foo'); - $this->assertSame([], $response); - } - - /** - * @expectedException \Sabre\DAV\Exception - * @expectedExceptionMessage Setting members of the group is not supported yet - */ - public function testSetGroupMembership() { - $this->connector->setGroupMemberSet('principals/groups/foo', ['foo']); - } - - public function testUpdatePrincipal() { - $this->assertSame(0, $this->connector->updatePrincipal('foo', new PropPatch(array()))); - } - - public function testSearchPrincipals() { - $this->assertSame([], $this->connector->searchPrincipals('principals/groups', [])); - } - - /** - * @return PHPUnit_Framework_MockObject_MockObject - */ - private function mockGroup($gid) { - $fooUser = $this->getMockBuilder('\OC\Group\Group') - ->disableOriginalConstructor()->getMock(); - $fooUser - ->expects($this->exactly(1)) - ->method('getGID') - ->will($this->returnValue($gid)); - return $fooUser; - } -} diff --git a/apps/dav/tests/unit/dav/sharing/plugintest.php b/apps/dav/tests/unit/dav/sharing/plugintest.php deleted file mode 100644 index ce6c96f1bfc..00000000000 --- a/apps/dav/tests/unit/dav/sharing/plugintest.php +++ /dev/null @@ -1,83 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\DAV; - - -use OCA\DAV\DAV\Sharing\IShareable; -use OCA\DAV\DAV\Sharing\Plugin; -use OCA\DAV\Connector\Sabre\Auth; -use OCP\IRequest; -use Sabre\DAV\Server; -use Sabre\DAV\SimpleCollection; -use Sabre\HTTP\Request; -use Sabre\HTTP\Response; -use Test\TestCase; - -class PluginTest extends TestCase { - - /** @var Plugin */ - private $plugin; - /** @var Server */ - private $server; - /** @var IShareable | \PHPUnit_Framework_MockObject_MockObject */ - private $book; - - public function setUp() { - parent::setUp(); - - /** @var Auth | \PHPUnit_Framework_MockObject_MockObject $authBackend */ - $authBackend = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Auth')->disableOriginalConstructor()->getMock(); - $authBackend->method('isDavAuthenticated')->willReturn(true); - - /** @var IRequest $request */ - $request = $this->getMockBuilder('OCP\IRequest')->disableOriginalConstructor()->getMock(); - $this->plugin = new Plugin($authBackend, $request); - - $root = new SimpleCollection('root'); - $this->server = new \Sabre\DAV\Server($root); - /** @var SimpleCollection $node */ - $this->book = $this->getMockBuilder('OCA\DAV\DAV\Sharing\IShareable')-> - disableOriginalConstructor()-> - getMock(); - $this->book->method('getName')->willReturn('addressbook1.vcf'); - $root->addChild($this->book); - $this->plugin->initialize($this->server); - } - - public function testSharing() { - - $this->book->expects($this->once())->method('updateShares')->with([[ - 'href' => 'principal:principals/admin', - 'commonName' => null, - 'summary' => null, - 'readOnly' => false - ]], ['mailto:wilfredo@example.com']); - - // setup request - $request = new Request(); - $request->addHeader('Content-Type', 'application/xml'); - $request->setUrl('addressbook1.vcf'); - $request->setBody('principal:principals/admin mailto:wilfredo@example.com'); - $response = new Response(); - $this->plugin->httpPost($request, $response); - } -} diff --git a/apps/dav/tests/unit/dav/systemprincipalbackendtest.php b/apps/dav/tests/unit/dav/systemprincipalbackendtest.php deleted file mode 100644 index 26717f7509b..00000000000 --- a/apps/dav/tests/unit/dav/systemprincipalbackendtest.php +++ /dev/null @@ -1,131 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\DAV; - -use OCA\DAV\DAV\SystemPrincipalBackend; -use Test\TestCase; - -class SystemPrincipalBackendTest extends TestCase { - - /** - * @dataProvider providesPrefix - * @param $expected - * @param $prefix - */ - public function testGetPrincipalsByPrefix($expected, $prefix) { - $backend = new SystemPrincipalBackend(); - $result = $backend->getPrincipalsByPrefix($prefix); - $this->assertEquals($expected, $result); - } - - public function providesPrefix() { - return [ - [[], ''], - [[[ - 'uri' => 'principals/system/system', - '{DAV:}displayname' => 'system', - ]], 'principals/system'], - ]; - } - - /** - * @dataProvider providesPath - * @param $expected - * @param $path - */ - public function testGetPrincipalByPath($expected, $path) { - $backend = new SystemPrincipalBackend(); - $result = $backend->getPrincipalByPath($path); - $this->assertEquals($expected, $result); - } - - public function providesPath() { - return [ - [null, ''], - [null, 'principals'], - [null, 'principals/system'], - [[ - 'uri' => 'principals/system/system', - '{DAV:}displayname' => 'system', - ], 'principals/system/system'], - ]; - } - - /** - * @dataProvider providesPrincipalForGetGroupMemberSet - * @expectedException \Sabre\DAV\Exception - * @expectedExceptionMessage Principal not found - * - * @param string $principal - * @throws \Sabre\DAV\Exception - */ - public function testGetGroupMemberSetExceptional($principal) { - $backend = new SystemPrincipalBackend(); - $backend->getGroupMemberSet($principal); - } - - public function providesPrincipalForGetGroupMemberSet() { - return [ - [null], - ['principals/system'], - ]; - } - - /** - * @throws \Sabre\DAV\Exception - */ - public function testGetGroupMemberSet() { - $backend = new SystemPrincipalBackend(); - $result = $backend->getGroupMemberSet('principals/system/system'); - $this->assertEquals(['principals/system/system'], $result); - } - - /** - * @dataProvider providesPrincipalForGetGroupMembership - * @expectedException \Sabre\DAV\Exception - * @expectedExceptionMessage Principal not found - * - * @param string $principal - * @throws \Sabre\DAV\Exception - */ - public function testGetGroupMembershipExceptional($principal) { - $backend = new SystemPrincipalBackend(); - $backend->getGroupMembership($principal); - } - - public function providesPrincipalForGetGroupMembership() { - return [ - ['principals/system/a'], - ]; - } - - /** - * @throws \Sabre\DAV\Exception - */ - public function testGetGroupMembership() { - $backend = new SystemPrincipalBackend(); - $result = $backend->getGroupMembership('principals/system/system'); - $this->assertEquals([], $result); - } - - -} diff --git a/apps/dav/tests/unit/phpunit.xml b/apps/dav/tests/unit/phpunit.xml index 314855d863b..e483515ca7a 100644 --- a/apps/dav/tests/unit/phpunit.xml +++ b/apps/dav/tests/unit/phpunit.xml @@ -6,7 +6,7 @@ timeoutForLargeTests="900" > - . + . diff --git a/apps/dav/tests/unit/servertest.php b/apps/dav/tests/unit/servertest.php deleted file mode 100644 index b25da3cc807..00000000000 --- a/apps/dav/tests/unit/servertest.php +++ /dev/null @@ -1,43 +0,0 @@ - - * @author Thomas Müller - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\Unit; - -use OCA\DAV\Server; -use OCP\IRequest; - -/** - * Class ServerTest - * - * @group DB - * - * @package OCA\DAV\Tests\Unit - */ -class ServerTest extends \Test\TestCase { - - public function test() { - /** @var IRequest $r */ - $r = $this->getMockBuilder('\OCP\IRequest') - ->disableOriginalConstructor()->getMock(); - $s = new Server($r, '/'); - $this->assertNotNull($s->server); - } -} \ No newline at end of file diff --git a/apps/dav/tests/unit/systemtag/systemtagmappingnode.php b/apps/dav/tests/unit/systemtag/systemtagmappingnode.php deleted file mode 100644 index f0e1c3bc567..00000000000 --- a/apps/dav/tests/unit/systemtag/systemtagmappingnode.php +++ /dev/null @@ -1,160 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\SystemTag; - -use Sabre\DAV\Exception\NotFound; -use OC\SystemTag\SystemTag; -use OCP\SystemTag\TagNotFoundException; -use OCP\SystemTag\ISystemTag; - -class SystemTagMappingNode extends \Test\TestCase { - - /** - * @var \OCP\SystemTag\ISystemTagManager - */ - private $tagManager; - - /** - * @var \OCP\SystemTag\ISystemTagObjectMapper - */ - private $tagMapper; - - /** - * @var \OCP\IUser - */ - private $user; - - protected function setUp() { - parent::setUp(); - - $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); - $this->tagMapper = $this->getMock('\OCP\SystemTag\ISystemTagObjectMapper'); - $this->user = $this->getMock('\OCP\IUser'); - } - - public function getMappingNode($tag = null) { - if ($tag === null) { - $tag = new SystemTag(1, 'Test', true, true); - } - return new \OCA\DAV\SystemTag\SystemTagMappingNode( - $tag, - 123, - 'files', - $this->user, - $this->tagManager, - $this->tagMapper - ); - } - - public function testGetters() { - $tag = new SystemTag(1, 'Test', true, false); - $node = $this->getMappingNode($tag); - $this->assertEquals('1', $node->getName()); - $this->assertEquals($tag, $node->getSystemTag()); - $this->assertEquals(123, $node->getObjectId()); - $this->assertEquals('files', $node->getObjectType()); - } - - public function testDeleteTag() { - $node = $this->getMappingNode(); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($node->getSystemTag()) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->once()) - ->method('canUserAssignTag') - ->with($node->getSystemTag()) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->never()) - ->method('deleteTags'); - $this->tagMapper->expects($this->once()) - ->method('unassignTags') - ->with(123, 'files', 1); - - $node->delete(); - } - - public function tagNodeDeleteProviderPermissionException() { - return [ - [ - // cannot unassign invisible tag - new SystemTag(1, 'Original', false, true), - 'Sabre\DAV\Exception\NotFound', - ], - [ - // cannot unassign non-assignable tag - new SystemTag(1, 'Original', true, false), - 'Sabre\DAV\Exception\Forbidden', - ], - ]; - } - - /** - * @dataProvider tagNodeDeleteProviderPermissionException - */ - public function testDeleteTagExpectedException(ISystemTag $tag, $expectedException) { - $this->tagManager->expects($this->any()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue($tag->isUserVisible())); - $this->tagManager->expects($this->any()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue($tag->isUserAssignable())); - $this->tagManager->expects($this->never()) - ->method('deleteTags'); - $this->tagMapper->expects($this->never()) - ->method('unassignTags'); - - $thrown = null; - try { - $this->getMappingNode($tag)->delete(); - } catch (\Exception $e) { - $thrown = $e; - } - - $this->assertInstanceOf($expectedException, $thrown); - } - - /** - * @expectedException Sabre\DAV\Exception\NotFound - */ - public function testDeleteTagNotFound() { - // assuming the tag existed at the time the node was created, - // but got deleted concurrently in the database - $tag = new SystemTag(1, 'Test', true, true); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue($tag->isUserVisible())); - $this->tagManager->expects($this->once()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue($tag->isUserAssignable())); - $this->tagMapper->expects($this->once()) - ->method('unassignTags') - ->with(123, 'files', 1) - ->will($this->throwException(new TagNotFoundException())); - - $this->getMappingNode($tag)->delete(); - } -} diff --git a/apps/dav/tests/unit/systemtag/systemtagnode.php b/apps/dav/tests/unit/systemtag/systemtagnode.php deleted file mode 100644 index d9e088a7d90..00000000000 --- a/apps/dav/tests/unit/systemtag/systemtagnode.php +++ /dev/null @@ -1,312 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\SystemTag; - -use Sabre\DAV\Exception\NotFound; -use Sabre\DAV\Exception\MethodNotAllowed; -use Sabre\DAV\Exception\Conflict; - -use OC\SystemTag\SystemTag; -use OCP\SystemTag\TagNotFoundException; -use OCP\SystemTag\TagAlreadyExistsException; -use OCP\SystemTag\ISystemTag; - -class SystemTagNode extends \Test\TestCase { - - /** - * @var \OCP\SystemTag\ISystemTagManager - */ - private $tagManager; - - /** - * @var \OCP\IUser - */ - private $user; - - protected function setUp() { - parent::setUp(); - - $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); - $this->user = $this->getMock('\OCP\IUser'); - } - - protected function getTagNode($isAdmin = true, $tag = null) { - if ($tag === null) { - $tag = new SystemTag(1, 'Test', true, true); - } - return new \OCA\DAV\SystemTag\SystemTagNode( - $tag, - $this->user, - $isAdmin, - $this->tagManager - ); - } - - public function adminFlagProvider() { - return [[true], [false]]; - } - - /** - * @dataProvider adminFlagProvider - */ - public function testGetters($isAdmin) { - $tag = new SystemTag('1', 'Test', true, true); - $node = $this->getTagNode($isAdmin, $tag); - $this->assertEquals('1', $node->getName()); - $this->assertEquals($tag, $node->getSystemTag()); - } - - /** - * @expectedException Sabre\DAV\Exception\MethodNotAllowed - */ - public function testSetName() { - $this->getTagNode()->setName('2'); - } - - public function tagNodeProvider() { - return [ - // admin - [ - true, - new SystemTag(1, 'Original', true, true), - ['Renamed', true, true] - ], - [ - true, - new SystemTag(1, 'Original', true, true), - ['Original', false, false] - ], - // non-admin - [ - // renaming allowed - false, - new SystemTag(1, 'Original', true, true), - ['Rename', true, true] - ], - ]; - } - - /** - * @dataProvider tagNodeProvider - */ - public function testUpdateTag($isAdmin, $originalTag, $changedArgs) { - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($originalTag) - ->will($this->returnValue($originalTag->isUserVisible() || $isAdmin)); - $this->tagManager->expects($this->once()) - ->method('canUserAssignTag') - ->with($originalTag) - ->will($this->returnValue($originalTag->isUserAssignable() || $isAdmin)); - $this->tagManager->expects($this->once()) - ->method('updateTag') - ->with(1, $changedArgs[0], $changedArgs[1], $changedArgs[2]); - $this->getTagNode($isAdmin, $originalTag) - ->update($changedArgs[0], $changedArgs[1], $changedArgs[2]); - } - - public function tagNodeProviderPermissionException() { - return [ - [ - // changing permissions not allowed - new SystemTag(1, 'Original', true, true), - ['Original', false, true], - 'Sabre\DAV\Exception\Forbidden', - ], - [ - // changing permissions not allowed - new SystemTag(1, 'Original', true, true), - ['Original', true, false], - 'Sabre\DAV\Exception\Forbidden', - ], - [ - // changing permissions not allowed - new SystemTag(1, 'Original', true, true), - ['Original', false, false], - 'Sabre\DAV\Exception\Forbidden', - ], - [ - // changing non-assignable not allowed - new SystemTag(1, 'Original', true, false), - ['Rename', true, false], - 'Sabre\DAV\Exception\Forbidden', - ], - [ - // changing non-assignable not allowed - new SystemTag(1, 'Original', true, false), - ['Original', true, true], - 'Sabre\DAV\Exception\Forbidden', - ], - [ - // invisible tag does not exist - new SystemTag(1, 'Original', false, false), - ['Rename', false, false], - 'Sabre\DAV\Exception\NotFound', - ], - ]; - } - - /** - * @dataProvider tagNodeProviderPermissionException - */ - public function testUpdateTagPermissionException($originalTag, $changedArgs, $expectedException = null) { - $this->tagManager->expects($this->any()) - ->method('canUserSeeTag') - ->with($originalTag) - ->will($this->returnValue($originalTag->isUserVisible())); - $this->tagManager->expects($this->any()) - ->method('canUserAssignTag') - ->with($originalTag) - ->will($this->returnValue($originalTag->isUserAssignable())); - $this->tagManager->expects($this->never()) - ->method('updateTag'); - - $thrown = null; - - try { - $this->getTagNode(false, $originalTag) - ->update($changedArgs[0], $changedArgs[1], $changedArgs[2]); - } catch (\Exception $e) { - $thrown = $e; - } - - $this->assertInstanceOf($expectedException, $thrown); - } - - /** - * @expectedException Sabre\DAV\Exception\Conflict - */ - public function testUpdateTagAlreadyExists() { - $tag = new SystemTag(1, 'tag1', true, true); - $this->tagManager->expects($this->any()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->any()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->once()) - ->method('updateTag') - ->with(1, 'Renamed', true, true) - ->will($this->throwException(new TagAlreadyExistsException())); - $this->getTagNode(false, $tag)->update('Renamed', true, true); - } - - /** - * @expectedException Sabre\DAV\Exception\NotFound - */ - public function testUpdateTagNotFound() { - $tag = new SystemTag(1, 'tag1', true, true); - $this->tagManager->expects($this->any()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->any()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->once()) - ->method('updateTag') - ->with(1, 'Renamed', true, true) - ->will($this->throwException(new TagNotFoundException())); - $this->getTagNode(false, $tag)->update('Renamed', true, true); - } - - /** - * @dataProvider adminFlagProvider - */ - public function testDeleteTag($isAdmin) { - $tag = new SystemTag(1, 'tag1', true, true); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->once()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->once()) - ->method('deleteTags') - ->with('1'); - $this->getTagNode($isAdmin, $tag)->delete(); - } - - public function tagNodeDeleteProviderPermissionException() { - return [ - [ - // cannot delete invisible tag - new SystemTag(1, 'Original', false, true), - 'Sabre\DAV\Exception\NotFound', - ], - [ - // cannot delete non-assignable tag - new SystemTag(1, 'Original', true, false), - 'Sabre\DAV\Exception\Forbidden', - ], - ]; - } - - /** - * @dataProvider tagNodeDeleteProviderPermissionException - */ - public function testDeleteTagPermissionException(ISystemTag $tag, $expectedException) { - $this->tagManager->expects($this->any()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue($tag->isUserVisible())); - $this->tagManager->expects($this->any()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue($tag->isUserAssignable())); - $this->tagManager->expects($this->never()) - ->method('deleteTags'); - - try { - $this->getTagNode(false, $tag)->delete(); - } catch (\Exception $e) { - $thrown = $e; - } - - $this->assertInstanceOf($expectedException, $thrown); - } - - /** - * @expectedException Sabre\DAV\Exception\NotFound - */ - public function testDeleteTagNotFound() { - $tag = new SystemTag(1, 'tag1', true, true); - $this->tagManager->expects($this->any()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue($tag->isUserVisible())); - $this->tagManager->expects($this->any()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue($tag->isUserAssignable())); - $this->tagManager->expects($this->once()) - ->method('deleteTags') - ->with('1') - ->will($this->throwException(new TagNotFoundException())); - $this->getTagNode(false, $tag)->delete(); - } -} diff --git a/apps/dav/tests/unit/systemtag/systemtagplugin.php b/apps/dav/tests/unit/systemtag/systemtagplugin.php deleted file mode 100644 index da82bc8904a..00000000000 --- a/apps/dav/tests/unit/systemtag/systemtagplugin.php +++ /dev/null @@ -1,734 +0,0 @@ - - * @author Lukas Reschke - * @author Vincent Petry - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\SystemTag; - -use OC\SystemTag\SystemTag; -use OCP\IGroupManager; -use OCP\IUserSession; -use OCP\SystemTag\TagAlreadyExistsException; -use OCP\IUser; -use OCP\SystemTag\ISystemTag; - -class SystemTagPlugin extends \Test\TestCase { - - const ID_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::ID_PROPERTYNAME; - const DISPLAYNAME_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::DISPLAYNAME_PROPERTYNAME; - const USERVISIBLE_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::USERVISIBLE_PROPERTYNAME; - const USERASSIGNABLE_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::USERASSIGNABLE_PROPERTYNAME; - const CANASSIGN_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::CANASSIGN_PROPERTYNAME; - const GROUPS_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::GROUPS_PROPERTYNAME; - - /** - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var \Sabre\DAV\Tree - */ - private $tree; - - /** - * @var \OCP\SystemTag\ISystemTagManager - */ - private $tagManager; - - /** - * @var IGroupManager - */ - private $groupManager; - - /** - * @var IUserSession - */ - private $userSession; - - /** - * @var IUser - */ - private $user; - - /** - * @var \OCA\DAV\SystemTag\SystemTagPlugin - */ - private $plugin; - - public function setUp() { - parent::setUp(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') - ->disableOriginalConstructor() - ->getMock(); - - $this->server = new \Sabre\DAV\Server($this->tree); - - $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); - $this->groupManager = $this->getMock('\OCP\IGroupManager'); - $this->user = $this->getMock('\OCP\IUser'); - $this->userSession = $this->getMock('\OCP\IUserSession'); - $this->userSession - ->expects($this->any()) - ->method('getUser') - ->willReturn($this->user); - $this->userSession - ->expects($this->any()) - ->method('isLoggedIn') - ->willReturn(true); - - $this->plugin = new \OCA\DAV\SystemTag\SystemTagPlugin( - $this->tagManager, - $this->groupManager, - $this->userSession - ); - $this->plugin->initialize($this->server); - } - - public function getPropertiesDataProvider() { - return [ - [ - new SystemTag(1, 'Test', true, true), - [], - [ - self::ID_PROPERTYNAME, - self::DISPLAYNAME_PROPERTYNAME, - self::USERVISIBLE_PROPERTYNAME, - self::USERASSIGNABLE_PROPERTYNAME, - self::CANASSIGN_PROPERTYNAME, - ], - [ - self::ID_PROPERTYNAME => '1', - self::DISPLAYNAME_PROPERTYNAME => 'Test', - self::USERVISIBLE_PROPERTYNAME => 'true', - self::USERASSIGNABLE_PROPERTYNAME => 'true', - self::CANASSIGN_PROPERTYNAME => 'true', - ] - ], - [ - new SystemTag(1, 'Test', true, false), - [], - [ - self::ID_PROPERTYNAME, - self::DISPLAYNAME_PROPERTYNAME, - self::USERVISIBLE_PROPERTYNAME, - self::USERASSIGNABLE_PROPERTYNAME, - self::CANASSIGN_PROPERTYNAME, - ], - [ - self::ID_PROPERTYNAME => '1', - self::DISPLAYNAME_PROPERTYNAME => 'Test', - self::USERVISIBLE_PROPERTYNAME => 'true', - self::USERASSIGNABLE_PROPERTYNAME => 'false', - self::CANASSIGN_PROPERTYNAME => 'false', - ] - ], - [ - new SystemTag(1, 'Test', true, false), - ['group1', 'group2'], - [ - self::ID_PROPERTYNAME, - self::GROUPS_PROPERTYNAME, - ], - [ - self::ID_PROPERTYNAME => '1', - self::GROUPS_PROPERTYNAME => 'group1|group2', - ] - ], - [ - new SystemTag(1, 'Test', true, true), - ['group1', 'group2'], - [ - self::ID_PROPERTYNAME, - self::GROUPS_PROPERTYNAME, - ], - [ - self::ID_PROPERTYNAME => '1', - // groups only returned when userAssignable is false - self::GROUPS_PROPERTYNAME => '', - ] - ], - ]; - } - - /** - * @dataProvider getPropertiesDataProvider - */ - public function testGetProperties(ISystemTag $systemTag, $groups, $requestedProperties, $expectedProperties) { - $this->user->expects($this->any()) - ->method('getUID') - ->willReturn('admin'); - $this->groupManager - ->expects($this->any()) - ->method('isAdmin') - ->with('admin') - ->willReturn(true); - - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getSystemTag') - ->will($this->returnValue($systemTag)); - - $this->tagManager->expects($this->any()) - ->method('canUserAssignTag') - ->will($this->returnValue($systemTag->isUserAssignable())); - - $this->tagManager->expects($this->any()) - ->method('getTagGroups') - ->will($this->returnValue($groups)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtag/1') - ->will($this->returnValue($node)); - - $propFind = new \Sabre\DAV\PropFind( - '/systemtag/1', - $requestedProperties, - 0 - ); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - - $result = $propFind->getResultForMultiStatus(); - - $this->assertEmpty($result[404]); - $this->assertEquals($expectedProperties, $result[200]); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testGetPropertiesForbidden() { - $systemTag = new SystemTag(1, 'Test', true, false); - $requestedProperties = [ - self::ID_PROPERTYNAME, - self::GROUPS_PROPERTYNAME, - ]; - $this->user->expects($this->once()) - ->method('getUID') - ->willReturn('admin'); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('admin') - ->willReturn(false); - - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getSystemTag') - ->will($this->returnValue($systemTag)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtag/1') - ->will($this->returnValue($node)); - - $propFind = new \Sabre\DAV\PropFind( - '/systemtag/1', - $requestedProperties, - 0 - ); - - $this->plugin->handleGetProperties( - $propFind, - $node - ); - } - - public function testUpdatePropertiesAdmin() { - $systemTag = new SystemTag(1, 'Test', true, false); - $this->user->expects($this->any()) - ->method('getUID') - ->willReturn('admin'); - $this->groupManager - ->expects($this->any()) - ->method('isAdmin') - ->with('admin') - ->willReturn(true); - - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getSystemTag') - ->will($this->returnValue($systemTag)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtag/1') - ->will($this->returnValue($node)); - - $node->expects($this->once()) - ->method('update') - ->with('Test changed', false, true); - - $this->tagManager->expects($this->once()) - ->method('setTagGroups') - ->with($systemTag, ['group1', 'group2']); - - // properties to set - $propPatch = new \Sabre\DAV\PropPatch(array( - self::DISPLAYNAME_PROPERTYNAME => 'Test changed', - self::USERVISIBLE_PROPERTYNAME => 'false', - self::USERASSIGNABLE_PROPERTYNAME => 'true', - self::GROUPS_PROPERTYNAME => 'group1|group2', - )); - - $this->plugin->handleUpdateProperties( - '/systemtag/1', - $propPatch - ); - - $propPatch->commit(); - - // all requested properties removed, as they were processed already - $this->assertEmpty($propPatch->getRemainingMutations()); - - $result = $propPatch->getResult(); - $this->assertEquals(200, $result[self::DISPLAYNAME_PROPERTYNAME]); - $this->assertEquals(200, $result[self::USERASSIGNABLE_PROPERTYNAME]); - $this->assertEquals(200, $result[self::USERVISIBLE_PROPERTYNAME]); - } - - /** - * @expectedException \Sabre\DAV\Exception\Forbidden - */ - public function testUpdatePropertiesForbidden() { - $systemTag = new SystemTag(1, 'Test', true, false); - $this->user->expects($this->any()) - ->method('getUID') - ->willReturn('admin'); - $this->groupManager - ->expects($this->any()) - ->method('isAdmin') - ->with('admin') - ->willReturn(false); - - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagNode') - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getSystemTag') - ->will($this->returnValue($systemTag)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtag/1') - ->will($this->returnValue($node)); - - $node->expects($this->never()) - ->method('update'); - - $this->tagManager->expects($this->never()) - ->method('setTagGroups'); - - // properties to set - $propPatch = new \Sabre\DAV\PropPatch(array( - self::GROUPS_PROPERTYNAME => 'group1|group2', - )); - - $this->plugin->handleUpdateProperties( - '/systemtag/1', - $propPatch - ); - - $propPatch->commit(); - } - - public function createTagInsufficientPermissionsProvider() { - return [ - [true, false, ''], - [false, true, ''], - [true, true, 'group1|group2'], - ]; - } - /** - * @dataProvider createTagInsufficientPermissionsProvider - * @expectedException \Sabre\DAV\Exception\BadRequest - * @expectedExceptionMessage Not sufficient permissions - */ - public function testCreateNotAssignableTagAsRegularUser($userVisible, $userAssignable, $groups) { - $this->user->expects($this->once()) - ->method('getUID') - ->willReturn('admin'); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('admin') - ->willReturn(false); - - $requestData = [ - 'name' => 'Test', - 'userVisible' => $userVisible, - 'userAssignable' => $userAssignable, - ]; - if (!empty($groups)) { - $requestData['groups'] = $groups; - } - $requestData = json_encode($requestData); - - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') - ->disableOriginalConstructor() - ->getMock(); - $this->tagManager->expects($this->never()) - ->method('createTag'); - $this->tagManager->expects($this->never()) - ->method('setTagGroups'); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtags') - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/systemtags')); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $this->plugin->httpPost($request, $response); - } - - public function testCreateTagInByIdCollectionAsRegularUser() { - $systemTag = new SystemTag(1, 'Test', true, false); - - $requestData = json_encode([ - 'name' => 'Test', - 'userVisible' => true, - 'userAssignable' => true, - ]); - - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') - ->disableOriginalConstructor() - ->getMock(); - $this->tagManager->expects($this->once()) - ->method('createTag') - ->with('Test', true, true) - ->will($this->returnValue($systemTag)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtags') - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/systemtags')); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $request->expects($this->once()) - ->method('getUrl') - ->will($this->returnValue('http://example.com/dav/systemtags')); - - $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Location', 'http://example.com/dav/systemtags/1'); - - $this->plugin->httpPost($request, $response); - } - - public function createTagProvider() { - return [ - [true, false, ''], - [false, false, ''], - [true, false, 'group1|group2'], - ]; - } - - /** - * @dataProvider createTagProvider - */ - public function testCreateTagInByIdCollection($userVisible, $userAssignable, $groups) { - $this->user->expects($this->once()) - ->method('getUID') - ->willReturn('admin'); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('admin') - ->willReturn(true); - - $systemTag = new SystemTag(1, 'Test', true, false); - - $requestData = [ - 'name' => 'Test', - 'userVisible' => $userVisible, - 'userAssignable' => $userAssignable, - ]; - if (!empty($groups)) { - $requestData['groups'] = $groups; - } - $requestData = json_encode($requestData); - - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsByIdCollection') - ->disableOriginalConstructor() - ->getMock(); - $this->tagManager->expects($this->once()) - ->method('createTag') - ->with('Test', $userVisible, $userAssignable) - ->will($this->returnValue($systemTag)); - - if (!empty($groups)) { - $this->tagManager->expects($this->once()) - ->method('setTagGroups') - ->with($systemTag, explode('|', $groups)) - ->will($this->returnValue($systemTag)); - } else { - $this->tagManager->expects($this->never()) - ->method('setTagGroups'); - } - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtags') - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/systemtags')); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $request->expects($this->once()) - ->method('getUrl') - ->will($this->returnValue('http://example.com/dav/systemtags')); - - $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Location', 'http://example.com/dav/systemtags/1'); - - $this->plugin->httpPost($request, $response); - } - - public function nodeClassProvider() { - return [ - ['\OCA\DAV\SystemTag\SystemTagsByIdCollection'], - ['\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection'], - ]; - } - - public function testCreateTagInMappingCollection() { - $this->user->expects($this->once()) - ->method('getUID') - ->willReturn('admin'); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('admin') - ->willReturn(true); - - $systemTag = new SystemTag(1, 'Test', true, false); - - $requestData = json_encode([ - 'name' => 'Test', - 'userVisible' => true, - 'userAssignable' => false, - ]); - - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection') - ->disableOriginalConstructor() - ->getMock(); - - $this->tagManager->expects($this->once()) - ->method('createTag') - ->with('Test', true, false) - ->will($this->returnValue($systemTag)); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtags-relations/files/12') - ->will($this->returnValue($node)); - - $node->expects($this->once()) - ->method('createFile') - ->with(1); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/systemtags-relations/files/12')); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $request->expects($this->once()) - ->method('getBaseUrl') - ->will($this->returnValue('http://example.com/dav/')); - - $response->expects($this->once()) - ->method('setHeader') - ->with('Content-Location', 'http://example.com/dav/systemtags/1'); - - $this->plugin->httpPost($request, $response); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotFound - */ - public function testCreateTagToUnknownNode() { - $node = $this->getMockBuilder('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection') - ->disableOriginalConstructor() - ->getMock(); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); - - $this->tagManager->expects($this->never()) - ->method('createTag'); - - $node->expects($this->never()) - ->method('createFile'); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/systemtags-relations/files/12')); - - $this->plugin->httpPost($request, $response); - } - - /** - * @dataProvider nodeClassProvider - * @expectedException \Sabre\DAV\Exception\Conflict - */ - public function testCreateTagConflict($nodeClass) { - $this->user->expects($this->once()) - ->method('getUID') - ->willReturn('admin'); - $this->groupManager - ->expects($this->once()) - ->method('isAdmin') - ->with('admin') - ->willReturn(true); - - $requestData = json_encode([ - 'name' => 'Test', - 'userVisible' => true, - 'userAssignable' => false, - ]); - - $node = $this->getMockBuilder($nodeClass) - ->disableOriginalConstructor() - ->getMock(); - $this->tagManager->expects($this->once()) - ->method('createTag') - ->with('Test', true, false) - ->will($this->throwException(new TagAlreadyExistsException('Tag already exists'))); - - $this->tree->expects($this->any()) - ->method('getNodeForPath') - ->with('/systemtags') - ->will($this->returnValue($node)); - - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder('Sabre\HTTP\ResponseInterface') - ->disableOriginalConstructor() - ->getMock(); - - $request->expects($this->once()) - ->method('getPath') - ->will($this->returnValue('/systemtags')); - - $request->expects($this->once()) - ->method('getBodyAsString') - ->will($this->returnValue($requestData)); - - $request->expects($this->once()) - ->method('getHeader') - ->with('Content-Type') - ->will($this->returnValue('application/json')); - - $this->plugin->httpPost($request, $response); - } - -} diff --git a/apps/dav/tests/unit/systemtag/systemtagsbyidcollection.php b/apps/dav/tests/unit/systemtag/systemtagsbyidcollection.php deleted file mode 100644 index 5aa28d1a254..00000000000 --- a/apps/dav/tests/unit/systemtag/systemtagsbyidcollection.php +++ /dev/null @@ -1,233 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\SystemTag; - - -use OC\SystemTag\SystemTag; -use OCP\SystemTag\TagNotFoundException; - -class SystemTagsByIdCollection extends \Test\TestCase { - - /** - * @var \OCP\SystemTag\ISystemTagManager - */ - private $tagManager; - - /** - * @var \OCP\IUser - */ - private $user; - - protected function setUp() { - parent::setUp(); - - $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); - } - - public function getNode($isAdmin = true) { - $this->user = $this->getMock('\OCP\IUser'); - $this->user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('testuser')); - $userSession = $this->getMock('\OCP\IUserSession'); - $userSession->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($this->user)); - $groupManager = $this->getMock('\OCP\IGroupManager'); - $groupManager->expects($this->any()) - ->method('isAdmin') - ->with('testuser') - ->will($this->returnValue($isAdmin)); - return new \OCA\DAV\SystemTag\SystemTagsByIdCollection( - $this->tagManager, - $userSession, - $groupManager - ); - } - - public function adminFlagProvider() { - return [[true], [false]]; - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testForbiddenCreateFile() { - $this->getNode()->createFile('555'); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testForbiddenCreateDirectory() { - $this->getNode()->createDirectory('789'); - } - - public function testGetChild() { - $tag = new SystemTag(123, 'Test', true, false); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue(true)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['123']) - ->will($this->returnValue([$tag])); - - $childNode = $this->getNode()->getChild('123'); - - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $childNode); - $this->assertEquals('123', $childNode->getName()); - $this->assertEquals($tag, $childNode->getSystemTag()); - } - - /** - * @expectedException Sabre\DAV\Exception\BadRequest - */ - public function testGetChildInvalidName() { - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['invalid']) - ->will($this->throwException(new \InvalidArgumentException())); - - $this->getNode()->getChild('invalid'); - } - - /** - * @expectedException Sabre\DAV\Exception\NotFound - */ - public function testGetChildNotFound() { - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['444']) - ->will($this->throwException(new TagNotFoundException())); - - $this->getNode()->getChild('444'); - } - - /** - * @expectedException Sabre\DAV\Exception\NotFound - */ - public function testGetChildUserNotVisible() { - $tag = new SystemTag(123, 'Test', false, false); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['123']) - ->will($this->returnValue([$tag])); - - $this->getNode(false)->getChild('123'); - } - - public function testGetChildrenAdmin() { - $tag1 = new SystemTag(123, 'One', true, false); - $tag2 = new SystemTag(456, 'Two', true, true); - - $this->tagManager->expects($this->once()) - ->method('getAllTags') - ->with(null) - ->will($this->returnValue([$tag1, $tag2])); - - $children = $this->getNode(true)->getChildren(); - - $this->assertCount(2, $children); - - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); - $this->assertEquals($tag1, $children[0]->getSystemTag()); - $this->assertEquals($tag2, $children[1]->getSystemTag()); - } - - public function testGetChildrenNonAdmin() { - $tag1 = new SystemTag(123, 'One', true, false); - $tag2 = new SystemTag(456, 'Two', true, true); - - $this->tagManager->expects($this->once()) - ->method('getAllTags') - ->with(true) - ->will($this->returnValue([$tag1, $tag2])); - - $children = $this->getNode(false)->getChildren(); - - $this->assertCount(2, $children); - - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); - $this->assertEquals($tag1, $children[0]->getSystemTag()); - $this->assertEquals($tag2, $children[1]->getSystemTag()); - } - - public function testGetChildrenEmpty() { - $this->tagManager->expects($this->once()) - ->method('getAllTags') - ->with(null) - ->will($this->returnValue([])); - $this->assertCount(0, $this->getNode()->getChildren()); - } - - public function childExistsProvider() { - return [ - [true, true], - [false, false], - ]; - } - - /** - * @dataProvider childExistsProvider - */ - public function testChildExists($userVisible, $expectedResult) { - $tag = new SystemTag(123, 'One', $userVisible, false); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue($userVisible)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['123']) - ->will($this->returnValue([$tag])); - - $this->assertEquals($expectedResult, $this->getNode()->childExists('123')); - } - - public function testChildExistsNotFound() { - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['123']) - ->will($this->throwException(new TagNotFoundException())); - - $this->assertFalse($this->getNode()->childExists('123')); - } - - /** - * @expectedException Sabre\DAV\Exception\BadRequest - */ - public function testChildExistsBadRequest() { - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['invalid']) - ->will($this->throwException(new \InvalidArgumentException())); - - $this->getNode()->childExists('invalid'); - } -} diff --git a/apps/dav/tests/unit/systemtag/systemtagsobjectmappingcollection.php b/apps/dav/tests/unit/systemtag/systemtagsobjectmappingcollection.php deleted file mode 100644 index 9adc5b88c41..00000000000 --- a/apps/dav/tests/unit/systemtag/systemtagsobjectmappingcollection.php +++ /dev/null @@ -1,348 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\SystemTag; - - -use OC\SystemTag\SystemTag; -use OCP\SystemTag\TagNotFoundException; - -class SystemTagsObjectMappingCollection extends \Test\TestCase { - - /** - * @var \OCP\SystemTag\ISystemTagManager - */ - private $tagManager; - - /** - * @var \OCP\SystemTag\ISystemTagMapper - */ - private $tagMapper; - - /** - * @var \OCP\IUser - */ - private $user; - - protected function setUp() { - parent::setUp(); - - $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); - $this->tagMapper = $this->getMock('\OCP\SystemTag\ISystemTagObjectMapper'); - - $this->user = $this->getMock('\OCP\IUser'); - } - - public function getNode() { - return new \OCA\DAV\SystemTag\SystemTagsObjectMappingCollection ( - 111, - 'files', - $this->user, - $this->tagManager, - $this->tagMapper - ); - } - - public function testAssignTag() { - $tag = new SystemTag('1', 'Test', true, true); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue(true)); - $this->tagManager->expects($this->once()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue(true)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['555']) - ->will($this->returnValue([$tag])); - $this->tagMapper->expects($this->once()) - ->method('assignTags') - ->with(111, 'files', '555'); - - $this->getNode()->createFile('555'); - } - - public function permissionsProvider() { - return [ - // invisible, tag does not exist for user - [false, true, '\Sabre\DAV\Exception\PreconditionFailed'], - // visible but static, cannot assign tag - [true, false, '\Sabre\DAV\Exception\Forbidden'], - ]; - } - - /** - * @dataProvider permissionsProvider - */ - public function testAssignTagNoPermission($userVisible, $userAssignable, $expectedException) { - $tag = new SystemTag('1', 'Test', $userVisible, $userAssignable); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue($userVisible)); - $this->tagManager->expects($this->any()) - ->method('canUserAssignTag') - ->with($tag) - ->will($this->returnValue($userAssignable)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['555']) - ->will($this->returnValue([$tag])); - $this->tagMapper->expects($this->never()) - ->method('assignTags'); - - $thrown = null; - try { - $this->getNode()->createFile('555'); - } catch (\Exception $e) { - $thrown = $e; - } - - $this->assertInstanceOf($expectedException, $thrown); - } - - /** - * @expectedException Sabre\DAV\Exception\PreconditionFailed - */ - public function testAssignTagNotFound() { - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['555']) - ->will($this->throwException(new TagNotFoundException())); - - $this->getNode()->createFile('555'); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testForbiddenCreateDirectory() { - $this->getNode()->createDirectory('789'); - } - - public function testGetChild() { - $tag = new SystemTag(555, 'TheTag', true, false); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue(true)); - - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '555', true) - ->will($this->returnValue(true)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['555']) - ->will($this->returnValue(['555' => $tag])); - - $childNode = $this->getNode()->getChild('555'); - - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $childNode); - $this->assertEquals('555', $childNode->getName()); - } - - /** - * @expectedException \Sabre\DAV\Exception\NotFound - */ - public function testGetChildNonVisible() { - $tag = new SystemTag(555, 'TheTag', false, false); - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue(false)); - - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '555', true) - ->will($this->returnValue(true)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['555']) - ->will($this->returnValue(['555' => $tag])); - - $this->getNode()->getChild('555'); - } - - /** - * @expectedException Sabre\DAV\Exception\NotFound - */ - public function testGetChildRelationNotFound() { - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '777') - ->will($this->returnValue(false)); - - $this->getNode()->getChild('777'); - } - - /** - * @expectedException Sabre\DAV\Exception\BadRequest - */ - public function testGetChildInvalidId() { - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', 'badid') - ->will($this->throwException(new \InvalidArgumentException())); - - $this->getNode()->getChild('badid'); - } - - /** - * @expectedException Sabre\DAV\Exception\NotFound - */ - public function testGetChildTagDoesNotExist() { - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '777') - ->will($this->throwException(new TagNotFoundException())); - - $this->getNode()->getChild('777'); - } - - public function testGetChildren() { - $tag1 = new SystemTag(555, 'TagOne', true, false); - $tag2 = new SystemTag(556, 'TagTwo', true, true); - $tag3 = new SystemTag(557, 'InvisibleTag', false, true); - - $this->tagMapper->expects($this->once()) - ->method('getTagIdsForObjects') - ->with([111], 'files') - ->will($this->returnValue(['111' => ['555', '556', '557']])); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['555', '556', '557']) - ->will($this->returnValue(['555' => $tag1, '556' => $tag2, '557' => $tag3])); - - $this->tagManager->expects($this->exactly(3)) - ->method('canUserSeeTag') - ->will($this->returnCallback(function($tag) { - return $tag->isUserVisible(); - })); - - $children = $this->getNode()->getChildren(); - - $this->assertCount(2, $children); - - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $children[1]); - - $this->assertEquals(111, $children[0]->getObjectId()); - $this->assertEquals('files', $children[0]->getObjectType()); - $this->assertEquals($tag1, $children[0]->getSystemTag()); - - $this->assertEquals(111, $children[1]->getObjectId()); - $this->assertEquals('files', $children[1]->getObjectType()); - $this->assertEquals($tag2, $children[1]->getSystemTag()); - } - - public function testChildExistsWithVisibleTag() { - $tag = new SystemTag(555, 'TagOne', true, false); - - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '555') - ->will($this->returnValue(true)); - - $this->tagManager->expects($this->once()) - ->method('canUserSeeTag') - ->with($tag) - ->will($this->returnValue(true)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['555']) - ->will($this->returnValue([$tag])); - - $this->assertTrue($this->getNode()->childExists('555')); - } - - public function testChildExistsWithInvisibleTag() { - $tag = new SystemTag(555, 'TagOne', false, false); - - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '555') - ->will($this->returnValue(true)); - - $this->tagManager->expects($this->once()) - ->method('getTagsByIds') - ->with(['555']) - ->will($this->returnValue([$tag])); - - $this->assertFalse($this->getNode()->childExists('555')); - } - - public function testChildExistsNotFound() { - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '555') - ->will($this->returnValue(false)); - - $this->assertFalse($this->getNode()->childExists('555')); - } - - public function testChildExistsTagNotFound() { - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '555') - ->will($this->throwException(new TagNotFoundException())); - - $this->assertFalse($this->getNode()->childExists('555')); - } - - /** - * @expectedException Sabre\DAV\Exception\BadRequest - */ - public function testChildExistsInvalidId() { - $this->tagMapper->expects($this->once()) - ->method('haveTag') - ->with([111], 'files', '555') - ->will($this->throwException(new \InvalidArgumentException())); - - $this->getNode()->childExists('555'); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testDelete() { - $this->getNode()->delete(); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testSetName() { - $this->getNode()->setName('somethingelse'); - } - - public function testGetName() { - $this->assertEquals('111', $this->getNode()->getName()); - } -} diff --git a/apps/dav/tests/unit/systemtag/systemtagsobjecttypecollection.php b/apps/dav/tests/unit/systemtag/systemtagsobjecttypecollection.php deleted file mode 100644 index 1d4264f94f9..00000000000 --- a/apps/dav/tests/unit/systemtag/systemtagsobjecttypecollection.php +++ /dev/null @@ -1,160 +0,0 @@ - - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see - * - */ - -namespace OCA\DAV\Tests\Unit\SystemTag; - -class SystemTagsObjectTypeCollection extends \Test\TestCase { - - /** - * @var \OCA\DAV\SystemTag\SystemTagsObjectTypeCollection - */ - private $node; - - /** - * @var \OCP\SystemTag\ISystemTagManager - */ - private $tagManager; - - /** - * @var \OCP\SystemTag\ISystemTagMapper - */ - private $tagMapper; - - /** - * @var \OCP\Files\Folder - */ - private $userFolder; - - protected function setUp() { - parent::setUp(); - - $this->tagManager = $this->getMock('\OCP\SystemTag\ISystemTagManager'); - $this->tagMapper = $this->getMock('\OCP\SystemTag\ISystemTagObjectMapper'); - - $user = $this->getMock('\OCP\IUser'); - $user->expects($this->any()) - ->method('getUID') - ->will($this->returnValue('testuser')); - $userSession = $this->getMock('\OCP\IUserSession'); - $userSession->expects($this->any()) - ->method('getUser') - ->will($this->returnValue($user)); - $groupManager = $this->getMock('\OCP\IGroupManager'); - $groupManager->expects($this->any()) - ->method('isAdmin') - ->with('testuser') - ->will($this->returnValue(true)); - - $this->userFolder = $this->getMock('\OCP\Files\Folder'); - - $fileRoot = $this->getMock('\OCP\Files\IRootFolder'); - $fileRoot->expects($this->any()) - ->method('getUserfolder') - ->with('testuser') - ->will($this->returnValue($this->userFolder)); - - $this->node = new \OCA\DAV\SystemTag\SystemTagsObjectTypeCollection( - 'files', - $this->tagManager, - $this->tagMapper, - $userSession, - $groupManager, - $fileRoot - ); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testForbiddenCreateFile() { - $this->node->createFile('555'); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testForbiddenCreateDirectory() { - $this->node->createDirectory('789'); - } - - public function testGetChild() { - $this->userFolder->expects($this->once()) - ->method('getById') - ->with('555') - ->will($this->returnValue([true])); - $childNode = $this->node->getChild('555'); - - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection', $childNode); - $this->assertEquals('555', $childNode->getName()); - } - - /** - * @expectedException Sabre\DAV\Exception\NotFound - */ - public function testGetChildWithoutAccess() { - $this->userFolder->expects($this->once()) - ->method('getById') - ->with('555') - ->will($this->returnValue([])); - $this->node->getChild('555'); - } - - /** - * @expectedException Sabre\DAV\Exception\MethodNotAllowed - */ - public function testGetChildren() { - $this->node->getChildren(); - } - - public function testChildExists() { - $this->userFolder->expects($this->once()) - ->method('getById') - ->with('123') - ->will($this->returnValue([true])); - $this->assertTrue($this->node->childExists('123')); - } - - public function testChildExistsWithoutAccess() { - $this->userFolder->expects($this->once()) - ->method('getById') - ->with('555') - ->will($this->returnValue([])); - $this->assertFalse($this->node->childExists('555')); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testDelete() { - $this->node->delete(); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testSetName() { - $this->node->setName('somethingelse'); - } - - public function testGetName() { - $this->assertEquals('files', $this->node->getName()); - } -} diff --git a/apps/dav/tests/unit/upload/assemblystreamtest.php b/apps/dav/tests/unit/upload/assemblystreamtest.php deleted file mode 100644 index 373d525a9dd..00000000000 --- a/apps/dav/tests/unit/upload/assemblystreamtest.php +++ /dev/null @@ -1,47 +0,0 @@ -assertEquals($expected, $content); - } - - function providesNodes() { - return[ - 'one node only' => ['1234567890', [ - $this->buildNode('0', '1234567890') - ]], - 'two nodes' => ['1234567890', [ - $this->buildNode('1', '67890'), - $this->buildNode('0', '12345') - ]] - ]; - } - - private function buildNode($name, $data) { - $node = $this->getMockBuilder('\Sabre\DAV\File') - ->setMethods(['getName', 'get', 'getSize']) - ->getMockForAbstractClass(); - - $node->expects($this->any()) - ->method('getName') - ->willReturn($name); - - $node->expects($this->any()) - ->method('get') - ->willReturn($data); - - $node->expects($this->any()) - ->method('getSize') - ->willReturn(strlen($data)); - - return $node; - } -} - diff --git a/apps/dav/tests/unit/upload/futurefiletest.php b/apps/dav/tests/unit/upload/futurefiletest.php deleted file mode 100644 index c0c14bf04d7..00000000000 --- a/apps/dav/tests/unit/upload/futurefiletest.php +++ /dev/null @@ -1,89 +0,0 @@ -mockFutureFile(); - $this->assertEquals('application/octet-stream', $f->getContentType()); - } - - public function testGetETag() { - $f = $this->mockFutureFile(); - $this->assertEquals('1234567890', $f->getETag()); - } - - public function testGetName() { - $f = $this->mockFutureFile(); - $this->assertEquals('foo.txt', $f->getName()); - } - - public function testGetLastModified() { - $f = $this->mockFutureFile(); - $this->assertEquals(12121212, $f->getLastModified()); - } - - public function testGetSize() { - $f = $this->mockFutureFile(); - $this->assertEquals(0, $f->getSize()); - } - - public function testGet() { - $f = $this->mockFutureFile(); - $stream = $f->get(); - $this->assertTrue(is_resource($stream)); - } - - public function testDelete() { - $d = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->setMethods(['delete']) - ->getMock(); - - $d->expects($this->once()) - ->method('delete'); - - $f = new \OCA\DAV\Upload\FutureFile($d, 'foo.txt'); - $f->delete(); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testPut() { - $f = $this->mockFutureFile(); - $f->put(''); - } - - /** - * @expectedException Sabre\DAV\Exception\Forbidden - */ - public function testSetName() { - $f = $this->mockFutureFile(); - $f->setName(''); - } - - /** - * @return \OCA\DAV\Upload\FutureFile - */ - private function mockFutureFile() { - $d = $this->getMockBuilder('OCA\DAV\Connector\Sabre\Directory') - ->disableOriginalConstructor() - ->setMethods(['getETag', 'getLastModified', 'getChildren']) - ->getMock(); - - $d->expects($this->any()) - ->method('getETag') - ->willReturn('1234567890'); - - $d->expects($this->any()) - ->method('getLastModified') - ->willReturn(12121212); - - $d->expects($this->any()) - ->method('getChildren') - ->willReturn([]); - - return new \OCA\DAV\Upload\FutureFile($d, 'foo.txt'); - } -} - -- cgit v1.2.3