summaryrefslogtreecommitdiffstats
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/core/avatar/avatarcontrollertest.php22
-rw-r--r--tests/core/command/config/listconfigstest.php17
-rw-r--r--tests/core/command/log/managetest.php181
-rw-r--r--tests/core/command/log/owncloudtest.php121
-rw-r--r--tests/data/setUploadLimit/htaccess60
-rw-r--r--tests/data/setUploadLimit/user.ini7
-rw-r--r--tests/lib/activitymanager.php197
-rw-r--r--tests/lib/app/manager.php70
-rw-r--r--tests/lib/backgroundjob/joblist.php26
-rw-r--r--tests/lib/connector/sabre/requesttest/requesttest.php50
-rw-r--r--tests/lib/files.php135
-rw-r--r--tests/lib/files/mount/mountpoint.php21
-rw-r--r--tests/lib/testcase.php33
-rw-r--r--tests/lib/traits/mountprovidertrait.php56
-rw-r--r--tests/lib/traits/usertrait.php32
-rw-r--r--tests/settings/controller/userscontrollertest.php18
16 files changed, 964 insertions, 82 deletions
diff --git a/tests/core/avatar/avatarcontrollertest.php b/tests/core/avatar/avatarcontrollertest.php
index 952e013bb8f..e8fb977fae1 100644
--- a/tests/core/avatar/avatarcontrollertest.php
+++ b/tests/core/avatar/avatarcontrollertest.php
@@ -26,6 +26,8 @@ use OCP\AppFramework\IAppContainer;
use OC\Files\Filesystem;
use OCP\AppFramework\Http;
use OCP\Image;
+use OCP\Files\Folder;
+use OCP\Files\File;
/**
* Overwrite is_uploaded_file in this namespace to allow proper unit testing of
@@ -72,6 +74,8 @@ class AvatarControllerTest extends \Test\TestCase {
->disableOriginalConstructor()->getMock();
$this->container['Request'] = $this->getMockBuilder('OCP\IRequest')
->disableOriginalConstructor()->getMock();
+ $this->container['UserFolder'] = $this->getMockBuilder('OCP\Files\Folder')
+ ->disableOriginalConstructor()->getMock();
$this->avatarMock = $this->getMockBuilder('OCP\IAvatar')
->disableOriginalConstructor()->getMock();
@@ -89,10 +93,6 @@ class AvatarControllerTest extends \Test\TestCase {
OC::$server->getUserManager()->createUser($this->user, $this->user);
$this->loginAsUser($this->user);
- // Create Cache dir
- $view = new \OC\Files\View('/'.$this->user);
- $view->mkdir('cache');
-
// Configure userMock
$this->userMock->method('getDisplayName')->willReturn($this->user);
$this->userMock->method('getUID')->willReturn($this->user);
@@ -259,8 +259,7 @@ class AvatarControllerTest extends \Test\TestCase {
$this->assertTrue($copyRes);
//Create file in cache
- $view = new \OC\Files\View('/'.$this->user.'/cache');
- $view->file_put_contents('avatar_upload', file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ $this->container['Cache']->method('get')->willReturn(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg'));
//Create request return
$reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => [filesize(OC::$SERVERROOT.'/tests/data/testimage.jpg')]];
@@ -298,8 +297,7 @@ class AvatarControllerTest extends \Test\TestCase {
$this->assertTrue($copyRes);
//Create file in cache
- $view = new \OC\Files\View('/'.$this->user.'/cache');
- $view->file_put_contents('avatar_upload', file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'));
+ $this->container['Cache']->method('get')->willReturn(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.gif'));
//Create request return
$reqRet = ['error' => [0], 'tmp_name' => [$fileName], 'size' => filesize(OC::$SERVERROOT.'/tests/data/testimage.gif')];
@@ -317,9 +315,11 @@ class AvatarControllerTest extends \Test\TestCase {
* Test posting avatar from existing file
*/
public function testPostAvatarFromFile() {
- //Create file in cache
- $view = new \OC\Files\View('/'.$this->user.'/files');
- $view->file_put_contents('avatar.jpg', file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ //Mock node API call
+ $file = $this->getMockBuilder('OCP\Files\File')
+ ->disableOriginalConstructor()->getMock();
+ $file->method('getContent')->willReturn(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg'));
+ $this->container['UserFolder']->method('get')->willReturn($file);
//Create request return
$response = $this->avatarController->postAvatar('avatar.jpg');
diff --git a/tests/core/command/config/listconfigstest.php b/tests/core/command/config/listconfigstest.php
index c9913d83f7f..7492701cce3 100644
--- a/tests/core/command/config/listconfigstest.php
+++ b/tests/core/command/config/listconfigstest.php
@@ -81,6 +81,7 @@ class ListConfigsTest extends TestCase {
false,
json_encode([
'system' => [
+ 'secret' => ListConfigs::SENSITIVE_VALUE,
'overwrite.cli.url' => 'http://localhost',
],
'apps' => [
@@ -134,10 +135,18 @@ class ListConfigsTest extends TestCase {
// config.php
[
'secret',
+ 'objectstore',
'overwrite.cli.url',
],
[
['secret', 'N;', 'my secret'],
+ ['objectstore', 'N;', [
+ 'class' => 'OC\\Files\\ObjectStore\\Swift',
+ 'arguments' => [
+ 'username' => 'facebook100000123456789',
+ 'password' => 'Secr3tPaSSWoRdt7',
+ ],
+ ]],
['overwrite.cli.url', 'N;', 'http://localhost'],
],
// app config
@@ -152,6 +161,14 @@ class ListConfigsTest extends TestCase {
false,
json_encode([
'system' => [
+ 'secret' => ListConfigs::SENSITIVE_VALUE,
+ 'objectstore' => [
+ 'class' => 'OC\\Files\\ObjectStore\\Swift',
+ 'arguments' => [
+ 'username' => 'facebook100000123456789',
+ 'password' => ListConfigs::SENSITIVE_VALUE,
+ ],
+ ],
'overwrite.cli.url' => 'http://localhost',
],
]),
diff --git a/tests/core/command/log/managetest.php b/tests/core/command/log/managetest.php
new file mode 100644
index 00000000000..6fb83347f23
--- /dev/null
+++ b/tests/core/command/log/managetest.php
@@ -0,0 +1,181 @@
+<?php
+/**
+ * @author Robin McCorkell <rmccorkell@owncloud.com>
+ *
+ * @copyright Copyright (c) 2015, ownCloud, Inc.
+ * @license AGPL-3.0
+ *
+ * This code is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, version 3,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License, version 3,
+ * along with this program. If not, see <http://www.gnu.org/licenses/>
+ *
+ */
+
+namespace Tests\Core\Command\Log;
+
+
+use OC\Core\Command\Log\Manage;
+use Test\TestCase;
+
+class ManageTest extends TestCase {
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $config;
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $consoleInput;
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $consoleOutput;
+
+ /** @var \Symfony\Component\Console\Command\Command */
+ protected $command;
+
+ protected function setUp() {
+ parent::setUp();
+
+ $config = $this->config = $this->getMockBuilder('OCP\IConfig')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->consoleInput = $this->getMock('Symfony\Component\Console\Input\InputInterface');
+ $this->consoleOutput = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
+
+ $this->command = new Manage($config);
+ }
+
+ public function testChangeBackend() {
+ $this->consoleInput->method('getOption')
+ ->will($this->returnValueMap([
+ ['backend', 'syslog']
+ ]));
+ $this->config->expects($this->once())
+ ->method('setSystemValue')
+ ->with('log_type', 'syslog');
+
+ self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
+ }
+
+ public function testChangeLevel() {
+ $this->consoleInput->method('getOption')
+ ->will($this->returnValueMap([
+ ['level', 'debug']
+ ]));
+ $this->config->expects($this->once())
+ ->method('setSystemValue')
+ ->with('loglevel', 0);
+
+ self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
+ }
+
+ public function testChangeTimezone() {
+ $this->consoleInput->method('getOption')
+ ->will($this->returnValueMap([
+ ['timezone', 'UTC']
+ ]));
+ $this->config->expects($this->once())
+ ->method('setSystemValue')
+ ->with('logtimezone', 'UTC');
+
+ self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
+ }
+
+ /**
+ * @expectedException \InvalidArgumentException
+ */
+ public function testValidateBackend() {
+ self::invokePrivate($this->command, 'validateBackend', ['notabackend']);
+ }
+
+ /**
+ * @expectedException \Exception
+ */
+ public function testValidateTimezone() {
+ // this might need to be changed when humanity colonises Mars
+ self::invokePrivate($this->command, 'validateTimezone', ['Mars/OlympusMons']);
+ }
+
+ public function convertLevelStringProvider() {
+ return [
+ ['dEbug', 0],
+ ['inFO', 1],
+ ['Warning', 2],
+ ['wArn', 2],
+ ['error', 3],
+ ['eRr', 3],
+ ];
+ }
+
+ /**
+ * @dataProvider convertLevelStringProvider
+ */
+ public function testConvertLevelString($levelString, $expectedInt) {
+ $this->assertEquals($expectedInt,
+ self::invokePrivate($this->command, 'convertLevelString', [$levelString])
+ );
+ }
+
+ /**
+ * @expectedException \InvalidArgumentException
+ */
+ public function testConvertLevelStringInvalid() {
+ self::invokePrivate($this->command, 'convertLevelString', ['abc']);
+ }
+
+ public function convertLevelNumberProvider() {
+ return [
+ [0, 'Debug'],
+ [1, 'Info'],
+ [2, 'Warning'],
+ [3, 'Error'],
+ ];
+ }
+
+ /**
+ * @dataProvider convertLevelNumberProvider
+ */
+ public function testConvertLevelNumber($levelNum, $expectedString) {
+ $this->assertEquals($expectedString,
+ self::invokePrivate($this->command, 'convertLevelNumber', [$levelNum])
+ );
+ }
+
+ /**
+ * @expectedException \InvalidArgumentException
+ */
+ public function testConvertLevelNumberInvalid() {
+ self::invokePrivate($this->command, 'convertLevelNumber', [11]);
+ }
+
+ public function testGetConfiguration() {
+ $this->config->expects($this->at(0))
+ ->method('getSystemValue')
+ ->with('log_type', 'owncloud')
+ ->willReturn('log_type_value');
+ $this->config->expects($this->at(1))
+ ->method('getSystemValue')
+ ->with('loglevel', 2)
+ ->willReturn(0);
+ $this->config->expects($this->at(2))
+ ->method('getSystemValue')
+ ->with('logtimezone', 'UTC')
+ ->willReturn('logtimezone_value');
+
+ $this->consoleOutput->expects($this->at(0))
+ ->method('writeln')
+ ->with('Enabled logging backend: log_type_value');
+ $this->consoleOutput->expects($this->at(1))
+ ->method('writeln')
+ ->with('Log level: Debug (0)');
+ $this->consoleOutput->expects($this->at(2))
+ ->method('writeln')
+ ->with('Log timezone: logtimezone_value');
+
+ self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
+ }
+
+}
diff --git a/tests/core/command/log/owncloudtest.php b/tests/core/command/log/owncloudtest.php
new file mode 100644
index 00000000000..3cb05221c37
--- /dev/null
+++ b/tests/core/command/log/owncloudtest.php
@@ -0,0 +1,121 @@
+<?php
+/**
+ * @author Robin McCorkell <rmccorkell@owncloud.com>
+ *
+ * @copyright Copyright (c) 2015, ownCloud, Inc.
+ * @license AGPL-3.0
+ *
+ * This code is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, version 3,
+ * as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License, version 3,
+ * along with this program. If not, see <http://www.gnu.org/licenses/>
+ *
+ */
+
+namespace Tests\Core\Command\Log;
+
+
+use OC\Core\Command\Log\OwnCloud;
+use Test\TestCase;
+
+class OwnCloudTest extends TestCase {
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $config;
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $consoleInput;
+ /** @var \PHPUnit_Framework_MockObject_MockObject */
+ protected $consoleOutput;
+
+ /** @var \Symfony\Component\Console\Command\Command */
+ protected $command;
+
+ protected function setUp() {
+ parent::setUp();
+
+ $config = $this->config = $this->getMockBuilder('OCP\IConfig')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $this->consoleInput = $this->getMock('Symfony\Component\Console\Input\InputInterface');
+ $this->consoleOutput = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
+
+ $this->command = new OwnCloud($config);
+ }
+
+ public function testEnable() {
+ $this->consoleInput->method('getOption')
+ ->will($this->returnValueMap([
+ ['enable', 'true']
+ ]));
+ $this->config->expects($this->once())
+ ->method('setSystemValue')
+ ->with('log_type', 'owncloud');
+
+ self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
+ }
+
+ public function testChangeFile() {
+ $this->consoleInput->method('getOption')
+ ->will($this->returnValueMap([
+ ['file', '/foo/bar/file.log']
+ ]));
+ $this->config->expects($this->once())
+ ->method('setSystemValue')
+ ->with('logfile', '/foo/bar/file.log');
+
+ self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
+ }
+
+ public function changeRotateSizeProvider() {
+ return [
+ ['42', 42],
+ ['0', 0],
+ ['1 kB', 1024],
+ ['5MB', 5 * 1024 * 1024],
+ ];
+ }
+
+ /**
+ * @dataProvider changeRotateSizeProvider
+ */
+ public function testChangeRotateSize($optionValue, $configValue) {
+ $this->consoleInput->method('getOption')
+ ->will($this->returnValueMap([
+ ['rotate-size', $optionValue]
+ ]));
+ $this->config->expects($this->once())
+ ->method('setSystemValue')
+ ->with('log_rotate_size', $configValue);
+
+ self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
+ }
+
+ public function testGetConfiguration() {
+ $this->config->method('getSystemValue')
+ ->will($this->returnValueMap([
+ ['log_type', 'owncloud', 'log_type_value'],
+ ['datadirectory', \OC::$SERVERROOT.'/data', '/data/directory/'],
+ ['logfile', '/data/directory/owncloud.log', '/var/log/owncloud.log'],
+ ['log_rotate_size', 0, 5 * 1024 * 1024],
+ ]));
+
+ $this->consoleOutput->expects($this->at(0))
+ ->method('writeln')
+ ->with('Log backend ownCloud: disabled');
+ $this->consoleOutput->expects($this->at(1))
+ ->method('writeln')
+ ->with('Log file: /var/log/owncloud.log');
+ $this->consoleOutput->expects($this->at(2))
+ ->method('writeln')
+ ->with('Rotate at: 5 MB');
+
+ self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]);
+ }
+
+}
diff --git a/tests/data/setUploadLimit/htaccess b/tests/data/setUploadLimit/htaccess
new file mode 100644
index 00000000000..65957a29838
--- /dev/null
+++ b/tests/data/setUploadLimit/htaccess
@@ -0,0 +1,60 @@
+# Version: 8.2.0
+<IfModule mod_headers.c>
+ <IfModule mod_fcgid.c>
+ <IfModule mod_setenvif.c>
+ SetEnvIfNoCase ^Authorization$ "(.+)" XAUTHORIZATION=$1
+ RequestHeader set XAuthorization %{XAUTHORIZATION}e env=XAUTHORIZATION
+ </IfModule>
+ </IfModule>
+
+ <IfModule mod_env.c>
+ # Add security and privacy related headers
+ Header set X-Content-Type-Options "nosniff"
+ Header set X-XSS-Protection "1; mode=block"
+ Header set X-Robots-Tag "none"
+ Header set X-Frame-Options "SAMEORIGIN"
+ SetEnv modHeadersAvailable true
+ </IfModule>
+
+ # Add cache control for CSS and JS files
+ <FilesMatch "\.(css|js)$">
+ Header set Cache-Control "max-age=7200, public"
+ </FilesMatch>
+</IfModule>
+<IfModule mod_php5.c>
+php_value upload_max_filesize 513M
+php_value post_max_size 513M
+php_value memory_limit 512M
+php_value mbstring.func_overload 0
+php_value always_populate_raw_post_data -1
+php_value default_charset 'UTF-8'
+php_value output_buffering off
+<IfModule mod_env.c>
+ SetEnv htaccessWorking true
+</IfModule>
+</IfModule>
+<IfModule mod_rewrite.c>
+RewriteEngine on
+RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
+RewriteRule ^\.well-known/host-meta /public.php?service=host-meta [QSA,L]
+RewriteRule ^\.well-known/host-meta\.json /public.php?service=host-meta-json [QSA,L]
+RewriteRule ^\.well-known/carddav /remote.php/carddav/ [R=301,L]
+RewriteRule ^\.well-known/caldav /remote.php/caldav/ [R=301,L]
+RewriteRule ^apps/calendar/caldav\.php remote.php/caldav/ [QSA,L]
+RewriteRule ^apps/contacts/carddav\.php remote.php/carddav/ [QSA,L]
+RewriteRule ^remote/(.*) remote.php [QSA,L]
+RewriteRule ^(build|tests|config|lib|3rdparty|templates)/.* - [R=404,L]
+RewriteRule ^(\.|autotest|occ|issue|indie|db_|console).* - [R=404,L]
+</IfModule>
+<IfModule mod_mime.c>
+AddType image/svg+xml svg svgz
+AddEncoding gzip svgz
+</IfModule>
+<IfModule mod_dir.c>
+DirectoryIndex index.php index.html
+</IfModule>
+AddDefaultCharset utf-8
+Options -Indexes
+<IfModule pagespeed_module>
+ ModPagespeed Off
+</IfModule>
diff --git a/tests/data/setUploadLimit/user.ini b/tests/data/setUploadLimit/user.ini
new file mode 100644
index 00000000000..c5996e8d47e
--- /dev/null
+++ b/tests/data/setUploadLimit/user.ini
@@ -0,0 +1,7 @@
+upload_max_filesize=513M
+post_max_size=513M
+memory_limit=512M
+mbstring.func_overload=0
+always_populate_raw_post_data=-1
+default_charset='UTF-8'
+output_buffering=off
diff --git a/tests/lib/activitymanager.php b/tests/lib/activitymanager.php
index 28caf575948..26759d46270 100644
--- a/tests/lib/activitymanager.php
+++ b/tests/lib/activitymanager.php
@@ -41,6 +41,9 @@ class Test_ActivityManager extends \Test\TestCase {
$this->config
);
+ $this->assertSame([], $this->invokePrivate($this->activityManager, 'getConsumers'));
+ $this->assertSame([], $this->invokePrivate($this->activityManager, 'getExtensions'));
+
$this->activityManager->registerConsumer(function() {
return new NoOpConsumer();
});
@@ -50,6 +53,11 @@ class Test_ActivityManager extends \Test\TestCase {
$this->activityManager->registerExtension(function() {
return new SimpleExtension();
});
+
+ $this->assertNotEmpty($this->invokePrivate($this->activityManager, 'getConsumers'));
+ $this->assertNotEmpty($this->invokePrivate($this->activityManager, 'getConsumers'));
+ $this->assertNotEmpty($this->invokePrivate($this->activityManager, 'getExtensions'));
+ $this->assertNotEmpty($this->invokePrivate($this->activityManager, 'getExtensions'));
}
public function testGetConsumers() {
@@ -249,6 +257,192 @@ class Test_ActivityManager extends \Test\TestCase {
->method('getUser')
->willReturn($mockUser);
}
+
+ /**
+ * @expectedException BadMethodCallException
+ * @expectedExceptionMessage App not set
+ * @expectedExceptionCode 10
+ */
+ public function testPublishExceptionNoApp() {
+ $event = new \OC\Activity\Event();
+ $this->activityManager->publish($event);
+ }
+
+ /**
+ * @expectedException BadMethodCallException
+ * @expectedExceptionMessage Type not set
+ * @expectedExceptionCode 11
+ */
+ public function testPublishExceptionNoType() {
+ $event = new \OC\Activity\Event();
+ $event->setApp('test');
+ $this->activityManager->publish($event);
+ }
+
+ /**
+ * @expectedException BadMethodCallException
+ * @expectedExceptionMessage Affected user not set
+ * @expectedExceptionCode 12
+ */
+ public function testPublishExceptionNoAffectedUser() {
+ $event = new \OC\Activity\Event();
+ $event->setApp('test')
+ ->setType('test_type');
+ $this->activityManager->publish($event);
+ }
+
+ /**
+ * @expectedException BadMethodCallException
+ * @expectedExceptionMessage Subject not set
+ * @expectedExceptionCode 13
+ */
+ public function testPublishExceptionNoSubject() {
+ $event = new \OC\Activity\Event();
+ $event->setApp('test')
+ ->setType('test_type')
+ ->setAffectedUser('test_affected');
+ $this->activityManager->publish($event);
+ }
+
+ public function dataPublish() {
+ return [
+ [null],
+ ['test_author'],
+ ];
+ }
+
+ /**
+ * @dataProvider dataPublish
+ * @param string $author
+ */
+ public function testPublish($author) {
+ if ($author !== null) {
+ $authorObject = $this->getMockBuilder('OCP\IUser')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $authorObject->expects($this->once())
+ ->method('getUID')
+ ->willReturn($author);
+ $this->session->expects($this->atLeastOnce())
+ ->method('getUser')
+ ->willReturn($authorObject);
+ }
+
+ $event = new \OC\Activity\Event();
+ $event->setApp('test')
+ ->setType('test_type')
+ ->setSubject('test_subject', [])
+ ->setAffectedUser('test_affected');
+
+ $consumer = $this->getMockBuilder('OCP\Activity\IConsumer')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $consumer->expects($this->once())
+ ->method('receive')
+ ->with($event)
+ ->willReturnCallback(function(\OCP\Activity\IEvent $event) use ($author) {
+ $this->assertLessThanOrEqual(time() + 2, $event->getTimestamp(), 'Timestamp not set correctly');
+ $this->assertGreaterThanOrEqual(time() - 2, $event->getTimestamp(), 'Timestamp not set correctly');
+ $this->assertSame($author, $event->getAuthor(), 'Author name not set correctly');
+ });
+ $this->activityManager->registerConsumer(function () use ($consumer) {
+ return $consumer;
+ });
+
+ $this->activityManager->publish($event);
+ }
+
+ public function testPublishAllManually() {
+ $event = new \OC\Activity\Event();
+ $event->setApp('test_app')
+ ->setType('test_type')
+ ->setAffectedUser('test_affected')
+ ->setAuthor('test_author')
+ ->setTimestamp(1337)
+ ->setSubject('test_subject', ['test_subject_param'])
+ ->setMessage('test_message', ['test_message_param'])
+ ->setObject('test_object_type', 42, 'test_object_name')
+ ->setLink('test_link')
+ ;
+
+ $consumer = $this->getMockBuilder('OCP\Activity\IConsumer')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $consumer->expects($this->once())
+ ->method('receive')
+ ->willReturnCallback(function(\OCP\Activity\IEvent $event) {
+ $this->assertSame('test_app', $event->getApp(), 'App not set correctly');
+ $this->assertSame('test_type', $event->getType(), 'Type not set correctly');
+ $this->assertSame('test_affected', $event->getAffectedUser(), 'Affected user not set correctly');
+ $this->assertSame('test_author', $event->getAuthor(), 'Author not set correctly');
+ $this->assertSame(1337, $event->getTimestamp(), 'Timestamp not set correctly');
+ $this->assertSame('test_subject', $event->getSubject(), 'Subject not set correctly');
+ $this->assertSame(['test_subject_param'], $event->getSubjectParameters(), 'Subject parameter not set correctly');
+ $this->assertSame('test_message', $event->getMessage(), 'Message not set correctly');
+ $this->assertSame(['test_message_param'], $event->getMessageParameters(), 'Message parameter not set correctly');
+ $this->assertSame('test_object_type', $event->getObjectType(), 'Object type not set correctly');
+ $this->assertSame(42, $event->getObjectId(), 'Object ID not set correctly');
+ $this->assertSame('test_object_name', $event->getObjectName(), 'Object name not set correctly');
+ $this->assertSame('test_link', $event->getLink(), 'Link not set correctly');
+ });
+ $this->activityManager->registerConsumer(function () use ($consumer) {
+ return $consumer;
+ });
+
+ $this->activityManager->publish($event);
+ }
+
+ public function testDeprecatedPublishActivity() {
+ $event = new \OC\Activity\Event();
+ $event->setApp('test_app')
+ ->setType('test_type')
+ ->setAffectedUser('test_affected')
+ ->setAuthor('test_author')
+ ->setTimestamp(1337)
+ ->setSubject('test_subject', ['test_subject_param'])
+ ->setMessage('test_message', ['test_message_param'])
+ ->setObject('test_object_type', 42, 'test_object_name')
+ ->setLink('test_link')
+ ;
+
+ $consumer = $this->getMockBuilder('OCP\Activity\IConsumer')
+ ->disableOriginalConstructor()
+ ->getMock();
+ $consumer->expects($this->once())
+ ->method('receive')
+ ->willReturnCallback(function(\OCP\Activity\IEvent $event) {
+ $this->assertSame('test_app', $event->getApp(), 'App not set correctly');
+ $this->assertSame('test_type', $event->getType(), 'Type not set correctly');
+ $this->assertSame('test_affected', $event->getAffectedUser(), 'Affected user not set correctly');
+ $this->assertSame('test_subject', $event->getSubject(), 'Subject not set correctly');
+ $this->assertSame(['test_subject_param'], $event->getSubjectParameters(), 'Subject parameter not set correctly');
+ $this->assertSame('test_message', $event->getMessage(), 'Message not set correctly');
+ $this->assertSame(['test_message_param'], $event->getMessageParameters(), 'Message parameter not set correctly');
+ $this->assertSame('test_object_name', $event->getObjectName(), 'Object name not set correctly');
+ $this->assertSame('test_link', $event->getLink(), 'Link not set correctly');
+
+ // The following values can not be used via publishActivity()
+ $this->assertLessThanOrEqual(time() + 2, $event->getTimestamp(), 'Timestamp not set correctly');
+ $this->assertGreaterThanOrEqual(time() - 2, $event->getTimestamp(), 'Timestamp not set correctly');
+ $this->assertSame(null, $event->getAuthor(), 'Author not set correctly');
+ $this->assertSame('', $event->getObjectType(), 'Object type should not be set');
+ $this->assertSame(0, $event->getObjectId(), 'Object ID should not be set');
+ });
+ $this->activityManager->registerConsumer(function () use ($consumer) {
+ return $consumer;
+ });
+
+ $this->activityManager->publishActivity(
+ $event->getApp(),
+ $event->getSubject(), $event->getSubjectParameters(),
+ $event->getMessage(), $event->getMessageParameters(),
+ $event->getObjectName(),
+ $event->getLink(),
+ $event->getAffectedUser(),
+ $event->getType(),
+ \OCP\Activity\IExtension::PRIORITY_MEDIUM
+ );
+ }
}
class SimpleExtension implements \OCP\Activity\IExtension {
@@ -368,6 +562,7 @@ class NoOpExtension implements \OCP\Activity\IExtension {
class NoOpConsumer implements \OCP\Activity\IConsumer {
- public function receive($app, $subject, $subjectParams, $message, $messageParams, $file, $link, $affectedUser, $type, $priority) {
+ public function receive(\OCP\Activity\IEvent $event) {
+
}
}
diff --git a/tests/lib/app/manager.php b/tests/lib/app/manager.php
index 6cf7eb3bb6c..7333d7601b1 100644
--- a/tests/lib/app/manager.php
+++ b/tests/lib/app/manager.php
@@ -204,4 +204,74 @@ class Manager extends \PHPUnit_Framework_TestCase {
$this->appConfig->setValue('test4', 'enabled', '["asd"]');
$this->assertEquals(['test1', 'test3'], $this->manager->getEnabledAppsForUser($user));
}
+
+ public function testGetAppsNeedingUpgrade() {
+ $this->manager = $this->getMockBuilder('\OC\App\AppManager')
+ ->setConstructorArgs([$this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory])
+ ->setMethods(['getAppInfo'])
+ ->getMock();
+
+ $appInfos = [
+ 'test1' => ['id' => 'test1', 'version' => '1.0.1', 'requiremax' => '9.0.0'],
+ 'test2' => ['id' => 'test2', 'version' => '1.0.0', 'requiremin' => '8.2.0'],
+ 'test3' => ['id' => 'test3', 'version' => '1.2.4', 'requiremin' => '9.0.0'],
+ 'test4' => ['id' => 'test4', 'version' => '3.0.0', 'requiremin' => '8.1.0'],
+ 'testnoversion' => ['id' => 'testnoversion', 'requiremin' => '8.2.0'],
+ ];
+
+ $this->manager->expects($this->any())
+ ->method('getAppInfo')
+ ->will($this->returnCallback(
+ function($appId) use ($appInfos) {
+ return $appInfos[$appId];
+ }
+ ));
+
+ $this->appConfig->setValue('test1', 'enabled', 'yes');
+ $this->appConfig->setValue('test1', 'installed_version', '1.0.0');
+ $this->appConfig->setValue('test2', 'enabled', 'yes');
+ $this->appConfig->setValue('test2', 'installed_version', '1.0.0');
+ $this->appConfig->setValue('test3', 'enabled', 'yes');
+ $this->appConfig->setValue('test3', 'installed_version', '1.0.0');
+ $this->appConfig->setValue('test4', 'enabled', 'yes');
+ $this->appConfig->setValue('test4', 'installed_version', '2.4.0');
+
+ $apps = $this->manager->getAppsNeedingUpgrade('8.2.0');
+
+ $this->assertCount(2, $apps);
+ $this->assertEquals('test1', $apps[0]['id']);
+ $this->assertEquals('test4', $apps[1]['id']);
+ }
+
+ public function testGetIncompatibleApps() {
+ $this->manager = $this->getMockBuilder('\OC\App\AppManager')
+ ->setConstructorArgs([$this->userSession, $this->appConfig, $this->groupManager, $this->cacheFactory])
+ ->setMethods(['getAppInfo'])
+ ->getMock();
+
+ $appInfos = [
+ 'test1' => ['id' => 'test1', 'version' => '1.0.1', 'requiremax' => '8.0.0'],
+ 'test2' => ['id' => 'test2', 'version' => '1.0.0', 'requiremin' => '8.2.0'],
+ 'test3' => ['id' => 'test3', 'version' => '1.2.4', 'requiremin' => '9.0.0'],
+ 'testnoversion' => ['id' => 'testnoversion', 'requiremin' => '8.2.0'],
+ ];
+
+ $this->manager->expects($this->any())
+ ->method('getAppInfo')
+ ->will($this->returnCallback(
+ function($appId) use ($appInfos) {
+ return $appInfos[$appId];
+ }
+ ));
+
+ $this->appConfig->setValue('test1', 'enabled', 'yes');
+ $this->appConfig->setValue('test2', 'enabled', 'yes');
+ $this->appConfig->setValue('test3', 'enabled', 'yes');
+
+ $apps = $this->manager->getIncompatibleApps('8.2.0');
+
+ $this->assertCount(2, $apps);
+ $this->assertEquals('test1', $apps[0]['id']);
+ $this->assertEquals('test3', $apps[1]['id']);
+ }
}
diff --git a/tests/lib/backgroundjob/joblist.php b/tests/lib/backgroundjob/joblist.php
index 13bee12479e..d5136676a47 100644
--- a/tests/lib/backgroundjob/joblist.php
+++ b/tests/lib/backgroundjob/joblist.php
@@ -202,4 +202,30 @@ class JobList extends \Test\TestCase {
$this->instance->remove($job);
}
+
+ public function testGetNextNonExisting() {
+ $job = new TestJob();
+ $this->instance->add($job, 1);
+ $this->instance->add('\OC\Non\Existing\Class');
+ $this->instance->add($job, 2);
+
+ $jobs = $this->instance->getAll();
+
+ $savedJob1 = $jobs[count($jobs) - 2];
+ $savedJob2 = $jobs[count($jobs) - 1];
+
+ $this->config->expects($this->any())
+ ->method('getAppValue')
+ ->with('backgroundjob', 'lastjob', 0)
+ ->will($this->returnValue($savedJob1->getId()));
+
+ $this->instance->getNext();
+
+ $nextJob = $this->instance->getNext();
+
+ $this->assertEquals($savedJob2, $nextJob);
+
+ $this->instance->remove($job, 1);
+ $this->instance->remove($job, 2);
+ }
}
diff --git a/tests/lib/connector/sabre/requesttest/requesttest.php b/tests/lib/connector/sabre/requesttest/requesttest.php
index c7739aefcd7..7f33dcf817b 100644
--- a/tests/lib/connector/sabre/requesttest/requesttest.php
+++ b/tests/lib/connector/sabre/requesttest/requesttest.php
@@ -11,22 +11,18 @@ namespace Test\Connector\Sabre\RequestTest;
use OC\Connector\Sabre\Server;
use OC\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 {
- /**
- * @var \OC_User_Dummy
- */
- protected $userBackend;
-
- /**
- * @var \OCP\Files\Config\IMountProvider[]
- */
- protected $mountProviders;
+ use UserTrait;
+ use MountProviderTrait;
/**
* @var \OC\Connector\Sabre\ServerFactory
@@ -40,33 +36,8 @@ abstract class RequestTest extends TestCase {
return $stream;
}
- /**
- * @param $userId
- * @param $storages
- * @return \OCP\Files\Config\IMountProvider
- */
- protected function getMountProvider($userId, $storages) {
- $mounts = [];
- foreach ($storages as $mountPoint => $storage) {
- $mounts[] = new MountPoint($storage, $mountPoint);
- }
- $provider = $this->getMock('\OCP\Files\Config\IMountProvider');
- $provider->expects($this->any())
- ->method('getMountsForUser')
- ->will($this->returnCallback(function (IUser $user) use ($userId, $mounts) {
- if ($user->getUID() === $userId) {
- return $mounts;
- } else {
- return [];
- }
- }));
- return $provider;
- }
-
protected function setUp() {
parent::setUp();
- $this->userBackend = new \OC_User_Dummy();
- \OC::$server->getUserManager()->registerBackend($this->userBackend);
$this->serverFactory = new ServerFactory(
\OC::$server->getConfig(),
@@ -78,16 +49,9 @@ abstract class RequestTest extends TestCase {
);
}
- protected function tearDown() {
- parent::tearDown();
- \OC::$server->getUserManager()->removeBackend($this->userBackend);
- }
-
protected function setupUser($name, $password) {
- $this->userBackend->createUser($name, $password);
- \OC::$server->getMountProviderCollection()->registerProvider($this->getMountProvider($name, [
- '/' . $name => new Temporary()
- ]));
+ $this->createUser($name, $password);
+ $this->registerMount($name, '\OC\Files\Storage\Temporary', '/' . $name);
$this->loginAsUser($name);
return new View('/' . $name . '/files');
}
diff --git a/tests/lib/files.php b/tests/lib/files.php
new file mode 100644
index 00000000000..6808b3e9f64
--- /dev/null
+++ b/tests/lib/files.php
@@ -0,0 +1,135 @@
+<?php
+/**
+ * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
+ *
+ * @copyright Copyright (c) 2015, ownCloud, Inc.
+ * @license AGPL-3.0
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this library. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Test;
+
+class Files extends \Test\TestCase {
+
+ const UPLOAD_LIMIT_DEFAULT_STR = '513M';
+ const UPLOAD_LIMIT_SETTING_STR = '2M';
+ const UPLOAD_LIMIT_SETTING_BYTES = 2097152;
+
+ /** @var array $tmpDirs */
+ private $tmpDirs = [];
+
+ /**
+ * @return array
+ */
+ private function getUploadLimitTestFiles() {
+ $dir = \OC::$server->getTempManager()->getTemporaryFolder();
+ $this->tmpDirs[] = $dir;
+ $result = [
+ '.htaccess' => $dir . '/htaccess',
+ '.user.ini' => $dir . '/user.ini'
+ ];
+ copy(\OC::$SERVERROOT . '/tests/data/setUploadLimit/htaccess', $result['.htaccess']);
+ copy(\OC::$SERVERROOT . '/tests/data/setUploadLimit/user.ini', $result['.user.ini']);
+ return $result;
+ }
+
+ protected function tearDown() {
+ foreach ($this->tmpDirs as $dir) {
+ \OC_Helper::rmdirr($dir);
+ }
+ parent::tearDown();
+ }
+
+ public function testSetUploadLimitSizeSanity() {
+ $this->assertFalse(\OC_Files::setUploadLimit(PHP_INT_MAX + 10));
+ $this->assertFalse(\OC_Files::setUploadLimit(\OC_Files::UPLOAD_MIN_LIMIT_BYTES - 10));
+ $this->assertFalse(\OC_Files::setUploadLimit('foobar'));
+ }
+
+ public function setUploadLimitWriteProvider() {
+ return [
+ [
+ // both files writable
+ true, true,
+ self::UPLOAD_LIMIT_SETTING_BYTES, self::UPLOAD_LIMIT_SETTING_BYTES,
+ self::UPLOAD_LIMIT_SETTING_STR, self::UPLOAD_LIMIT_SETTING_STR
+ ],
+ [
+ // neither file writable
+ false, false,
+ self::UPLOAD_LIMIT_SETTING_BYTES, false,
+ self::UPLOAD_LIMIT_DEFAULT_STR, self::UPLOAD_LIMIT_DEFAULT_STR
+ ],
+ [
+ // only .htaccess writable
+ true, false,
+ self::UPLOAD_LIMIT_SETTING_BYTES, false,
+ self::UPLOAD_LIMIT_SETTING_STR, self::UPLOAD_LIMIT_DEFAULT_STR
+ ],
+ [
+ // only .user.ini writable
+ false, true,
+ self::UPLOAD_LIMIT_SETTING_BYTES, false,
+ self::UPLOAD_LIMIT_DEFAULT_STR, self::UPLOAD_LIMIT_SETTING_STR
+ ],
+ [
+ // test rounding of values
+ true, true,
+ self::UPLOAD_LIMIT_SETTING_BYTES + 20, self::UPLOAD_LIMIT_SETTING_BYTES,
+ self::UPLOAD_LIMIT_SETTING_STR, self::UPLOAD_LIMIT_SETTING_STR
+ ]
+ ];
+ }
+
+ /**
+ * @dataProvider setUploadLimitWriteProvider
+ */
+ public function testSetUploadLimitWrite(
+ $htaccessWritable, $userIniWritable,
+ $setSize, $expectedSize,
+ $htaccessStr, $userIniStr
+ ) {
+ $files = $this->getUploadLimitTestFiles();
+ chmod($files['.htaccess'], ($htaccessWritable ? 0644 : 0444));
+ chmod($files['.user.ini'], ($userIniWritable ? 0644 : 0444));
+
+ $htaccessSize = filesize($files['.htaccess']);
+ $userIniSize = filesize($files['.user.ini']);
+ $htaccessSizeMod = 2*(strlen($htaccessStr) - strlen(self::UPLOAD_LIMIT_DEFAULT_STR));
+ $userIniSizeMod = 2*(strlen($userIniStr) - strlen(self::UPLOAD_LIMIT_DEFAULT_STR));
+
+ $this->assertEquals($expectedSize, \OC_Files::setUploadLimit($setSize, $files));
+
+ // check file contents
+ $htaccess = file_get_contents($files['.htaccess']);
+ $this->assertEquals(1,
+ preg_match('/php_value upload_max_filesize '.$htaccessStr.'/', $htaccess)
+ );
+ $this->assertEquals(1,
+ preg_match('/php_value post_max_size '.$htaccessStr.'/', $htaccess)
+ );
+ $this->assertEquals($htaccessSize + $htaccessSizeMod, filesize($files['.htaccess']));
+
+ $userIni = file_get_contents($files['.user.ini']);
+ $this->assertEquals(1,
+ preg_match('/upload_max_filesize='.$userIniStr.'/', $userIni)
+ );
+ $this->assertEquals(1,
+ preg_match('/post_max_size='.$userIniStr.'/', $userIni)
+ );
+ $this->assertEquals($userIniSize + $userIniSizeMod, filesize($files['.user.ini']));
+ }
+}
diff --git a/tests/lib/files/mount/mountpoint.php b/tests/lib/files/mount/mountpoint.php
index d758c1b8d4d..29610e6058d 100644
--- a/tests/lib/files/mount/mountpoint.php
+++ b/tests/lib/files/mount/mountpoint.php
@@ -70,25 +70,4 @@ class MountPoint extends \Test\TestCase {
// storage wrapper never called
$this->assertFalse($called);
}
-
- public function testWrappedStorage() {
- $storage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Wrapper')
- ->disableOriginalConstructor()
- ->getMock();
-
- $loader = $this->getMock('\OCP\Files\Storage\IStorageFactory');
- $loader->expects($this->never())
- ->method('getInstance');
- $loader->expects($this->never())
- ->method('wrap');
-
- $mountPoint = new \OC\Files\Mount\MountPoint(
- $storage,
- '/mountpoint',
- null,
- $loader
- );
-
- $this->assertEquals($storage, $mountPoint->getStorage());
- }
}
diff --git a/tests/lib/testcase.php b/tests/lib/testcase.php
index fd0b8d5f2de..854d5f4f65b 100644
--- a/tests/lib/testcase.php
+++ b/tests/lib/testcase.php
@@ -32,21 +32,52 @@ abstract class TestCase extends \PHPUnit_Framework_TestCase {
*/
private $commandBus;
+ protected function getTestTraits() {
+ $traits = [];
+ $class = $this;
+ do {
+ $traits = array_merge(class_uses($class), $traits);
+ } while ($class = get_parent_class($class));
+ foreach ($traits as $trait => $same) {
+ $traits = array_merge(class_uses($trait), $traits);
+ }
+ $traits = array_unique($traits);
+ return array_filter($traits, function ($trait) {
+ return substr($trait, 0, 5) === 'Test\\';
+ });
+ }
+
protected function setUp() {
// overwrite the command bus with one we can run ourselves
$this->commandBus = new QueueBus();
\OC::$server->registerService('AsyncCommandBus', function () {
return $this->commandBus;
});
+
+ $traits = $this->getTestTraits();
+ foreach ($traits as $trait) {
+ $methodName = 'setUp' . basename(str_replace('\\', '/', $trait));
+ if (method_exists($this, $methodName)) {
+ call_user_func([$this, $methodName]);
+ }
+ }
}
protected function tearDown() {
$hookExceptions = \OC_Hook::$thrownExceptions;
\OC_Hook::$thrownExceptions = [];
\OC::$server->getLockingProvider()->releaseAll();
- if(!empty($hookExceptions)) {
+ if (!empty($hookExceptions)) {
throw $hookExceptions[0];
}
+
+ $traits = $this->getTestTraits();
+ foreach ($traits as $trait) {
+ $methodName = 'tearDown' . basename(str_replace('\\', '/', $trait));
+ if (method_exists($this, $methodName)) {
+ call_user_func([$this, $methodName]);
+ }
+ }
}
/**
diff --git a/tests/lib/traits/mountprovidertrait.php b/tests/lib/traits/mountprovidertrait.php
new file mode 100644
index 00000000000..66eca1597c8
--- /dev/null
+++ b/tests/lib/traits/mountprovidertrait.php
@@ -0,0 +1,56 @@
+<?php
+/**
+ * Copyright (c) 2015 Robin Appelman <icewind@owncloud.com>
+ * This file is licensed under the Affero General Public License version 3 or
+ * later.
+ * See the COPYING-README file.
+ */
+
+namespace Test\Traits;
+
+use OC\Files\Mount\MountPoint;
+use OC\Files\Storage\StorageFactory;
+use OCP\IUser;
+
+/**
+ * Allow setting mounts for users
+ */
+trait MountProviderTrait {
+ /**
+ * @var \OCP\Files\Config\IMountProvider
+ */
+ protected $mountProvider;
+
+ /**
+ * @var \OC\Files\Storage\StorageFactory
+ */
+ protected $storageFactory;
+
+ protected $mounts = [];
+
+ protected function registerMount($userId, $storage, $mountPoint, $arguments = null) {
+ if (!isset($this->mounts[$userId])) {
+ $this->mounts[$userId] = [];
+ }
+ $this->mounts[$userId][] = new MountPoint($storage, $mountPoint, $arguments, $this->storageFactory);
+ }
+
+ protected function registerStorageWrapper($name, $wrapper) {
+ $this->storageFactory->addStorageWrapper($name, $wrapper);
+ }
+
+ protected function setUpMountProviderTrait() {
+ $this->storageFactory = new StorageFactory();
+ $this->mountProvider = $this->getMock('\OCP\Files\Config\IMountProvider');
+ $this->mountProvider->expects($this->any())
+ ->method('getMountsForUser')
+ ->will($this->returnCallback(function (IUser $user) {
+ if (isset($this->mounts[$user->getUID()])) {
+ return $this->mounts[$user->getUID()];
+ } else {
+ return [];
+ }
+ }));
+ \OC::$server->getMountProviderCollection()->registerProvider($this->mountProvider);
+ }
+}
diff --git a/tests/lib/traits/usertrait.php b/tests/lib/traits/usertrait.php
new file mode 100644
index 00000000000..401d8b8a832
--- /dev/null
+++ b/tests/lib/traits/usertrait.php
@@ -0,0 +1,32 @@
+<?php
+/**
+ * Copyright (c) 2015 Robin Appelman <icewind@owncloud.com>
+ * This file is licensed under the Affero General Public License version 3 or
+ * later.
+ * See the COPYING-README file.
+ */
+
+namespace Test\Traits;
+
+/**
+ * Allow creating users in a temporary backend
+ */
+trait UserTrait {
+ /**
+ * @var \OC_User_Dummy|\OCP\UserInterface
+ */
+ protected $userBackend;
+
+ protected function createUser($name, $password) {
+ $this->userBackend->createUser($name, $password);
+ }
+
+ protected function setUpUserTrait() {
+ $this->userBackend = new \OC_User_Dummy();
+ \OC::$server->getUserManager()->registerBackend($this->userBackend);
+ }
+
+ protected function tearDownUserTrait() {
+ \OC::$server->getUserManager()->removeBackend($this->userBackend);
+ }
+}
diff --git a/tests/settings/controller/userscontrollertest.php b/tests/settings/controller/userscontrollertest.php
index 5f98cf21c04..06065a8454e 100644
--- a/tests/settings/controller/userscontrollertest.php
+++ b/tests/settings/controller/userscontrollertest.php
@@ -1390,9 +1390,11 @@ class UsersControllerTest extends \Test\TestCase {
public function setEmailAddressData() {
return [
- ['', true, false, true],
- ['foobar@localhost', true, true, false],
- ['foo@bar@localhost', false, false, false],
+ /* mailAddress, isValid, expectsUpdate, expectsDelete, canChangeDisplayName, responseCode */
+ [ '', true, false, true, true, Http::STATUS_OK ],
+ [ 'foo@local', true, true, false, true, Http::STATUS_OK],
+ [ 'foo@bar@local', false, false, false, true, Http::STATUS_UNPROCESSABLE_ENTITY],
+ [ 'foo@local', true, false, false, false, Http::STATUS_FORBIDDEN],
];
}
@@ -1404,7 +1406,7 @@ class UsersControllerTest extends \Test\TestCase {
* @param bool $expectsUpdate
* @param bool $expectsDelete
*/
- public function testSetEmailAddress($mailAddress, $isValid, $expectsUpdate, $expectsDelete) {
+ public function testSetEmailAddress($mailAddress, $isValid, $expectsUpdate, $expectsDelete, $canChangeDisplayName, $responseCode) {
$this->container['IsAdmin'] = true;
$user = $this->getMockBuilder('\OC\User\User')
@@ -1413,6 +1415,10 @@ class UsersControllerTest extends \Test\TestCase {
->expects($this->any())
->method('getUID')
->will($this->returnValue('foo'));
+ $user
+ ->expects($this->any())
+ ->method('canChangeDisplayName')
+ ->will($this->returnValue($canChangeDisplayName));
$this->container['UserSession']
->expects($this->atLeastOnce())
->method('getUser')
@@ -1455,7 +1461,9 @@ class UsersControllerTest extends \Test\TestCase {
);
- $this->container['UsersController']->setMailAddress($user->getUID(), $mailAddress);
+ $response = $this->container['UsersController']->setMailAddress($user->getUID(), $mailAddress);
+
+ $this->assertSame($responseCode, $response->getStatus());
}
}