diff options
author | Stanimir Bozhilov <stanimir.bozhilov.1998@gmail.com> | 2022-12-19 09:07:38 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-12-19 09:07:38 +0100 |
commit | 7dcd6eb561f4bba7ed36ce1178c725278dd9b80e (patch) | |
tree | 8de1664f1a18df2e3b7b3dafadb3e0b6c3a8b439 /tests/lib | |
parent | ed902d58b62150a46c745b5e87c895fc3fc67509 (diff) | |
parent | e12aaa298861743f798d9adf644d626ac8e89a95 (diff) | |
download | nextcloud-server-7dcd6eb561f4bba7ed36ce1178c725278dd9b80e.tar.gz nextcloud-server-7dcd6eb561f4bba7ed36ce1178c725278dd9b80e.zip |
Merge branch 'master' into add-scim-json-support
Signed-off-by: Stanimir Bozhilov <stanimir.bozhilov.1998@gmail.com>
Diffstat (limited to 'tests/lib')
50 files changed, 1002 insertions, 984 deletions
diff --git a/tests/lib/Accounts/AccountManagerTest.php b/tests/lib/Accounts/AccountManagerTest.php index 2eaec755b50..3a3405f18a0 100644 --- a/tests/lib/Accounts/AccountManagerTest.php +++ b/tests/lib/Accounts/AccountManagerTest.php @@ -157,6 +157,11 @@ class AccountManagerTest extends TestCase { 'scope' => IAccountManager::SCOPE_PUBLISHED ], [ + 'name' => IAccountManager::PROPERTY_FEDIVERSE, + 'value' => '@someMastodon@mastodon.social', + 'scope' => IAccountManager::SCOPE_PUBLISHED + ], + [ 'name' => IAccountManager::PROPERTY_PHONE, 'value' => '+491601231212', 'scope' => IAccountManager::SCOPE_FEDERATED @@ -212,6 +217,11 @@ class AccountManagerTest extends TestCase { 'scope' => IAccountManager::SCOPE_FEDERATED ], [ + 'name' => IAccountManager::PROPERTY_FEDIVERSE, + 'value' => '@a_alice@cool.social', + 'scope' => IAccountManager::SCOPE_FEDERATED + ], + [ 'name' => IAccountManager::PROPERTY_PHONE, 'value' => '+491602312121', 'scope' => IAccountManager::SCOPE_LOCAL @@ -267,6 +277,11 @@ class AccountManagerTest extends TestCase { 'scope' => IAccountManager::SCOPE_LOCAL ], [ + 'name' => IAccountManager::PROPERTY_FEDIVERSE, + 'value' => '', + 'scope' => IAccountManager::SCOPE_LOCAL + ], + [ 'name' => IAccountManager::PROPERTY_PHONE, 'value' => '+491603121212', 'scope' => IAccountManager::SCOPE_PUBLISHED @@ -322,6 +337,11 @@ class AccountManagerTest extends TestCase { scope' => IAccountManager::SCOPE_LOCAL ], [ + 'name' => IAccountManager::PROPERTY_FEDIVERSE, + 'value' => '', ' + scope' => IAccountManager::SCOPE_LOCAL + ], + [ 'name' => IAccountManager::PROPERTY_PHONE, 'value' => '+71601212123', 'scope' => IAccountManager::SCOPE_LOCAL @@ -387,6 +407,11 @@ class AccountManagerTest extends TestCase { 'scope' => IAccountManager::SCOPE_LOCAL ], [ + 'name' => IAccountManager::PROPERTY_FEDIVERSE, + 'value' => '', + 'scope' => IAccountManager::SCOPE_LOCAL + ], + [ 'name' => IAccountManager::PROPERTY_PHONE, 'value' => '+71602121231', 'scope' => IAccountManager::SCOPE_FEDERATED @@ -571,6 +596,13 @@ class AccountManagerTest extends TestCase { ], [ + 'name' => IAccountManager::PROPERTY_FEDIVERSE, + 'value' => '', + 'scope' => IAccountManager::SCOPE_LOCAL, + 'verified' => IAccountManager::NOT_VERIFIED, + ], + + [ 'name' => IAccountManager::PROPERTY_ORGANISATION, 'value' => '', 'scope' => IAccountManager::SCOPE_LOCAL, @@ -620,6 +652,12 @@ class AccountManagerTest extends TestCase { 'name' => IAccountManager::PROPERTY_TWITTER, ], [ + 'value' => '@mastohandle@mastodon.social', + 'scope' => IAccountManager::SCOPE_LOCAL, + 'verified' => IAccountManager::NOT_VERIFIED, + 'name' => IAccountManager::PROPERTY_FEDIVERSE, + ], + [ 'value' => 'test@example.com', 'scope' => IAccountManager::SCOPE_PUBLISHED, 'verified' => IAccountManager::VERIFICATION_IN_PROGRESS, @@ -634,6 +672,7 @@ class AccountManagerTest extends TestCase { ]; $expected = new Account($user); $expected->setProperty(IAccountManager::PROPERTY_TWITTER, '@twitterhandle', IAccountManager::SCOPE_LOCAL, IAccountManager::NOT_VERIFIED); + $expected->setProperty(IAccountManager::PROPERTY_FEDIVERSE, '@mastohandle@mastodon.social', IAccountManager::SCOPE_LOCAL, IAccountManager::NOT_VERIFIED); $expected->setProperty(IAccountManager::PROPERTY_EMAIL, 'test@example.com', IAccountManager::SCOPE_PUBLISHED, IAccountManager::VERIFICATION_IN_PROGRESS); $expected->setProperty(IAccountManager::PROPERTY_WEBSITE, 'https://example.com', IAccountManager::SCOPE_FEDERATED, IAccountManager::VERIFIED); diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php index db2f117cb9b..de515837406 100644 --- a/tests/lib/App/AppManagerTest.php +++ b/tests/lib/App/AppManagerTest.php @@ -429,6 +429,7 @@ class AppManagerTest extends TestCase { 'settings', 'test1', 'test3', + 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine', @@ -458,6 +459,7 @@ class AppManagerTest extends TestCase { 'settings', 'test1', 'test3', + 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine', @@ -485,6 +487,7 @@ class AppManagerTest extends TestCase { 'test4' => ['id' => 'test4', 'version' => '3.0.0', 'requiremin' => '8.1.0'], 'testnoversion' => ['id' => 'testnoversion', 'requiremin' => '8.2.0'], 'settings' => ['id' => 'settings'], + 'theming' => ['id' => 'theming'], 'twofactor_backupcodes' => ['id' => 'twofactor_backupcodes'], 'viewer' => ['id' => 'viewer'], 'workflowengine' => ['id' => 'workflowengine'], @@ -534,6 +537,7 @@ class AppManagerTest extends TestCase { 'test3' => ['id' => 'test3', 'version' => '1.2.4', 'requiremin' => '9.0.0'], 'settings' => ['id' => 'settings'], 'testnoversion' => ['id' => 'testnoversion', 'requiremin' => '8.2.0'], + 'theming' => ['id' => 'theming'], 'twofactor_backupcodes' => ['id' => 'twofactor_backupcodes'], 'workflowengine' => ['id' => 'workflowengine'], 'oauth2' => ['id' => 'oauth2'], @@ -580,6 +584,7 @@ class AppManagerTest extends TestCase { 'settings', 'test1', 'test3', + 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine', diff --git a/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php b/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php index 55534cae699..c1fe5ef328a 100644 --- a/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php +++ b/tests/lib/App/AppStore/Bundles/BundleFetcherTest.php @@ -22,7 +22,6 @@ namespace Test\App\AppStore\Bundles; use OC\App\AppStore\Bundles\BundleFetcher; -use OC\App\AppStore\Bundles\CoreBundle; use OC\App\AppStore\Bundles\EducationBundle; use OC\App\AppStore\Bundles\EnterpriseBundle; use OC\App\AppStore\Bundles\GroupwareBundle; @@ -58,16 +57,8 @@ class BundleFetcherTest extends TestCase { $this->assertEquals($expected, $this->bundleFetcher->getBundles()); } - public function testGetDefaultInstallationBundle() { - $expected = [ - new CoreBundle($this->l10n), - ]; - $this->assertEquals($expected, $this->bundleFetcher->getDefaultInstallationBundle()); - } - public function testGetBundleByIdentifier() { $this->assertEquals(new EnterpriseBundle($this->l10n), $this->bundleFetcher->getBundleByIdentifier('EnterpriseBundle')); - $this->assertEquals(new CoreBundle($this->l10n), $this->bundleFetcher->getBundleByIdentifier('CoreBundle')); $this->assertEquals(new GroupwareBundle($this->l10n), $this->bundleFetcher->getBundleByIdentifier('GroupwareBundle')); } diff --git a/tests/lib/App/AppStore/Bundles/CoreBundleTest.php b/tests/lib/App/AppStore/Bundles/CoreBundleTest.php deleted file mode 100644 index 2ace537b938..00000000000 --- a/tests/lib/App/AppStore/Bundles/CoreBundleTest.php +++ /dev/null @@ -1,36 +0,0 @@ -<?php -/** - * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * 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 - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - */ - -namespace Test\App\AppStore\Bundles; - -use OC\App\AppStore\Bundles\CoreBundle; - -class CoreBundleTest extends BundleBase { - protected function setUp(): void { - parent::setUp(); - $this->bundle = new CoreBundle($this->l10n); - $this->bundleIdentifier = 'CoreBundle'; - $this->bundleName = 'Core bundle'; - $this->bundleAppIds = [ - 'bruteforcesettings', - ]; - } -} diff --git a/tests/lib/AppFramework/Db/MapperTest.php b/tests/lib/AppFramework/Db/MapperTest.php deleted file mode 100644 index e5a4b63b7a3..00000000000 --- a/tests/lib/AppFramework/Db/MapperTest.php +++ /dev/null @@ -1,300 +0,0 @@ -<?php - -/** - * ownCloud - App Framework - * - * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com - * - * 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\AppFramework\Db; - -use OCP\AppFramework\Db\DoesNotExistException; -use OCP\AppFramework\Db\Entity; -use OCP\AppFramework\Db\Mapper; -use OCP\AppFramework\Db\MultipleObjectsReturnedException; -use OCP\IDBConnection; - -/** - * @method integer getId() - * @method void setId(integer $id) - * @method string getEmail() - * @method void setEmail(string $email) - * @method string getPreName() - * @method void setPreName(string $preName) - */ -class Example extends Entity { - protected $preName; - protected $email; -}; - - -class ExampleMapper extends Mapper { - public function __construct(IDBConnection $db) { - parent::__construct($db, 'table'); - } - public function find($table, $id) { - return $this->findOneQuery($table, $id); - } - public function findOneEntity($table, $id) { - return $this->findEntity($table, $id); - } - public function findAllEntities($table) { - return $this->findEntities($table); - } - public function mapRow($row) { - return $this->mapRowToEntity($row); - } - public function execSql($sql, $params) { - return $this->execute($sql, $params); - } -} - - -class MapperTest extends MapperTestUtility { - - /** - * @var Mapper - */ - private $mapper; - - protected function setUp(): void { - parent::setUp(); - $this->mapper = new ExampleMapper($this->db); - } - - - public function testMapperShouldSetTableName() { - $this->assertEquals('*PREFIX*table', $this->mapper->getTableName()); - } - - - public function testFindQuery() { - $sql = 'hi'; - $params = ['jo']; - $rows = [ - ['hi'] - ]; - $this->setMapperResult($sql, $params, $rows); - $this->mapper->find($sql, $params); - } - - public function testFindEntity() { - $sql = 'hi'; - $params = ['jo']; - $rows = [ - ['pre_name' => 'hi'] - ]; - $this->setMapperResult($sql, $params, $rows, null, null, true); - $this->mapper->findOneEntity($sql, $params); - } - - public function testFindNotFound() { - $sql = 'hi'; - $params = ['jo']; - $rows = []; - $this->setMapperResult($sql, $params, $rows); - $this->expectException(DoesNotExistException::class); - $this->mapper->find($sql, $params); - } - - public function testFindEntityNotFound() { - $sql = 'hi'; - $params = ['jo']; - $rows = []; - $this->setMapperResult($sql, $params, $rows, null, null, true); - $this->expectException(DoesNotExistException::class); - $this->mapper->findOneEntity($sql, $params); - } - - public function testFindMultiple() { - $sql = 'hi'; - $params = ['jo']; - $rows = [ - ['jo'], ['ho'] - ]; - $this->setMapperResult($sql, $params, $rows, null, null, true); - $this->expectException(MultipleObjectsReturnedException::class); - $this->mapper->find($sql, $params); - } - - public function testFindEntityMultiple() { - $sql = 'hi'; - $params = ['jo']; - $rows = [ - ['jo'], ['ho'] - ]; - $this->setMapperResult($sql, $params, $rows, null, null, true); - $this->expectException(MultipleObjectsReturnedException::class); - $this->mapper->findOneEntity($sql, $params); - } - - - public function testDelete() { - $sql = 'DELETE FROM `*PREFIX*table` WHERE `id` = ?'; - $params = [2]; - - $this->setMapperResult($sql, $params, [], null, null, true); - $entity = new Example(); - $entity->setId($params[0]); - - $this->mapper->delete($entity); - } - - - public function testCreate() { - $this->db->expects($this->once()) - ->method('lastInsertId') - ->with($this->equalTo('*PREFIX*table')) - ->willReturn(3); - $this->mapper = new ExampleMapper($this->db); - - $sql = 'INSERT INTO `*PREFIX*table`(`pre_name`,`email`) ' . - 'VALUES(?,?)'; - $params = ['john', 'my@email']; - $entity = new Example(); - $entity->setPreName($params[0]); - $entity->setEmail($params[1]); - - $this->setMapperResult($sql, $params, [], null, null, true); - - $this->mapper->insert($entity); - } - - - public function testCreateShouldReturnItemWithCorrectInsertId() { - $this->db->expects($this->once()) - ->method('lastInsertId') - ->with($this->equalTo('*PREFIX*table')) - ->willReturn(3); - $this->mapper = new ExampleMapper($this->db); - - $sql = 'INSERT INTO `*PREFIX*table`(`pre_name`,`email`) ' . - 'VALUES(?,?)'; - $params = ['john', 'my@email']; - $entity = new Example(); - $entity->setPreName($params[0]); - $entity->setEmail($params[1]); - - $this->setMapperResult($sql, $params); - - $result = $this->mapper->insert($entity); - - $this->assertEquals(3, $result->getId()); - } - - - public function testAssocParameters() { - $sql = 'test'; - $params = [':test' => 1, ':a' => 2]; - - $this->setMapperResult($sql, $params); - $this->mapper->execSql($sql, $params); - } - - - public function testUpdate() { - $sql = 'UPDATE `*PREFIX*table` ' . - 'SET ' . - '`pre_name` = ?,'. - '`email` = ? ' . - 'WHERE `id` = ?'; - - $params = ['john', 'my@email', 1]; - $entity = new Example(); - $entity->setPreName($params[0]); - $entity->setEmail($params[1]); - $entity->setId($params[2]); - - $this->setMapperResult($sql, $params, [], null, null, true); - - $this->mapper->update($entity); - } - - - public function testUpdateNoId() { - $params = ['john', 'my@email']; - $entity = new Example(); - $entity->setPreName($params[0]); - $entity->setEmail($params[1]); - - $this->expectException(\InvalidArgumentException::class); - - $this->mapper->update($entity); - } - - - public function testUpdateNothingChangedNoQuery() { - $params = ['john', 'my@email']; - $entity = new Example(); - $entity->setId(3); - $entity->setEmail($params[1]); - $entity->resetUpdatedFields(); - - $this->db->expects($this->never()) - ->method('prepare'); - - $this->mapper->update($entity); - } - - - public function testMapRowToEntity() { - $entity1 = $this->mapper->mapRow(['pre_name' => 'test1', 'email' => 'test2']); - $entity2 = new Example(); - $entity2->setPreName('test1'); - $entity2->setEmail('test2'); - $entity2->resetUpdatedFields(); - $this->assertEquals($entity2, $entity1); - } - - public function testFindEntities() { - $sql = 'hi'; - $rows = [ - ['pre_name' => 'hi'] - ]; - $entity = new Example(); - $entity->setPreName('hi'); - $entity->resetUpdatedFields(); - $this->setMapperResult($sql, [], $rows, null, null, true); - $result = $this->mapper->findAllEntities($sql); - $this->assertEquals([$entity], $result); - } - - public function testFindEntitiesNotFound() { - $sql = 'hi'; - $rows = []; - $this->setMapperResult($sql, [], $rows); - $result = $this->mapper->findAllEntities($sql); - $this->assertEquals([], $result); - } - - public function testFindEntitiesMultiple() { - $sql = 'hi'; - $rows = [ - ['pre_name' => 'jo'], ['email' => 'ho'] - ]; - $entity1 = new Example(); - $entity1->setPreName('jo'); - $entity1->resetUpdatedFields(); - $entity2 = new Example(); - $entity2->setEmail('ho'); - $entity2->resetUpdatedFields(); - $this->setMapperResult($sql, [], $rows); - $result = $this->mapper->findAllEntities($sql); - $this->assertEquals([$entity1, $entity2], $result); - } -} diff --git a/tests/lib/AppFramework/Db/MapperTestUtility.php b/tests/lib/AppFramework/Db/MapperTestUtility.php deleted file mode 100644 index e17b875e4c4..00000000000 --- a/tests/lib/AppFramework/Db/MapperTestUtility.php +++ /dev/null @@ -1,206 +0,0 @@ -<?php - -/** - * ownCloud - App Framework - * - * @author Bernhard Posselt - * @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com - * - * 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\AppFramework\Db; - -use OCP\DB\IPreparedStatement; -use OCP\DB\IResult; - -/** - * Simple utility class for testing mappers - */ -abstract class MapperTestUtility extends \Test\TestCase { - protected $db; - private $statement; - private $queryAt; - private $prepareAt; - private $fetchAt; - private $iterators; - - - /** - * Run this function before the actual test to either set or initialize the - * db. After this the db can be accessed by using $this->db - */ - protected function setUp(): void { - parent::setUp(); - - $this->db = $this->getMockBuilder( - '\OCP\IDBConnection') - ->disableOriginalConstructor() - ->getMock(); - - $this->statement = $this->createMock(IPreparedStatement::class); - $this->queryAt = 0; - $this->prepareAt = 0; - $this->iterators = []; - $this->fetchAt = 0; - } - - /** - * Checks if an array is associative - * @param array $array - * @return bool true if associative - */ - private function isAssocArray(array $array) { - return array_values($array) !== $array; - } - - /** - * Returns the correct PDO constant based on the value type - * @param $value - * @return int PDO constant - */ - private function getPDOType($value) { - switch (gettype($value)) { - case 'integer': - return \PDO::PARAM_INT; - case 'boolean': - return \PDO::PARAM_BOOL; - default: - return \PDO::PARAM_STR; - } - } - - /** - * Create mocks and set expected results for database queries - * @param string $sql the sql query that you expect to receive - * @param array $arguments the expected arguments for the prepare query - * method - * @param array $returnRows the rows that should be returned for the result - * of the database query. If not provided, it wont be assumed that fetch - * will be called on the result - */ - protected function setMapperResult($sql, $arguments = [], $returnRows = [], - $limit = null, $offset = null, $expectClose = false) { - if ($limit === null && $offset === null) { - $this->db->expects($this->at($this->prepareAt)) - ->method('prepare') - ->with($this->equalTo($sql)) - ->will(($this->returnValue($this->statement))); - } elseif ($limit !== null && $offset === null) { - $this->db->expects($this->at($this->prepareAt)) - ->method('prepare') - ->with($this->equalTo($sql), $this->equalTo($limit)) - ->will(($this->returnValue($this->statement))); - } elseif ($limit === null && $offset !== null) { - $this->db->expects($this->at($this->prepareAt)) - ->method('prepare') - ->with($this->equalTo($sql), - $this->equalTo(null), - $this->equalTo($offset)) - ->will(($this->returnValue($this->statement))); - } else { - $this->db->expects($this->at($this->prepareAt)) - ->method('prepare') - ->with($this->equalTo($sql), - $this->equalTo($limit), - $this->equalTo($offset)) - ->will(($this->returnValue($this->statement))); - } - - $this->iterators[] = new ArgumentIterator($returnRows); - - $iterators = $this->iterators; - $fetchAt = $this->fetchAt; - - $this->statement->expects($this->any()) - ->method('fetch') - ->willReturnCallback( - function () use ($iterators, $fetchAt) { - $iterator = $iterators[$fetchAt]; - $result = $iterator->next(); - - if ($result === false) { - $fetchAt++; - } - - $this->queryAt++; - - return $result; - } - ); - - if ($this->isAssocArray($arguments)) { - foreach ($arguments as $key => $argument) { - $pdoConstant = $this->getPDOType($argument); - $this->statement->expects($this->at($this->queryAt)) - ->method('bindValue') - ->with($this->equalTo($key), - $this->equalTo($argument), - $this->equalTo($pdoConstant)); - $this->queryAt++; - } - } else { - $index = 1; - foreach ($arguments as $argument) { - $pdoConstant = $this->getPDOType($argument); - $this->statement->expects($this->at($this->queryAt)) - ->method('bindValue') - ->with($this->equalTo($index), - $this->equalTo($argument), - $this->equalTo($pdoConstant)); - $index++; - $this->queryAt++; - } - } - - $this->statement->expects($this->at($this->queryAt)) - ->method('execute') - ->willReturnCallback(function ($sql, $p = null, $o = null, $s = null) { - return $this->createMock(IResult::class); - }); - $this->queryAt++; - - - - if ($expectClose) { - $closing = $this->at($this->queryAt); - } else { - $closing = $this->any(); - } - $this->statement->expects($closing)->method('closeCursor'); - $this->queryAt++; - - $this->prepareAt++; - $this->fetchAt++; - } -} - - -class ArgumentIterator { - private $arguments; - - public function __construct($arguments) { - $this->arguments = $arguments; - } - - public function next() { - $result = array_shift($this->arguments); - if ($result === null) { - return false; - } else { - return $result; - } - } -} diff --git a/tests/lib/AppFramework/Http/DispatcherTest.php b/tests/lib/AppFramework/Http/DispatcherTest.php index 8f591f26e58..016bd7efb58 100644 --- a/tests/lib/AppFramework/Http/DispatcherTest.php +++ b/tests/lib/AppFramework/Http/DispatcherTest.php @@ -51,11 +51,12 @@ class TestController extends Controller { /** * @param int $int * @param bool $bool + * @param double $foo * @param int $test - * @param int $test2 + * @param integer $test2 * @return array */ - public function exec($int, $bool, $test = 4, $test2 = 1) { + public function exec($int, $bool, $foo, $test = 4, $test2 = 1) { $this->registerResponder('text', function ($in) { return new JSONResponse(['text' => $in]); }); @@ -315,7 +316,8 @@ class DispatcherTest extends \Test\TestCase { [ 'post' => [ 'int' => '3', - 'bool' => 'false' + 'bool' => 'false', + 'double' => 1.2, ], 'method' => 'POST' ], @@ -346,6 +348,7 @@ class DispatcherTest extends \Test\TestCase { 'post' => [ 'int' => '3', 'bool' => 'false', + 'double' => 1.2, 'test2' => 7 ], 'method' => 'POST', @@ -377,7 +380,8 @@ class DispatcherTest extends \Test\TestCase { [ 'post' => [ 'int' => '3', - 'bool' => 'false' + 'bool' => 'false', + 'double' => 1.2, ], 'urlParams' => [ 'format' => 'text' @@ -410,7 +414,8 @@ class DispatcherTest extends \Test\TestCase { [ 'post' => [ 'int' => '3', - 'bool' => 'false' + 'bool' => 'false', + 'double' => 1.2, ], 'urlParams' => [ 'format' => 'json' @@ -443,7 +448,8 @@ class DispatcherTest extends \Test\TestCase { [ 'post' => [ 'int' => '3', - 'bool' => 'false' + 'bool' => 'false', + 'double' => 1.2, ], 'server' => [ 'HTTP_ACCEPT' => 'application/text, test', @@ -477,7 +483,8 @@ class DispatcherTest extends \Test\TestCase { [ 'post' => [ 'int' => '3', - 'bool' => 'false' + 'bool' => 'false', + 'double' => 1.2, ], 'get' => [ 'format' => 'text' diff --git a/tests/lib/AppFramework/Http/RequestStream.php b/tests/lib/AppFramework/Http/RequestStream.php index 3868ed16505..1a99685e340 100644 --- a/tests/lib/AppFramework/Http/RequestStream.php +++ b/tests/lib/AppFramework/Http/RequestStream.php @@ -7,24 +7,26 @@ namespace Test\AppFramework\Http; * Used to simulate php://input for Request tests */ class RequestStream { - protected $position; - protected $varname; + protected int $position = 0; + protected string $varname = ''; + /* @var resource */ + public $context; - public function stream_open($path, $mode, $options, &$opened_path) { + public function stream_open(string $path, string $mode, int $options, ?string &$opened_path): bool { $url = parse_url($path); - $this->varname = $url["host"]; + $this->varname = $url["host"] ?? ''; $this->position = 0; return true; } - public function stream_read($count) { + public function stream_read(int $count): string { $ret = substr($GLOBALS[$this->varname], $this->position, $count); $this->position += strlen($ret); return $ret; } - public function stream_write($data) { + public function stream_write(string $data): int { $left = substr($GLOBALS[$this->varname], 0, $this->position); $right = substr($GLOBALS[$this->varname], $this->position + strlen($data)); $GLOBALS[$this->varname] = $left . $data . $right; @@ -32,15 +34,15 @@ class RequestStream { return strlen($data); } - public function stream_tell() { + public function stream_tell(): int { return $this->position; } - public function stream_eof() { + public function stream_eof(): bool { return $this->position >= strlen($GLOBALS[$this->varname]); } - public function stream_seek($offset, $whence) { + public function stream_seek(int $offset, int $whence = SEEK_SET): bool { switch ($whence) { case SEEK_SET: if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) { @@ -74,7 +76,7 @@ class RequestStream { } } - public function stream_stat() { + public function stream_stat(): array { $size = strlen($GLOBALS[$this->varname]); $time = time(); $data = [ @@ -96,10 +98,10 @@ class RequestStream { //return false; } - public function stream_metadata($path, $option, $var) { + public function stream_metadata(string $path, int $option, $var): bool { if ($option == STREAM_META_TOUCH) { $url = parse_url($path); - $varname = $url["host"]; + $varname = $url["host"] ?? ''; if (!isset($GLOBALS[$varname])) { $GLOBALS[$varname] = ''; } diff --git a/tests/lib/AppFramework/Http/RequestTest.php b/tests/lib/AppFramework/Http/RequestTest.php index 16875cfb0d8..78e656f5fc3 100644 --- a/tests/lib/AppFramework/Http/RequestTest.php +++ b/tests/lib/AppFramework/Http/RequestTest.php @@ -256,9 +256,20 @@ class RequestTest extends \Test\TestCase { $this->assertSame('someothertestvalue', $result['propertyB']); } - public function testNotJsonPost() { + public function notJsonDataProvider() { + return [ + ['this is not valid json'], + ['"just a string"'], + ['{"just a string"}'], + ]; + } + + /** + * @dataProvider notJsonDataProvider + */ + public function testNotJsonPost($testData) { global $data; - $data = 'this is not valid json'; + $data = $testData; $vars = [ 'method' => 'POST', 'server' => ['CONTENT_TYPE' => 'application/json; utf-8'] diff --git a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php index 7e7140971e4..7d07bffc46b 100644 --- a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php @@ -25,6 +25,7 @@ namespace Test\AppFramework\Middleware\PublicShare; use OC\AppFramework\Middleware\PublicShare\Exceptions\NeedAuthenticationException; use OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware; +use OC\Security\Bruteforce\Throttler; use OCP\AppFramework\AuthPublicShareController; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\NotFoundResponse; @@ -44,6 +45,8 @@ class PublicShareMiddlewareTest extends \Test\TestCase { private $session; /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ private $config; + /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ + private $throttler; /** @var PublicShareMiddleware */ private $middleware; @@ -55,11 +58,13 @@ class PublicShareMiddlewareTest extends \Test\TestCase { $this->request = $this->createMock(IRequest::class); $this->session = $this->createMock(ISession::class); $this->config = $this->createMock(IConfig::class); + $this->throttler = $this->createMock(Throttler::class); $this->middleware = new PublicShareMiddleware( $this->request, $this->session, - $this->config + $this->config, + $this->throttler ); } diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php index 22fad4ab61f..4b2619a3761 100644 --- a/tests/lib/AppTest.php +++ b/tests/lib/AppTest.php @@ -346,6 +346,7 @@ class AppTest extends \Test\TestCase { 'oauth2', 'provisioning_api', 'settings', + 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine', @@ -368,6 +369,7 @@ class AppTest extends \Test\TestCase { 'oauth2', 'provisioning_api', 'settings', + 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine', @@ -391,6 +393,7 @@ class AppTest extends \Test\TestCase { 'oauth2', 'provisioning_api', 'settings', + 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine', @@ -414,6 +417,7 @@ class AppTest extends \Test\TestCase { 'oauth2', 'provisioning_api', 'settings', + 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine', @@ -437,6 +441,7 @@ class AppTest extends \Test\TestCase { 'oauth2', 'provisioning_api', 'settings', + 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine', @@ -517,11 +522,11 @@ class AppTest extends \Test\TestCase { ); $apps = \OC_App::getEnabledApps(); - $this->assertEquals(['files', 'app3', 'cloud_federation_api', 'dav', 'federatedfilesharing', 'lookup_server_connector', 'oauth2', 'provisioning_api', 'settings', 'twofactor_backupcodes', 'viewer', 'workflowengine'], $apps); + $this->assertEquals(['files', 'app3', 'cloud_federation_api', 'dav', 'federatedfilesharing', 'lookup_server_connector', 'oauth2', 'provisioning_api', 'settings', 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine'], $apps); // mock should not be called again here $apps = \OC_App::getEnabledApps(); - $this->assertEquals(['files', 'app3', 'cloud_federation_api', 'dav', 'federatedfilesharing', 'lookup_server_connector', 'oauth2', 'provisioning_api', 'settings', 'twofactor_backupcodes', 'viewer', 'workflowengine'], $apps); + $this->assertEquals(['files', 'app3', 'cloud_federation_api', 'dav', 'federatedfilesharing', 'lookup_server_connector', 'oauth2', 'provisioning_api', 'settings', 'theming', 'twofactor_backupcodes', 'viewer', 'workflowengine'], $apps); $this->restoreAppConfig(); \OC_User::setUserId(null); diff --git a/tests/lib/Authentication/Login/EmailLoginCommandTest.php b/tests/lib/Authentication/Login/EmailLoginCommandTest.php index 9de372148b9..0e70c40a1df 100644 --- a/tests/lib/Authentication/Login/EmailLoginCommandTest.php +++ b/tests/lib/Authentication/Login/EmailLoginCommandTest.php @@ -55,7 +55,7 @@ class EmailLoginCommandTest extends ALoginCommandTest { public function testProcessNotAnEmailLogin() { $data = $this->getFailedLoginData(); - $this->userManager->expects($this->once()) + $this->userManager->expects($this->never()) ->method('getByEmail') ->with($this->username) ->willReturn([]); @@ -67,9 +67,10 @@ class EmailLoginCommandTest extends ALoginCommandTest { public function testProcessDuplicateEmailLogin() { $data = $this->getFailedLoginData(); + $data->setUsername('user@example.com'); $this->userManager->expects($this->once()) ->method('getByEmail') - ->with($this->username) + ->with('user@example.com') ->willReturn([ $this->createMock(IUser::class), $this->createMock(IUser::class), diff --git a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php index 1ef0aa80817..d6e8dba31be 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * @copyright Copyright (c) 2018 Roeland Jago Douma <roeland@famdouma.nl> * @@ -33,7 +36,9 @@ use OC\Authentication\Token\PublicKeyTokenProvider; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; +use OCP\IDBConnection; use OCP\Security\ICrypto; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; @@ -46,6 +51,8 @@ class PublicKeyTokenProviderTest extends TestCase { private $crypto; /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ private $config; + /** @var IDBConnection|MockObject */ + private IDBConnection $db; /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ private $logger; /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ @@ -66,14 +73,21 @@ class PublicKeyTokenProviderTest extends TestCase { ['secret', '', '1f4h9s'], ['openssl', [], []], ]); + $this->db = $this->createMock(IDBConnection::class); $this->logger = $this->createMock(LoggerInterface::class); $this->timeFactory = $this->createMock(ITimeFactory::class); $this->time = 1313131; $this->timeFactory->method('getTime') ->willReturn($this->time); - $this->tokenProvider = new PublicKeyTokenProvider($this->mapper, $this->crypto, $this->config, $this->logger, - $this->timeFactory); + $this->tokenProvider = new PublicKeyTokenProvider( + $this->mapper, + $this->crypto, + $this->config, + $this->db, + $this->logger, + $this->timeFactory, + ); } public function testGenerateToken() { @@ -296,9 +310,12 @@ class PublicKeyTokenProviderTest extends TestCase { } public function testInvalidateToken() { - $this->mapper->expects($this->once()) + $this->mapper->expects($this->at(0)) ->method('invalidate') ->with(hash('sha512', 'token7'.'1f4h9s')); + $this->mapper->expects($this->at(1)) + ->method('invalidate') + ->with(hash('sha512', 'token7')); $this->tokenProvider->invalidateToken('token7'); } @@ -429,13 +446,22 @@ class PublicKeyTokenProviderTest extends TestCase { public function testGetInvalidToken() { $this->expectException(InvalidTokenException::class); - $this->mapper->method('getToken') + $this->mapper->expects($this->at(0)) + ->method('getToken') ->with( - $this->callback(function (string $token) { + $this->callback(function (string $token): bool { return hash('sha512', 'unhashedToken'.'1f4h9s') === $token; }) )->willThrowException(new DoesNotExistException('nope')); + $this->mapper->expects($this->at(1)) + ->method('getToken') + ->with( + $this->callback(function (string $token): bool { + return hash('sha512', 'unhashedToken') === $token; + }) + )->willThrowException(new DoesNotExistException('nope')); + $this->tokenProvider->getToken('unhashedToken'); } diff --git a/tests/lib/Calendar/ManagerTest.php b/tests/lib/Calendar/ManagerTest.php index ba30be1b548..540fd5c0c69 100644 --- a/tests/lib/Calendar/ManagerTest.php +++ b/tests/lib/Calendar/ManagerTest.php @@ -28,6 +28,7 @@ use OC\Calendar\Manager; use OCP\AppFramework\Utility\ITimeFactory; use OCP\Calendar\ICalendar; use OCP\Calendar\ICreateFromString; +use OCP\Calendar\IHandleImipMessage; use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; @@ -35,6 +36,12 @@ use Sabre\VObject\Document; use Sabre\VObject\Reader; use Test\TestCase; +/* + * This allows us to create Mock object supporting both interfaces + */ +interface ICreateFromStringAndHandleImipMessage extends ICreateFromString, IHandleImipMessage { +} + class ManagerTest extends TestCase { /** @var Coordinator|MockObject */ @@ -334,7 +341,7 @@ class ManagerTest extends TestCase { 'getCalendarsForPrincipal' ]) ->getMock(); - $calendar = $this->createMock(ICreateFromString::class); + $calendar = $this->createMock(ICreateFromStringAndHandleImipMessage::class); $principalUri = 'principals/user/linus'; $sender = 'pierre@general-store.com'; $recipient = 'linus@stardew-tent-living.com'; @@ -371,7 +378,7 @@ class ManagerTest extends TestCase { 'getCalendarsForPrincipal' ]) ->getMock(); - $calendar = $this->createMock(ICreateFromString::class); + $calendar = $this->createMock(ICreateFromStringAndHandleImipMessage::class); $principalUri = 'principals/user/linus'; $sender = 'pierre@general-store.com'; $recipient = 'linus@stardew-tent-living.com'; @@ -495,7 +502,7 @@ class ManagerTest extends TestCase { $sender = 'clint@stardew-blacksmiths.com'; $recipient = 'pierre@general-store.com'; $replyTo = 'linus@stardew-tent-living.com'; - $calendar = $this->createMock(ICreateFromString::class); + $calendar = $this->createMock(ICreateFromStringAndHandleImipMessage::class); $calendarData = $this->getVCalendarCancel(); $this->time->expects(self::once()) @@ -532,7 +539,7 @@ class ManagerTest extends TestCase { $sender = 'linus@stardew-tent-living.com'; $recipient = 'pierre@general-store.com'; $replyTo = null; - $calendar = $this->createMock(ICreateFromString::class); + $calendar = $this->createMock(ICreateFromStringAndHandleImipMessage::class); $calendarData = $this->getVCalendarCancel(); $this->time->expects(self::once()) diff --git a/tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php b/tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php index aa609aedbb9..a038058069e 100644 --- a/tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php +++ b/tests/lib/Contacts/ContactsMenu/ContactsStoreTest.php @@ -140,6 +140,10 @@ class ContactsStoreTest extends TestCase { public function testGetContactsWithoutBinaryImage() { /** @var IUser|MockObject $user */ $user = $this->createMock(IUser::class); + $this->urlGenerator->expects($this->any()) + ->method('linkToRouteAbsolute') + ->with('core.avatar.getAvatar', $this->anything()) + ->willReturn('https://urlToNcAvatar.test'); $this->contactsManager->expects($this->once()) ->method('search') ->with($this->equalTo(''), $this->equalTo(['FN', 'EMAIL'])) @@ -163,7 +167,7 @@ class ContactsStoreTest extends TestCase { $entries = $this->contactsStore->getContacts($user, ''); $this->assertCount(2, $entries); - $this->assertNull($entries[1]->getAvatar()); + $this->assertSame('https://urlToNcAvatar.test', $entries[1]->getAvatar()); } public function testGetContactsWithoutAvatarURI() { @@ -859,6 +863,7 @@ class ContactsStoreTest extends TestCase { ['core', 'shareapi_restrict_user_enumeration_to_phone', 'no', 'no'], ['core', 'shareapi_restrict_user_enumeration_full_match', 'yes', 'yes'], ['core', 'shareapi_exclude_groups', 'no', 'yes'], + ['core', 'shareapi_exclude_groups_list', '', ''], ['core', 'shareapi_only_share_with_group_members', 'no', 'no'], ]); diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php index 70e8dd74a1e..c02a95a4162 100644 --- a/tests/lib/ContactsManagerTest.php +++ b/tests/lib/ContactsManagerTest.php @@ -232,9 +232,9 @@ class ContactsManagerTest extends \Test\TestCase { // register the address book $this->cm->registerAddressBook($addressbook); - $all_books = $this->cm->getAddressBooks(); + $all_books = $this->cm->getUserAddressBooks(); $this->assertEquals(1, count($all_books)); - $this->assertEquals('A very simple Addressbook', $all_books['SIMPLE_ADDRESS_BOOK']); + $this->assertEquals($addressbook, $all_books['SIMPLE_ADDRESS_BOOK']); } } diff --git a/tests/lib/DB/MigrationsTest.php b/tests/lib/DB/MigrationsTest.php index 3d115f25adf..b7d49b565ac 100644 --- a/tests/lib/DB/MigrationsTest.php +++ b/tests/lib/DB/MigrationsTest.php @@ -31,7 +31,6 @@ use OCP\Migration\IMigrationStep; * @package Test\DB */ class MigrationsTest extends \Test\TestCase { - /** @var MigrationService | \PHPUnit\Framework\MockObject\MockObject */ private $migrationService; /** @var \PHPUnit\Framework\MockObject\MockObject | IDBConnection $db */ @@ -247,6 +246,9 @@ class MigrationsTest extends \Test\TestCase { ->willReturn(\str_repeat('a', 30)); $primaryKey = $this->createMock(Index::class); + $primaryKey->expects($this->once()) + ->method('getName') + ->willReturn(\str_repeat('a', 30)); $table->expects($this->once()) ->method('getColumns') diff --git a/tests/lib/Encryption/Keys/StorageTest.php b/tests/lib/Encryption/Keys/StorageTest.php index bb7bbbcd7c1..d1c0257cc6e 100644 --- a/tests/lib/Encryption/Keys/StorageTest.php +++ b/tests/lib/Encryption/Keys/StorageTest.php @@ -31,22 +31,23 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class StorageTest extends TestCase { - /** @var Storage */ protected $storage; - /** @var \PHPUnit\Framework\MockObject\MockObject */ + /** @var MockObject|\OC\Encryption\Util */ protected $util; - /** @var \PHPUnit\Framework\MockObject\MockObject */ + /** @var MockObject|View */ protected $view; - /** @var \PHPUnit\Framework\MockObject\MockObject */ + /** @var MockObject|IConfig */ protected $config; /** @var MockObject|ICrypto */ protected $crypto; + private array $mkdirStack = []; + protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Encryption/UtilTest.php b/tests/lib/Encryption/UtilTest.php index 248377fc698..c2bc4ac55bd 100644 --- a/tests/lib/Encryption/UtilTest.php +++ b/tests/lib/Encryption/UtilTest.php @@ -13,7 +13,6 @@ use OCP\IUserManager; use Test\TestCase; class UtilTest extends TestCase { - /** * block size will always be 8192 for a PHP stream * @see https://bugs.php.net/bug.php?id=21641 diff --git a/tests/lib/ErrorHandlerTest.php b/tests/lib/ErrorHandlerTest.php index ea53e67005c..f6bf850f0b5 100644 --- a/tests/lib/ErrorHandlerTest.php +++ b/tests/lib/ErrorHandlerTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * ownCloud * @@ -22,7 +25,26 @@ namespace Test; -class ErrorHandlerTest extends \Test\TestCase { +use OC\Log\ErrorHandler; +use OCP\ILogger; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; + +class ErrorHandlerTest extends TestCase { + + /** @var MockObject */ + private LoggerInterface $logger; + + private ErrorHandler $errorHandler; + + protected function setUp(): void { + parent::setUp(); + + $this->logger = $this->createMock(LoggerInterface::class); + $this->errorHandler = new ErrorHandler( + $this->logger + ); + } /** * provide username, password combinations for testRemovePassword @@ -47,24 +69,19 @@ class ErrorHandlerTest extends \Test\TestCase { * @param string $username * @param string $password */ - public function testRemovePassword($username, $password) { + public function testRemovePasswordFromError($username, $password) { $url = 'http://'.$username.':'.$password.'@owncloud.org'; $expectedResult = 'http://xxx:xxx@owncloud.org'; - $result = TestableErrorHandler::testRemovePassword($url); + $this->logger->expects(self::once()) + ->method('log') + ->with( + ILogger::ERROR, + 'Could not reach ' . $expectedResult . ' at file#4', + ['app' => 'PHP'], + ); - $this->assertEquals($expectedResult, $result); - } -} + $result = $this->errorHandler->onError(E_USER_ERROR, 'Could not reach ' . $url, 'file', 4); -/** - * dummy class to access protected methods of \OC\Log\ErrorHandler - */ -class TestableErrorHandler extends \OC\Log\ErrorHandler { - - /** - * @param string $msg - */ - public static function testRemovePassword($msg) { - return self::removePassword($msg); + self::assertTrue($result); } } diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStorageOverwrite.php b/tests/lib/Files/ObjectStore/ObjectStoreStorageOverwrite.php index 5872056e42d..b85f6289c94 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreStorageOverwrite.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreStorageOverwrite.php @@ -37,4 +37,8 @@ class ObjectStoreStorageOverwrite extends ObjectStoreStorage { public function getObjectStore(): IObjectStore { return $this->objectStore; } + + public function setValidateWrites(bool $validate) { + $this->validateWrites = $validate; + } } diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php index 5ebfd48d1a6..1bebaf6c4ba 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreStorageTest.php @@ -181,6 +181,15 @@ class ObjectStoreStorageTest extends Storage { $this->assertFalse($this->instance->file_exists('test.txt')); } + public function testWriteObjectSilentFailureNoCheck() { + $objectStore = $this->instance->getObjectStore(); + $this->instance->setObjectStore(new FailWriteObjectStore($objectStore)); + $this->instance->setValidateWrites(false); + + $this->instance->file_put_contents('test.txt', 'foo'); + $this->assertTrue($this->instance->file_exists('test.txt')); + } + public function testDeleteObjectFailureKeepCache() { $objectStore = $this->instance->getObjectStore(); $this->instance->setObjectStore(new FailDeleteObjectStore($objectStore)); diff --git a/tests/lib/Files/SimpleFS/SimpleFolderTest.php b/tests/lib/Files/SimpleFS/SimpleFolderTest.php index 50714b8356e..9710b6f438b 100644 --- a/tests/lib/Files/SimpleFS/SimpleFolderTest.php +++ b/tests/lib/Files/SimpleFS/SimpleFolderTest.php @@ -28,6 +28,7 @@ use OC\Files\Storage\Temporary; use OCP\Files\Folder; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFile; +use OCP\Files\SimpleFS\ISimpleFolder; use Test\Traits\MountProviderTrait; use Test\Traits\UserTrait; @@ -109,4 +110,22 @@ class SimpleFolderTest extends \Test\TestCase { $this->assertInstanceOf(ISimpleFile::class, $result[0]); $this->assertInstanceOf(ISimpleFile::class, $result[1]); } + + public function testGetFolder() { + $this->folder->newFolder('exists'); + + $result = $this->simpleFolder->getFolder('exists'); + $this->assertInstanceOf(ISimpleFolder::class, $result); + + $this->expectException(NotFoundException::class); + $this->simpleFolder->getFolder('not-exists'); + } + + public function testNewFolder() { + $result = $this->simpleFolder->newFolder('folder'); + $this->assertInstanceOf(ISimpleFolder::class, $result); + $result->newFile('file'); + + $this->assertTrue($this->folder->nodeExists('folder')); + } } diff --git a/tests/lib/Files/Stream/EncryptionTest.php b/tests/lib/Files/Stream/EncryptionTest.php index 5516c0bf658..79a845fe7a6 100644 --- a/tests/lib/Files/Stream/EncryptionTest.php +++ b/tests/lib/Files/Stream/EncryptionTest.php @@ -12,6 +12,7 @@ use OCP\IConfig; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class EncryptionTest extends \Test\TestCase { + public const DEFAULT_WRAPPER = '\OC\Files\Stream\Encryption'; /** @var \OCP\Encryption\IEncryptionModule | \PHPUnit\Framework\MockObject\MockObject */ private $encryptionModule; @@ -22,7 +23,7 @@ class EncryptionTest extends \Test\TestCase { * @param integer $unencryptedSize * @return resource */ - protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = '\OC\Files\Stream\Encryption') { + protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = self::DEFAULT_WRAPPER, $unencryptedSizeOnClose = 0) { clearstatcache(); $size = filesize($fileName); $source = fopen($fileName, $mode); @@ -64,9 +65,10 @@ class EncryptionTest extends \Test\TestCase { $entry = new CacheEntry([ 'fileid' => 5, 'encryptedVersion' => 2, + 'unencrypted_size' => $unencryptedSizeOnClose, ]); $cache->expects($this->any())->method('get')->willReturn($entry); - $cache->expects($this->any())->method('update')->with(5, ['encrypted' => 3, 'encryptedVersion' => 3]); + $cache->expects($this->any())->method('update')->with(5, ['encrypted' => 3, 'encryptedVersion' => 3, 'unencrypted_size' => $unencryptedSizeOnClose]); return $wrapper::wrap($source, $internalPath, @@ -188,7 +190,7 @@ class EncryptionTest extends \Test\TestCase { public function testWriteRead() { $fileName = tempnam("/tmp", "FOO"); - $stream = $this->getStream($fileName, 'w+', 0); + $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 6); $this->assertEquals(6, fwrite($stream, 'foobar')); fclose($stream); @@ -196,7 +198,7 @@ class EncryptionTest extends \Test\TestCase { $this->assertEquals('foobar', fread($stream, 100)); fclose($stream); - $stream = $this->getStream($fileName, 'r+', 6); + $stream = $this->getStream($fileName, 'r+', 6, self::DEFAULT_WRAPPER, 6); $this->assertEquals(3, fwrite($stream, 'bar')); fclose($stream); @@ -209,7 +211,7 @@ class EncryptionTest extends \Test\TestCase { public function testRewind() { $fileName = tempnam("/tmp", "FOO"); - $stream = $this->getStream($fileName, 'w+', 0); + $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 6); $this->assertEquals(6, fwrite($stream, 'foobar')); $this->assertEquals(true, rewind($stream)); $this->assertEquals('foobar', fread($stream, 100)); @@ -227,7 +229,7 @@ class EncryptionTest extends \Test\TestCase { public function testSeek() { $fileName = tempnam("/tmp", "FOO"); - $stream = $this->getStream($fileName, 'w+', 0); + $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, 9); $this->assertEquals(6, fwrite($stream, 'foobar')); $this->assertEquals(0, fseek($stream, 3)); $this->assertEquals(6, fwrite($stream, 'foobar')); @@ -261,7 +263,7 @@ class EncryptionTest extends \Test\TestCase { $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile); // write it $fileName = tempnam("/tmp", "FOO"); - $stream = $this->getStream($fileName, 'w+', 0); + $stream = $this->getStream($fileName, 'w+', 0, self::DEFAULT_WRAPPER, strlen($expectedData)); // while writing the file from the beginning to the end we should never try // to read parts of the file. This should only happen for write operations // in the middle of a file @@ -302,7 +304,7 @@ class EncryptionTest extends \Test\TestCase { $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile); // write it $fileName = tempnam("/tmp", "FOO"); - $stream = $this->getStream($fileName, 'w+', 0, '\Test\Files\Stream\DummyEncryptionWrapper'); + $stream = $this->getStream($fileName, 'w+', 0, '\Test\Files\Stream\DummyEncryptionWrapper', strlen($expectedData)); // while writing the file from the beginning to the end we should never try // to read parts of the file. This should only happen for write operations // in the middle of a file @@ -311,7 +313,7 @@ class EncryptionTest extends \Test\TestCase { fclose($stream); // read it all - $stream = $this->getStream($fileName, 'r', strlen($expectedData), '\Test\Files\Stream\DummyEncryptionWrapper'); + $stream = $this->getStream($fileName, 'r', strlen($expectedData), '\Test\Files\Stream\DummyEncryptionWrapper', strlen($expectedData)); $data = stream_get_contents($stream); fclose($stream); diff --git a/tests/lib/Files/ViewTest.php b/tests/lib/Files/ViewTest.php index 86101d79a1e..2189e7c09f4 100644 --- a/tests/lib/Files/ViewTest.php +++ b/tests/lib/Files/ViewTest.php @@ -2709,4 +2709,23 @@ class ViewTest extends \Test\TestCase { $this->assertEquals(25, $info->getUploadTime()); $this->assertEquals(0, $info->getCreationTime()); } + + public function testFopenGone() { + $storage = new Temporary([]); + $scanner = $storage->getScanner(); + $storage->file_put_contents('foo.txt', 'bar'); + $scanner->scan(''); + $cache = $storage->getCache(); + + Filesystem::mount($storage, [], '/test/'); + $view = new View('/test'); + + $storage->unlink('foo.txt'); + + $this->assertTrue($cache->inCache('foo.txt')); + + $this->assertFalse($view->fopen('foo.txt', 'r')); + + $this->assertFalse($cache->inCache('foo.txt')); + } } diff --git a/tests/lib/Group/ManagerTest.php b/tests/lib/Group/ManagerTest.php index d689fd4eb7a..65210bcc0f7 100644 --- a/tests/lib/Group/ManagerTest.php +++ b/tests/lib/Group/ManagerTest.php @@ -26,6 +26,7 @@ namespace Test\Group; use OC\Group\Database; use OC\User\Manager; use OCP\GroupInterface; +use OCP\ICacheFactory; use OCP\IUser; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; @@ -39,6 +40,8 @@ class ManagerTest extends TestCase { protected $dispatcher; /** @var LoggerInterface|MockObject */ protected $logger; + /** @var ICacheFactory|MockObject */ + private $cache; protected function setUp(): void { parent::setUp(); @@ -46,6 +49,7 @@ class ManagerTest extends TestCase { $this->userManager = $this->createMock(Manager::class); $this->dispatcher = $this->createMock(EventDispatcherInterface::class); $this->logger = $this->createMock(LoggerInterface::class); + $this->cache = $this->createMock(ICacheFactory::class); } private function getTestUser($userId) { @@ -107,7 +111,7 @@ class ManagerTest extends TestCase { ->with('group1') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $group = $manager->get('group1'); @@ -116,7 +120,7 @@ class ManagerTest extends TestCase { } public function testGetNoBackend() { - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $this->assertNull($manager->get('group1')); } @@ -131,7 +135,7 @@ class ManagerTest extends TestCase { ->with('group1') ->willReturn(false); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $this->assertNull($manager->get('group1')); @@ -141,7 +145,7 @@ class ManagerTest extends TestCase { $backend = new \Test\Util\Group\Dummy(); $backend->createGroup('group1'); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $group = $manager->get('group1'); @@ -168,7 +172,7 @@ class ManagerTest extends TestCase { ->with('group1') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend1); $manager->addBackend($backend2); @@ -194,7 +198,7 @@ class ManagerTest extends TestCase { return true; }); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $group = $manager->createGroup('group1'); @@ -223,7 +227,7 @@ class ManagerTest extends TestCase { ->method('getGroupDetails') ->willReturn([]); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $group = $manager->createGroup('group1'); @@ -240,7 +244,7 @@ class ManagerTest extends TestCase { $backend->expects($this->never()) ->method('createGroup'); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $group = $manager->createGroup('group1'); @@ -261,7 +265,7 @@ class ManagerTest extends TestCase { ->with('group1') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $groups = $manager->search('1'); @@ -295,7 +299,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend1); $manager->addBackend($backend2); @@ -332,7 +336,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend1); $manager->addBackend($backend2); @@ -359,7 +363,7 @@ class ManagerTest extends TestCase { /** @var \OC\User\Manager $userManager */ $userManager = $this->createMock(Manager::class); - $manager = new \OC\Group\Manager($userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $groups = $manager->search('1'); @@ -380,7 +384,7 @@ class ManagerTest extends TestCase { ->with('group1') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $groups = $manager->getUserGroups($this->getTestUser('user1')); @@ -398,7 +402,7 @@ class ManagerTest extends TestCase { ->with('myUID') ->willReturn(['123', 'abc']); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); /** @var \OC\User\User|\PHPUnit\Framework\MockObject\MockObject $user */ @@ -428,7 +432,7 @@ class ManagerTest extends TestCase { ->with('group1') ->willReturn(false); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); /** @var \OC\User\User|\PHPUnit\Framework\MockObject\MockObject $user */ @@ -454,7 +458,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $this->assertTrue($manager->isInGroup('user1', 'group1')); @@ -473,7 +477,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $this->assertTrue($manager->isAdmin('user1')); @@ -492,7 +496,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $this->assertFalse($manager->isAdmin('user1')); @@ -523,7 +527,7 @@ class ManagerTest extends TestCase { ->method('groupExists') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend1); $manager->addBackend($backend2); @@ -582,7 +586,7 @@ class ManagerTest extends TestCase { } }); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', 'user3'); @@ -642,7 +646,7 @@ class ManagerTest extends TestCase { } }); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', 'user3', 1); @@ -706,7 +710,7 @@ class ManagerTest extends TestCase { } }); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', 'user3', 1, 1); @@ -746,7 +750,7 @@ class ManagerTest extends TestCase { } }); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', ''); @@ -785,7 +789,7 @@ class ManagerTest extends TestCase { } }); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', '', 1); @@ -824,7 +828,7 @@ class ManagerTest extends TestCase { } }); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $users = $manager->displayNamesInGroup('testgroup', '', 1, 1); @@ -852,7 +856,7 @@ class ManagerTest extends TestCase { ->with('group1') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); // prime cache @@ -895,7 +899,7 @@ class ManagerTest extends TestCase { ->method('removeFromGroup') ->willReturn(true); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); // prime cache @@ -925,7 +929,7 @@ class ManagerTest extends TestCase { ->with('user1') ->willReturn(null); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); $groups = $manager->getUserIdGroups('user1'); @@ -951,7 +955,7 @@ class ManagerTest extends TestCase { ['group2', ['gid' => 'group2']], ]); - $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger); + $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache); $manager->addBackend($backend); // group with display name diff --git a/tests/lib/Http/Client/ClientServiceTest.php b/tests/lib/Http/Client/ClientServiceTest.php index 94f4d51ecee..ed1165236aa 100644 --- a/tests/lib/Http/Client/ClientServiceTest.php +++ b/tests/lib/Http/Client/ClientServiceTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * Copyright (c) 2015 Lukas Reschke <lukas@owncloud.com> * This file is licensed under the Affero General Public License version 3 or @@ -14,9 +17,9 @@ use GuzzleHttp\Handler\CurlHandler; use OC\Http\Client\Client; use OC\Http\Client\ClientService; use OC\Http\Client\DnsPinMiddleware; -use OC\Http\Client\LocalAddressChecker; use OCP\ICertificateManager; use OCP\IConfig; +use OCP\Security\IRemoteHostValidator; /** * Class ClientServiceTest @@ -33,13 +36,13 @@ class ClientServiceTest extends \Test\TestCase { ->method('addDnsPinning') ->willReturn(function () { }); - $localAddressChecker = $this->createMock(LocalAddressChecker::class); + $remoteHostValidator = $this->createMock(IRemoteHostValidator::class); $clientService = new ClientService( $config, $certificateManager, $dnsPinMiddleware, - $localAddressChecker + $remoteHostValidator ); $handler = new CurlHandler(); @@ -52,7 +55,7 @@ class ClientServiceTest extends \Test\TestCase { $config, $certificateManager, $guzzleClient, - $localAddressChecker + $remoteHostValidator ), $clientService->newClient() ); diff --git a/tests/lib/Http/Client/ClientTest.php b/tests/lib/Http/Client/ClientTest.php index 141c6190cd9..93948a5daf3 100644 --- a/tests/lib/Http/Client/ClientTest.php +++ b/tests/lib/Http/Client/ClientTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * Copyright (c) 2015 Lukas Reschke <lukas@owncloud.com> * This file is licensed under the Affero General Public License version 3 or @@ -10,12 +13,13 @@ namespace Test\Http\Client; use GuzzleHttp\Psr7\Response; use OC\Http\Client\Client; -use OC\Http\Client\LocalAddressChecker; use OC\Security\CertificateManager; use OCP\Http\Client\LocalServerException; use OCP\ICertificateManager; use OCP\IConfig; +use OCP\Security\IRemoteHostValidator; use PHPUnit\Framework\MockObject\MockObject; +use function parse_url; /** * Class ClientTest @@ -29,8 +33,8 @@ class ClientTest extends \Test\TestCase { private $client; /** @var IConfig|MockObject */ private $config; - /** @var LocalAddressChecker|MockObject */ - private $localAddressChecker; + /** @var IRemoteHostValidator|MockObject */ + private IRemoteHostValidator $remoteHostValidator; /** @var array */ private $defaultRequestOptions; @@ -39,12 +43,12 @@ class ClientTest extends \Test\TestCase { $this->config = $this->createMock(IConfig::class); $this->guzzleClient = $this->createMock(\GuzzleHttp\Client::class); $this->certificateManager = $this->createMock(ICertificateManager::class); - $this->localAddressChecker = $this->createMock(LocalAddressChecker::class); + $this->remoteHostValidator = $this->createMock(IRemoteHostValidator::class); $this->client = new Client( $this->config, $this->certificateManager, $this->guzzleClient, - $this->localAddressChecker + $this->remoteHostValidator ); } @@ -146,21 +150,22 @@ class ClientTest extends \Test\TestCase { public function dataPreventLocalAddress():array { return [ - ['localhost/foo.bar'], - ['localHost/foo.bar'], - ['random-host/foo.bar'], - ['[::1]/bla.blub'], - ['[::]/bla.blub'], - ['192.168.0.1'], - ['172.16.42.1'], - ['[fdf8:f53b:82e4::53]/secret.ics'], - ['[fe80::200:5aee:feaa:20a2]/secret.ics'], - ['[0:0:0:0:0:0:10.0.0.1]/secret.ics'], - ['[0:0:0:0:0:ffff:127.0.0.0]/secret.ics'], - ['10.0.0.1'], - ['another-host.local'], - ['service.localhost'], - ['!@#$'], // test invalid url + ['https://localhost/foo.bar'], + ['https://localHost/foo.bar'], + ['https://random-host/foo.bar'], + ['https://[::1]/bla.blub'], + ['https://[::]/bla.blub'], + ['https://192.168.0.1'], + ['https://172.16.42.1'], + ['https://[fdf8:f53b:82e4::53]/secret.ics'], + ['https://[fe80::200:5aee:feaa:20a2]/secret.ics'], + ['https://[0:0:0:0:0:0:10.0.0.1]/secret.ics'], + ['https://[0:0:0:0:0:ffff:127.0.0.0]/secret.ics'], + ['https://10.0.0.1'], + ['https://another-host.local'], + ['https://service.localhost'], + ['!@#$', true], // test invalid url + ['https://normal.host.com'], ]; } @@ -174,9 +179,7 @@ class ClientTest extends \Test\TestCase { ->with('allow_local_remote_servers', false) ->willReturn(true); -// $this->expectException(LocalServerException::class); - - self::invokePrivate($this->client, 'preventLocalAddress', ['http://' . $uri, []]); + self::invokePrivate($this->client, 'preventLocalAddress', [$uri, []]); } /** @@ -187,9 +190,7 @@ class ClientTest extends \Test\TestCase { $this->config->expects($this->never()) ->method('getSystemValueBool'); -// $this->expectException(LocalServerException::class); - - self::invokePrivate($this->client, 'preventLocalAddress', ['http://' . $uri, [ + self::invokePrivate($this->client, 'preventLocalAddress', [$uri, [ 'nextcloud' => ['allow_local_address' => true], ]]); } @@ -199,14 +200,14 @@ class ClientTest extends \Test\TestCase { * @param string $uri */ public function testPreventLocalAddressOnGet(string $uri): void { + $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->localAddressChecker - ->expects($this->once()) - ->method('ThrowIfLocalAddress') - ->with('http://' . $uri) - ->will($this->throwException(new LocalServerException())); + $this->remoteHostValidator + ->method('isValid') + ->with($host) + ->willReturn(false); - $this->client->get('http://' . $uri); + $this->client->get($uri); } /** @@ -214,14 +215,14 @@ class ClientTest extends \Test\TestCase { * @param string $uri */ public function testPreventLocalAddressOnHead(string $uri): void { + $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->localAddressChecker - ->expects($this->once()) - ->method('ThrowIfLocalAddress') - ->with('http://' . $uri) - ->will($this->throwException(new LocalServerException())); + $this->remoteHostValidator + ->method('isValid') + ->with($host) + ->willReturn(false); - $this->client->head('http://' . $uri); + $this->client->head($uri); } /** @@ -229,14 +230,14 @@ class ClientTest extends \Test\TestCase { * @param string $uri */ public function testPreventLocalAddressOnPost(string $uri): void { + $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->localAddressChecker - ->expects($this->once()) - ->method('ThrowIfLocalAddress') - ->with('http://' . $uri) - ->will($this->throwException(new LocalServerException())); + $this->remoteHostValidator + ->method('isValid') + ->with($host) + ->willReturn(false); - $this->client->post('http://' . $uri); + $this->client->post($uri); } /** @@ -244,14 +245,14 @@ class ClientTest extends \Test\TestCase { * @param string $uri */ public function testPreventLocalAddressOnPut(string $uri): void { + $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->localAddressChecker - ->expects($this->once()) - ->method('ThrowIfLocalAddress') - ->with('http://' . $uri) - ->will($this->throwException(new LocalServerException())); + $this->remoteHostValidator + ->method('isValid') + ->with($host) + ->willReturn(false); - $this->client->put('http://' . $uri); + $this->client->put($uri); } /** @@ -259,14 +260,14 @@ class ClientTest extends \Test\TestCase { * @param string $uri */ public function testPreventLocalAddressOnDelete(string $uri): void { + $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->localAddressChecker - ->expects($this->once()) - ->method('ThrowIfLocalAddress') - ->with('http://' . $uri) - ->will($this->throwException(new LocalServerException())); + $this->remoteHostValidator + ->method('isValid') + ->with($host) + ->willReturn(false); - $this->client->delete('http://' . $uri); + $this->client->delete($uri); } private function setUpDefaultRequestOptions(): void { diff --git a/tests/lib/Http/Client/LocalAddressCheckerTest.php b/tests/lib/Http/Client/LocalAddressCheckerTest.php deleted file mode 100644 index 9f2f6c72993..00000000000 --- a/tests/lib/Http/Client/LocalAddressCheckerTest.php +++ /dev/null @@ -1,139 +0,0 @@ -<?php - -declare(strict_types=1); - -/** - * @copyright Copyright (c) 2021, Lukas Reschke <lukas@statuscode.ch> - * - * @author Lukas Reschke <lukas@statuscode.ch> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * 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 - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - */ - -namespace Test\Http\Client; - -use OCP\Http\Client\LocalServerException; -use OC\Http\Client\LocalAddressChecker; -use Psr\Log\LoggerInterface; - -class LocalAddressCheckerTest extends \Test\TestCase { - /** @var LocalAddressChecker */ - private $localAddressChecker; - - protected function setUp(): void { - parent::setUp(); - - $logger = $this->createMock(LoggerInterface::class); - $this->localAddressChecker = new LocalAddressChecker($logger); - } - - /** - * @dataProvider dataPreventLocalAddress - * @param string $uri - */ - public function testThrowIfLocalAddress($uri) : void { - $this->expectException(LocalServerException::class); - $this->localAddressChecker->ThrowIfLocalAddress('http://' . $uri); - } - - /** - * @dataProvider dataAllowLocalAddress - * @param string $uri - */ - public function testThrowIfLocalAddressGood($uri) : void { - $this->localAddressChecker->ThrowIfLocalAddress('http://' . $uri); - $this->assertTrue(true); - } - - - /** - * @dataProvider dataInternalIPs - * @param string $ip - */ - public function testThrowIfLocalIpBad($ip) : void { - $this->expectException(LocalServerException::class); - $this->localAddressChecker->ThrowIfLocalIp($ip); - } - - /** - * @dataProvider dataPublicIPs - * @param string $ip - */ - public function testThrowIfLocalIpGood($ip) : void { - $this->localAddressChecker->ThrowIfLocalIp($ip); - $this->assertTrue(true); - } - - public function dataPublicIPs() : array { - return [ - ['8.8.8.8'], - ['8.8.4.4'], - ['2001:4860:4860::8888'], - ['2001:4860:4860::8844'], - ]; - } - - public function dataInternalIPs() : array { - return [ - ['192.168.0.1'], - ['fe80::200:5aee:feaa:20a2'], - ['0:0:0:0:0:0:10.0.0.1'], - ['0:0:0:0:0:ffff:127.0.0.0'], - ['10.0.0.1'], - ['::'], - ['::1'], - ['100.100.100.200'], - ['192.0.0.1'], - ]; - } - - public function dataPreventLocalAddress():array { - return [ - ['localhost/foo.bar'], - ['localHost/foo.bar'], - ['random-host/foo.bar'], - ['[::1]/bla.blub'], - ['[::]/bla.blub'], - ['192.168.0.1'], - ['172.16.42.1'], - ['[fdf8:f53b:82e4::53]/secret.ics'], - ['[fe80::200:5aee:feaa:20a2]/secret.ics'], - ['[0:0:0:0:0:0:10.0.0.1]/secret.ics'], - ['[0:0:0:0:0:ffff:127.0.0.0]/secret.ics'], - ['10.0.0.1'], - ['another-host.local'], - ['service.localhost'], - ['!@#$'], // test invalid url - ['100.100.100.200'], - ['192.0.0.1'], - ['randomdomain.internal'], - ]; - } - - public function dataAllowLocalAddress():array { - return [ - ['example.com/foo.bar'], - ['example.net/foo.bar'], - ['example.org/foo.bar'], - ['8.8.8.8/bla.blub'], - ['8.8.4.4/bla.blub'], - ['8.8.8.8'], - ['8.8.4.4'], - ['[2001:4860:4860::8888]/secret.ics'], - ]; - } -} diff --git a/tests/lib/ImageTest.php b/tests/lib/ImageTest.php index e6818c7e243..2a753b01550 100644 --- a/tests/lib/ImageTest.php +++ b/tests/lib/ImageTest.php @@ -140,7 +140,7 @@ class ImageTest extends \Test\TestCase { $config = $this->createMock(IConfig::class); $config->expects($this->once()) ->method('getAppValue') - ->with('preview', 'jpeg_quality', 90) + ->with('preview', 'jpeg_quality', '80') ->willReturn(null); $config->expects($this->once()) ->method('getSystemValueInt') @@ -149,8 +149,10 @@ class ImageTest extends \Test\TestCase { $img = new \OC_Image(null, null, $config); $img->loadFromFile(OC::$SERVERROOT.'/tests/data/testimage.jpg'); $raw = imagecreatefromstring(file_get_contents(OC::$SERVERROOT.'/tests/data/testimage.jpg')); + /** @psalm-suppress InvalidScalarArgument */ + imageinterlace($raw, (PHP_VERSION_ID >= 80000 ? true : 1)); ob_start(); - imagejpeg($raw); + imagejpeg($raw, null, 80); $expected = ob_get_clean(); $this->assertEquals($expected, $img->data()); diff --git a/tests/lib/L10N/FactoryTest.php b/tests/lib/L10N/FactoryTest.php index 4e01602a4f7..7af069cbff3 100644 --- a/tests/lib/L10N/FactoryTest.php +++ b/tests/lib/L10N/FactoryTest.php @@ -13,6 +13,7 @@ namespace Test\L10N; use OC\L10N\Factory; use OC\L10N\LanguageNotFoundException; +use OCP\ICacheFactory; use OCP\IConfig; use OCP\IRequest; use OCP\IUser; @@ -32,6 +33,9 @@ class FactoryTest extends TestCase { /** @var IUserSession|MockObject */ protected $userSession; + /** @var ICacheFactory|MockObject */ + protected $cacheFactory; + /** @var string */ protected $serverRoot; @@ -41,6 +45,7 @@ class FactoryTest extends TestCase { $this->config = $this->createMock(IConfig::class); $this->request = $this->createMock(IRequest::class); $this->userSession = $this->createMock(IUserSession::class); + $this->cacheFactory = $this->createMock(ICacheFactory::class); $this->serverRoot = \OC::$SERVERROOT; } @@ -64,13 +69,14 @@ class FactoryTest extends TestCase { $this->config, $this->request, $this->userSession, + $this->cacheFactory, $this->serverRoot, ]) ->setMethods($methods) ->getMock(); } - return new Factory($this->config, $this->request, $this->userSession, $this->serverRoot); + return new Factory($this->config, $this->request, $this->userSession, $this->cacheFactory, $this->serverRoot); } public function dataFindAvailableLanguages(): array { diff --git a/tests/lib/L10N/L10nTest.php b/tests/lib/L10N/L10nTest.php index f410c523c05..f224592432c 100644 --- a/tests/lib/L10N/L10nTest.php +++ b/tests/lib/L10N/L10nTest.php @@ -11,6 +11,7 @@ namespace Test\L10N; use DateTime; use OC\L10N\Factory; use OC\L10N\L10N; +use OCP\ICacheFactory; use OCP\IConfig; use OCP\IRequest; use OCP\IUserSession; @@ -32,7 +33,8 @@ class L10nTest extends TestCase { $request = $this->createMock(IRequest::class); /** @var IUserSession $userSession */ $userSession = $this->createMock(IUserSession::class); - return new Factory($config, $request, $userSession, \OC::$SERVERROOT); + $cacheFactory = $this->createMock(ICacheFactory::class); + return new Factory($config, $request, $userSession, $cacheFactory, \OC::$SERVERROOT); } public function testSimpleTranslationWithTrailingColon(): void { diff --git a/tests/lib/Mail/MessageTest.php b/tests/lib/Mail/MessageTest.php index f30630824fc..bec70d1c78a 100644 --- a/tests/lib/Mail/MessageTest.php +++ b/tests/lib/Mail/MessageTest.php @@ -102,12 +102,23 @@ class MessageTest extends TestCase { $this->assertSame('lukas@owncloud.com', $this->message->getReplyTo()); } - public function testSetTo() { + /** @dataProvider dataSetTo */ + public function testSetTo(array $to, array $expected) { $this->swiftMessage ->expects($this->once()) ->method('setTo') - ->with(['lukas@owncloud.com']); - $this->message->setTo(['lukas@owncloud.com']); + ->with($expected); + $this->message->setTo($to); + } + + public function dataSetTo(): array { + return [ + [['robot@example.com'], ['robot@example.com']], + [['robot'], ['robot' => 'robot']], + [['robot' => 'robot display name'], ['robot' => 'robot display name']], + [['example@🤖.com'], ['example@xn--yp9h.com']], + [['example@🤖.com' => 'A robot'], ['example@xn--yp9h.com' => 'A robot']], + ]; } /** diff --git a/tests/lib/Net/HostnameClassifierTest.php b/tests/lib/Net/HostnameClassifierTest.php new file mode 100644 index 00000000000..f363a08bb8a --- /dev/null +++ b/tests/lib/Net/HostnameClassifierTest.php @@ -0,0 +1,78 @@ +<?php + +declare(strict_types=1); + +/* + * @copyright 2022 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @author 2022 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * 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 + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +namespace lib\Net; + +use OC\Net\HostnameClassifier; +use Test\TestCase; + +class HostnameClassifierTest extends TestCase { + private HostnameClassifier $classifier; + + protected function setUp(): void { + parent::setUp(); + + $this->classifier = new HostnameClassifier(); + } + + public function localHostnamesData():array { + return [ + ['localhost'], + ['localHost'], + ['random-host'], + ['another-host.local'], + ['service.localhost'], + ['randomdomain.internal'], + ]; + } + + /** + * @dataProvider localHostnamesData + */ + public function testLocalHostname(string $host): void { + $isLocal = $this->classifier->isLocalHostname($host); + + self::assertTrue($isLocal); + } + + public function publicHostnamesData(): array { + return [ + ['example.com'], + ['example.net'], + ['example.org'], + ['host.domain'], + ['cloud.domain.tld'], + ]; + } + + /** + * @dataProvider publicHostnamesData + */ + public function testPublicHostname(string $host): void { + $isLocal = $this->classifier->isLocalHostname($host); + + self::assertFalse($isLocal); + } +} diff --git a/tests/lib/Net/IpAddressClassifierTest.php b/tests/lib/Net/IpAddressClassifierTest.php new file mode 100644 index 00000000000..593abcd2b40 --- /dev/null +++ b/tests/lib/Net/IpAddressClassifierTest.php @@ -0,0 +1,80 @@ +<?php + +declare(strict_types=1); + +/* + * @copyright 2022 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @author 2022 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * 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 + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +namespace lib\Net; + +use OC\Net\IpAddressClassifier; +use Test\TestCase; + +class IpAddressClassifierTest extends TestCase { + private IpAddressClassifier $classifier; + + protected function setUp(): void { + parent::setUp(); + + $this->classifier = new IpAddressClassifier(); + } + + public function publicIpAddressData(): array { + return [ + ['8.8.8.8'], + ['8.8.4.4'], + ['2001:4860:4860::8888'], + ['2001:4860:4860::8844'], + ]; + } + + /** + * @dataProvider publicIpAddressData + */ + public function testPublicAddress(string $ip): void { + $isLocal = $this->classifier->isLocalAddress($ip); + + self::assertFalse($isLocal); + } + + public function localIpAddressData(): array { + return [ + ['192.168.0.1'], + ['fe80::200:5aee:feaa:20a2'], + ['0:0:0:0:0:ffff:10.0.0.1'], + ['0:0:0:0:0:ffff:127.0.0.0'], + ['10.0.0.1'], + ['::'], + ['::1'], + ['100.100.100.200'], + ['192.0.0.1'], + ]; + } + + /** + * @dataProvider localIpAddressData + */ + public function testLocalAddress(string $ip): void { + $isLocal = $this->classifier->isLocalAddress($ip); + + self::assertTrue($isLocal); + } +} diff --git a/tests/lib/Notification/ManagerTest.php b/tests/lib/Notification/ManagerTest.php index e482ba3876b..a32eebcdb95 100644 --- a/tests/lib/Notification/ManagerTest.php +++ b/tests/lib/Notification/ManagerTest.php @@ -248,10 +248,10 @@ class ManagerTest extends TestCase { public function dataIsFairUseOfFreePushService(): array { return [ - [true, 499, true], - [true, 500, true], - [false, 499, true], - [false, 500, false], + [true, 999, true], + [true, 1000, true], + [false, 999, true], + [false, 1000, false], ]; } diff --git a/tests/lib/Preview/BackgroundCleanupJobTest.php b/tests/lib/Preview/BackgroundCleanupJobTest.php index cd9f6ef0399..c1c225bd179 100644 --- a/tests/lib/Preview/BackgroundCleanupJobTest.php +++ b/tests/lib/Preview/BackgroundCleanupJobTest.php @@ -25,6 +25,7 @@ namespace Test\Preview; use OC\Preview\BackgroundCleanupJob; use OC\Preview\Storage\Root; use OC\PreviewManager; +use OCP\AppFramework\Utility\ITimeFactory; use OCP\Files\File; use OCP\Files\IMimeTypeLoader; use OCP\Files\IRootFolder; @@ -62,6 +63,8 @@ class BackgroundCleanupJobTest extends \Test\TestCase { /** @var IMimeTypeLoader */ private $mimeTypeLoader; + private ITimeFactory $timeFactory; + protected function setUp(): void { parent::setUp(); @@ -83,6 +86,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase { $this->previewManager = \OC::$server->getPreviewManager(); $this->rootFolder = \OC::$server->getRootFolder(); $this->mimeTypeLoader = \OC::$server->getMimeTypeLoader(); + $this->timeFactory = \OCP\Server::get(ITimeFactory::class); } protected function tearDown(): void { @@ -142,7 +146,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase { $root = $this->getRoot(); $this->assertSame(11, $this->countPreviews($root, $fileIds)); - $job = new BackgroundCleanupJob($this->connection, $root, $this->mimeTypeLoader, true); + $job = new BackgroundCleanupJob($this->timeFactory, $this->connection, $root, $this->mimeTypeLoader, true); $job->run([]); foreach ($files as $file) { @@ -166,7 +170,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase { $root = $this->getRoot(); $this->assertSame(11, $this->countPreviews($root, $fileIds)); - $job = new BackgroundCleanupJob($this->connection, $root, $this->mimeTypeLoader, false); + $job = new BackgroundCleanupJob($this->timeFactory, $this->connection, $root, $this->mimeTypeLoader, false); $job->run([]); foreach ($files as $file) { @@ -196,7 +200,7 @@ class BackgroundCleanupJobTest extends \Test\TestCase { $appdata = \OC::$server->getAppDataDir('preview'); $this->assertSame(2, count($appdata->getDirectoryListing())); - $job = new BackgroundCleanupJob($this->connection, $this->getRoot(), $this->mimeTypeLoader, true); + $job = new BackgroundCleanupJob($this->timeFactory, $this->connection, $this->getRoot(), $this->mimeTypeLoader, true); $job->run([]); $appdata = \OC::$server->getAppDataDir('preview'); diff --git a/tests/lib/Preview/GeneratorTest.php b/tests/lib/Preview/GeneratorTest.php index 1e38afd7744..b673100be9e 100644 --- a/tests/lib/Preview/GeneratorTest.php +++ b/tests/lib/Preview/GeneratorTest.php @@ -25,6 +25,7 @@ namespace Test\Preview; use OC\Preview\Generator; use OC\Preview\GeneratorHelper; +use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\File; use OCP\Files\IAppData; use OCP\Files\NotFoundException; @@ -32,6 +33,7 @@ use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\SimpleFS\ISimpleFolder; use OCP\IConfig; use OCP\IPreview; +use OCP\Preview\BeforePreviewFetchedEvent; use OCP\Preview\IProviderV2; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; @@ -50,9 +52,12 @@ class GeneratorTest extends \Test\TestCase { /** @var GeneratorHelper|\PHPUnit\Framework\MockObject\MockObject */ private $helper; - /** @var EventDispatcherInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */ private $eventDispatcher; + /** @var EventDispatcherInterface|\PHPUnit\Framework\MockObject\MockObject */ + private $legacyEventDispatcher; + /** @var Generator */ private $generator; @@ -63,13 +68,15 @@ class GeneratorTest extends \Test\TestCase { $this->previewManager = $this->createMock(IPreview::class); $this->appData = $this->createMock(IAppData::class); $this->helper = $this->createMock(GeneratorHelper::class); - $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); + $this->eventDispatcher = $this->createMock(IEventDispatcher::class); + $this->legacyEventDispatcher = $this->createMock(EventDispatcherInterface::class); $this->generator = new Generator( $this->config, $this->previewManager, $this->appData, $this->helper, + $this->legacyEventDispatcher, $this->eventDispatcher ); } @@ -109,7 +116,7 @@ class GeneratorTest extends \Test\TestCase { ->with($this->equalTo('256-256.png')) ->willReturn($previewFile); - $this->eventDispatcher->expects($this->once()) + $this->legacyEventDispatcher->expects($this->once()) ->method('dispatch') ->with( $this->equalTo(IPreview::EVENT), @@ -120,6 +127,10 @@ class GeneratorTest extends \Test\TestCase { }) ); + $this->eventDispatcher->expects($this->once()) + ->method('dispatchTyped') + ->with(new BeforePreviewFetchedEvent($file)); + $result = $this->generator->getPreview($file, 100, 100); $this->assertSame($previewFile, $result); } @@ -147,8 +158,13 @@ class GeneratorTest extends \Test\TestCase { ->willReturn($previewFolder); $this->config->method('getSystemValue') - ->willReturnCallback(function ($key, $defult) { - return $defult; + ->willReturnCallback(function ($key, $default) { + return $default; + }); + + $this->config->method('getSystemValueInt') + ->willReturnCallback(function ($key, $default) { + return $default; }); $invalidProvider = $this->createMock(IProviderV2::class); @@ -239,7 +255,7 @@ class GeneratorTest extends \Test\TestCase { ->method('putContent') ->with('my resized data'); - $this->eventDispatcher->expects($this->once()) + $this->legacyEventDispatcher->expects($this->once()) ->method('dispatch') ->with( $this->equalTo(IPreview::EVENT), @@ -250,6 +266,10 @@ class GeneratorTest extends \Test\TestCase { }) ); + $this->eventDispatcher->expects($this->once()) + ->method('dispatchTyped') + ->with(new BeforePreviewFetchedEvent($file)); + $result = $this->generator->getPreview($file, 100, 100); $this->assertSame($previewFile, $result); } @@ -285,7 +305,7 @@ class GeneratorTest extends \Test\TestCase { ->with($this->equalTo('1024-512-crop.png')) ->willThrowException(new NotFoundException()); - $this->eventDispatcher->expects($this->once()) + $this->legacyEventDispatcher->expects($this->once()) ->method('dispatch') ->with( $this->equalTo(IPreview::EVENT), @@ -298,6 +318,10 @@ class GeneratorTest extends \Test\TestCase { }) ); + $this->eventDispatcher->expects($this->once()) + ->method('dispatchTyped') + ->with(new BeforePreviewFetchedEvent($file)); + $this->generator->getPreview($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType'); } @@ -333,7 +357,7 @@ class GeneratorTest extends \Test\TestCase { $this->previewManager->expects($this->never()) ->method('isMimeSupported'); - $this->eventDispatcher->expects($this->once()) + $this->legacyEventDispatcher->expects($this->once()) ->method('dispatch') ->with( $this->equalTo(IPreview::EVENT), @@ -346,6 +370,10 @@ class GeneratorTest extends \Test\TestCase { }) ); + $this->eventDispatcher->expects($this->once()) + ->method('dispatchTyped') + ->with(new BeforePreviewFetchedEvent($file)); + $result = $this->generator->getPreview($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType'); $this->assertSame($preview, $result); } @@ -370,7 +398,7 @@ class GeneratorTest extends \Test\TestCase { $this->previewManager->method('getProviders') ->willReturn([]); - $this->eventDispatcher->expects($this->once()) + $this->legacyEventDispatcher->expects($this->once()) ->method('dispatch') ->with( $this->equalTo(IPreview::EVENT), @@ -381,6 +409,10 @@ class GeneratorTest extends \Test\TestCase { }) ); + $this->eventDispatcher->expects($this->once()) + ->method('dispatchTyped') + ->with(new BeforePreviewFetchedEvent($file)); + $this->expectException(NotFoundException::class); $this->generator->getPreview($file, 100, 100); } @@ -502,7 +534,7 @@ class GeneratorTest extends \Test\TestCase { ->with($this->equalTo($filename)) ->willReturn($preview); - $this->eventDispatcher->expects($this->once()) + $this->legacyEventDispatcher->expects($this->once()) ->method('dispatch') ->with( $this->equalTo(IPreview::EVENT), @@ -515,6 +547,10 @@ class GeneratorTest extends \Test\TestCase { }) ); + $this->eventDispatcher->expects($this->once()) + ->method('dispatchTyped') + ->with(new BeforePreviewFetchedEvent($file)); + $result = $this->generator->getPreview($file, $reqX, $reqY, $crop, $mode); if ($expectedX === $maxX && $expectedY === $maxY) { $this->assertSame($maxPreview, $result); diff --git a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php index de4c6179610..71842547462 100644 --- a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php +++ b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php @@ -25,6 +25,7 @@ namespace Test\Repair; use OC\Avatar\AvatarManager; use OC\Repair\ClearGeneratedAvatarCache; +use OCP\BackgroundJob\IJobList; use OCP\IConfig; use OCP\Migration\IOutput; @@ -39,8 +40,10 @@ class ClearGeneratedAvatarCacheTest extends \Test\TestCase { /** @var IConfig */ private $config; - /** @var ClearGeneratedAvatarCache */ - protected $repair; + /** @var IJobList */ + private $jobList; + + protected ClearGeneratedAvatarCache $repair; protected function setUp(): void { parent::setUp(); @@ -48,8 +51,9 @@ class ClearGeneratedAvatarCacheTest extends \Test\TestCase { $this->outputMock = $this->createMock(IOutput::class); $this->avatarManager = $this->createMock(AvatarManager::class); $this->config = $this->createMock(IConfig::class); + $this->jobList = $this->createMock(IJobList::class); - $this->repair = new ClearGeneratedAvatarCache($this->config, $this->avatarManager); + $this->repair = new ClearGeneratedAvatarCache($this->config, $this->avatarManager, $this->jobList); } public function shouldRunDataProvider() { diff --git a/tests/lib/Security/RemoteHostValidatorIntegrationTest.php b/tests/lib/Security/RemoteHostValidatorIntegrationTest.php new file mode 100644 index 00000000000..73cbbd7b0e8 --- /dev/null +++ b/tests/lib/Security/RemoteHostValidatorIntegrationTest.php @@ -0,0 +1,144 @@ +<?php + +declare(strict_types=1); + +/* + * @copyright 2022 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @author 2022 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * 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 + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +namespace lib\Security; + +use OC\Net\HostnameClassifier; +use OC\Net\IpAddressClassifier; +use OC\Security\RemoteHostValidator; +use OCP\IConfig; +use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\NullLogger; +use Test\TestCase; + +class RemoteHostValidatorIntegrationTest extends TestCase { + + /** @var IConfig|IConfig&MockObject|MockObject */ + private IConfig $config; + private RemoteHostValidator $validator; + + protected function setUp(): void { + parent::setUp(); + + // Mock config to avoid any side effects + $this->config = $this->createMock(IConfig::class); + + $this->validator = new RemoteHostValidator( + $this->config, + Server::get(HostnameClassifier::class), + Server::get(IpAddressClassifier::class), + new NullLogger(), + ); + } + + public function localHostsData(): array { + return [ + ['[::1]'], + ['[::]'], + ['192.168.0.1'], + ['172.16.42.1'], + ['[fdf8:f53b:82e4::53]'], + ['[fe80::200:5aee:feaa:20a2]'], + ['[0:0:0:0:0:ffff:10.0.0.1]'], + ['[0:0:0:0:0:ffff:127.0.0.0]'], + ['10.0.0.1'], + ['!@#$'], // test invalid url + ['100.100.100.200'], + ['192.0.0.1'], + ['0177.0.0.9'], + ['⑯⑨。②⑤④。⑯⑨。②⑤④'], + ['127。②⑤④。⑯⑨.②⑤④'], + ['127.0.00000000000000000000000000000000001'], + ['127.1'], + ['127.000.001'], + ['0177.0.0.01'], + ['0x7f.0x0.0x0.0x1'], + ['0x7f000001'], + ['2130706433'], + ['00000000000000000000000000000000000000000000000000177.1'], + ['0x7f.1'], + ['127.0x1'], + ['[0000:0000:0000:0000:0000:0000:0000:0001]'], + ['[0:0:0:0:0:0:0:1]'], + ['[0:0:0:0::0:0:1]'], + ['%31%32%37%2E%30%2E%30%2E%31'], + ['%31%32%37%2E%30%2E%30.%31'], + ['[%3A%3A%31]'], + ]; + } + + /** + * @dataProvider localHostsData + */ + public function testLocalHostsWhenNotAllowed(string $host): void { + $this->config + ->method('getSystemValueBool') + ->with('allow_local_remote_servers', false) + ->willReturn(false); + + $isValid = $this->validator->isValid($host); + + self::assertFalse($isValid); + } + + /** + * @dataProvider localHostsData + */ + public function testLocalHostsWhenAllowed(string $host): void { + $this->config + ->method('getSystemValueBool') + ->with('allow_local_remote_servers', false) + ->willReturn(true); + + $isValid = $this->validator->isValid($host); + + self::assertTrue($isValid); + } + + public function externalAddressesData():array { + return [ + ['8.8.8.8'], + ['8.8.4.4'], + ['8.8.8.8'], + ['8.8.4.4'], + ['[2001:4860:4860::8888]'], + ]; + } + + /** + * @dataProvider externalAddressesData + */ + public function testExternalHost(string $host): void { + $this->config + ->method('getSystemValueBool') + ->with('allow_local_remote_servers', false) + ->willReturn(false); + + $isValid = $this->validator->isValid($host); + + self::assertTrue($isValid); + } +} diff --git a/tests/lib/Security/RemoteHostValidatorTest.php b/tests/lib/Security/RemoteHostValidatorTest.php new file mode 100644 index 00000000000..acaa7a4be30 --- /dev/null +++ b/tests/lib/Security/RemoteHostValidatorTest.php @@ -0,0 +1,111 @@ +<?php + +declare(strict_types=1); + +/* + * @copyright 2022 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @author 2022 Christoph Wurst <christoph@winzerhof-wurst.at> + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * 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 + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +namespace lib\Security; + +use OC\Net\HostnameClassifier; +use OC\Net\IpAddressClassifier; +use OC\Security\RemoteHostValidator; +use OCP\IConfig; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class RemoteHostValidatorTest extends TestCase { + + /** @var IConfig|IConfig&MockObject|MockObject */ + private IConfig $config; + /** @var HostnameClassifier|HostnameClassifier&MockObject|MockObject */ + private HostnameClassifier $hostnameClassifier; + /** @var IpAddressClassifier|IpAddressClassifier&MockObject|MockObject */ + private IpAddressClassifier $ipAddressClassifier; + /** @var MockObject|LoggerInterface|LoggerInterface&MockObject */ + private LoggerInterface $logger; + private RemoteHostValidator $validator; + + protected function setUp(): void { + parent::setUp(); + + $this->config = $this->createMock(IConfig::class); + $this->hostnameClassifier = $this->createMock(HostnameClassifier::class); + $this->ipAddressClassifier = $this->createMock(IpAddressClassifier::class); + $this->logger = $this->createMock(LoggerInterface::class); + + $this->validator = new RemoteHostValidator( + $this->config, + $this->hostnameClassifier, + $this->ipAddressClassifier, + $this->logger, + ); + } + + public function testValid(): void { + $host = 'nextcloud.com'; + $this->hostnameClassifier + ->method('isLocalHostname') + ->with($host) + ->willReturn(false); + $this->ipAddressClassifier + ->method('isLocalAddress') + ->with($host) + ->willReturn(false); + + $valid = $this->validator->isValid($host); + + self::assertTrue($valid); + } + + public function testLocalHostname(): void { + $host = 'localhost'; + $this->hostnameClassifier + ->method('isLocalHostname') + ->with($host) + ->willReturn(true); + $this->ipAddressClassifier + ->method('isLocalAddress') + ->with($host) + ->willReturn(false); + + $valid = $this->validator->isValid($host); + + self::assertFalse($valid); + } + + public function testLocalAddress(): void { + $host = '10.0.0.10'; + $this->hostnameClassifier + ->method('isLocalHostname') + ->with($host) + ->willReturn(false); + $this->ipAddressClassifier + ->method('isLocalAddress') + ->with($host) + ->willReturn(true); + + $valid = $this->validator->isValid($host); + + self::assertFalse($valid); + } +} diff --git a/tests/lib/Security/VerificationToken/VerificationTokenTest.php b/tests/lib/Security/VerificationToken/VerificationTokenTest.php index 4d90e304ab7..481646f26ab 100644 --- a/tests/lib/Security/VerificationToken/VerificationTokenTest.php +++ b/tests/lib/Security/VerificationToken/VerificationTokenTest.php @@ -35,18 +35,21 @@ use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; use OCP\Security\VerificationToken\InvalidTokenException; use Test\TestCase; +use PHPUnit\Framework\MockObject\MockObject; class VerificationTokenTest extends TestCase { /** @var VerificationToken */ protected $token; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig|MockObject */ protected $config; - /** @var ISecureRandom|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ISecureRandom|MockObject */ protected $secureRandom; - /** @var ICrypto|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ICrypto|MockObject */ protected $crypto; - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory|MockObject */ protected $timeFactory; + /** @var IJobList|MockObject */ + protected $jobList; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/ServerTest.php b/tests/lib/ServerTest.php index 8df39ca7cc9..cbaa0e0762a 100644 --- a/tests/lib/ServerTest.php +++ b/tests/lib/ServerTest.php @@ -151,7 +151,7 @@ class ServerTest extends \Test\TestCase { ['UserSession', '\OCP\IUserSession'], ['TagMapper', '\OC\Tagging\TagMapper'], - ['TagMapper', '\OCP\AppFramework\Db\Mapper'], + ['TagMapper', '\OCP\AppFramework\Db\QBMapper'], ['TagManager', '\OC\TagManager'], ['TagManager', '\OCP\ITagManager'], ['TempManager', '\OC\TempManager'], diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php index 29ae33c3c93..cc13479b1d0 100644 --- a/tests/lib/Settings/ManagerTest.php +++ b/tests/lib/Settings/ManagerTest.php @@ -36,24 +36,26 @@ use OCP\Settings\ISettings; use OCP\Settings\ISubAdminSettings; use Psr\Log\LoggerInterface; use Test\TestCase; +use PHPUnit\Framework\MockObject\MockObject; class ManagerTest extends TestCase { - - /** @var Manager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Manager|MockObject */ private $manager; - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ private $logger; - /** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IDBConnection|MockObject */ private $l10n; - /** @var IFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IFactory|MockObject */ private $l10nFactory; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ private $url; - /** @var IServerContainer|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IServerContainer|MockObject */ private $container; - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var AuthorizedGroupMapper|MockObject */ + private $mapper; + /** @var IGroupManager|MockObject */ private $groupManager; - /** @var ISubAdmin|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ISubAdmin|MockObject */ private $subAdmin; protected function setUp(): void { diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php index c690ada99ca..35dc00739f6 100644 --- a/tests/lib/Share/ShareTest.php +++ b/tests/lib/Share/ShareTest.php @@ -21,6 +21,9 @@ namespace Test\Share; +use OC\Share\Share; +use OCP\DB\QueryBuilder\IQueryBuilder; +use OCP\IDBConnection; use OCP\IGroup; use OCP\IGroupManager; use OCP\IUser; @@ -35,36 +38,25 @@ use OCP\Share\IShare; class ShareTest extends \Test\TestCase { protected $itemType; - /** @var IUser */ - protected $user1; - /** @var IUser */ - protected $user2; - /** @var IUser */ - protected $user3; - /** @var IUser */ - protected $user4; - /** @var IUser */ - protected $user5; - /** @var IUser */ - protected $user6; - /** @var IUser */ - protected $groupAndUser_user; - - /** @var IGroup */ - protected $group1; - /** @var IGroup */ - protected $group2; - /** @var IGroup */ - protected $groupAndUser_group; - - protected $resharing; - protected $dateInFuture; - protected $dateInPast; - - /** @var IGroupManager */ - protected $groupManager; - /** @var IUserManager */ - protected $userManager; + protected IUser $user1; + protected IUser $user2; + protected IUser $user3; + protected IUser $user4; + protected IUser $user5; + protected IUser $user6; + protected IUser $groupAndUser_user; + + protected IGroup $group1; + protected IGroup $group2; + protected IGroup $groupAndUser_group; + + protected string $resharing; + protected string $dateInFuture; + protected string $dateInPast; + + protected IGroupManager $groupManager; + protected IUserManager $userManager; + private IDBConnection $connection; protected function setUp(): void { parent::setUp(); @@ -90,6 +82,7 @@ class ShareTest extends \Test\TestCase { $this->group1 = $this->groupManager->createGroup($this->getUniqueID('group1_')); $this->group2 = $this->groupManager->createGroup($this->getUniqueID('group2_')); $this->groupAndUser_group = $this->groupManager->createGroup($groupAndUserId); + $this->connection = \OC::$server->get(IDBConnection::class); $this->group1->addUser($this->user1); $this->group1->addUser($this->user2); @@ -99,7 +92,7 @@ class ShareTest extends \Test\TestCase { $this->groupAndUser_group->addUser($this->user2); $this->groupAndUser_group->addUser($this->user3); - \OC\Share\Share::registerBackend('test', 'Test\Share\Backend'); + Share::registerBackend('test', 'Test\Share\Backend'); \OC_Hook::clear('OCP\\Share'); \OC::registerShareHooks(\OC::$server->getSystemConfig()); $this->resharing = \OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes'); @@ -113,8 +106,9 @@ class ShareTest extends \Test\TestCase { } protected function tearDown(): void { - $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `item_type` = ?'); - $query->execute(['test']); + $query = $this->connection->getQueryBuilder(); + $query->delete('share')->andWhere($query->expr()->eq('item_type', $query->createNamedParameter('test'))); + $query->executeStatement(); \OC::$server->getConfig()->setAppValue('core', 'shareapi_allow_resharing', $this->resharing); $this->user1->delete(); @@ -136,39 +130,51 @@ class ShareTest extends \Test\TestCase { public function testGetItemSharedWithUser() { \OC_User::setUserId($this->user1->getUID()); - //add dummy values to the share table - $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (' - .' `item_type`, `item_source`, `item_target`, `share_type`,' - .' `share_with`, `uid_owner`) VALUES (?,?,?,?,?,?)'); - $args = ['test', 99, 'target1', IShare::TYPE_USER, $this->user2->getUID(), $this->user1->getUID()]; - $query->execute($args); - $args = ['test', 99, 'target2', IShare::TYPE_USER, $this->user4->getUID(), $this->user1->getUID()]; - $query->execute($args); - $args = ['test', 99, 'target3', IShare::TYPE_USER, $this->user3->getUID(), $this->user2->getUID()]; - $query->execute($args); - $args = ['test', 99, 'target4', IShare::TYPE_USER, $this->user3->getUID(), $this->user4->getUID()]; - $query->execute($args); - $args = ['test', 99, 'target4', IShare::TYPE_USER, $this->user6->getUID(), $this->user4->getUID()]; - $query->execute($args); - - - $result1 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user2->getUID(), $this->user1->getUID()); + // add dummy values to the share table + $query = $this->connection->getQueryBuilder(); + $query->insert('share') + ->values([ + 'item_type' => $query->createParameter('itemType'), + 'item_source' => $query->createParameter('itemSource'), + 'item_target' => $query->createParameter('itemTarget'), + 'share_type' => $query->createParameter('shareType'), + 'share_with' => $query->createParameter('shareWith'), + 'uid_owner' => $query->createParameter('uidOwner') + ]); + $args = [ + ['test', 99, 'target1', IShare::TYPE_USER, $this->user2->getUID(), $this->user1->getUID()], + ['test', 99, 'target2', IShare::TYPE_USER, $this->user4->getUID(), $this->user1->getUID()], + ['test', 99, 'target3', IShare::TYPE_USER, $this->user3->getUID(), $this->user2->getUID()], + ['test', 99, 'target4', IShare::TYPE_USER, $this->user3->getUID(), $this->user4->getUID()], + ['test', 99, 'target4', IShare::TYPE_USER, $this->user6->getUID(), $this->user4->getUID()], + ]; + foreach ($args as $row) { + $query->setParameter('itemType', $row[0]); + $query->setParameter('itemSource', $row[1], IQueryBuilder::PARAM_INT); + $query->setParameter('itemTarget', $row[2]); + $query->setParameter('shareType', $row[3], IQueryBuilder::PARAM_INT); + $query->setParameter('shareWith', $row[4]); + $query->setParameter('uidOwner', $row[5]); + $query->executeStatement(); + } + + $result1 = Share::getItemSharedWithUser('test', 99, $this->user2->getUID(), $this->user1->getUID()); $this->assertSame(1, count($result1)); $this->verifyResult($result1, ['target1']); - $result2 = \OCP\Share::getItemSharedWithUser('test', 99, null, $this->user1->getUID()); + $result2 = Share::getItemSharedWithUser('test', 99, null, $this->user1->getUID()); $this->assertSame(2, count($result2)); $this->verifyResult($result2, ['target1', 'target2']); - $result3 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user3->getUID()); + $result3 = Share::getItemSharedWithUser('test', 99, $this->user3->getUID()); $this->assertSame(2, count($result3)); $this->verifyResult($result3, ['target3', 'target4']); - $result4 = \OCP\Share::getItemSharedWithUser('test', 99, null, null); + $result4 = Share::getItemSharedWithUser('test', 99, null, null); $this->assertSame(5, count($result4)); // 5 because target4 appears twice $this->verifyResult($result4, ['target1', 'target2', 'target3', 'target4']); - $result6 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user6->getUID(), null); + $result6 = Share::getItemSharedWithUser('test', 99, $this->user6->getUID(), null); $this->assertSame(1, count($result6)); $this->verifyResult($result6, ['target4']); } @@ -176,38 +182,52 @@ class ShareTest extends \Test\TestCase { public function testGetItemSharedWithUserFromGroupShare() { \OC_User::setUserId($this->user1->getUID()); - //add dummy values to the share table - $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (' - .' `item_type`, `item_source`, `item_target`, `share_type`,' - .' `share_with`, `uid_owner`) VALUES (?,?,?,?,?,?)'); - $args = ['test', 99, 'target1', IShare::TYPE_GROUP, $this->group1->getGID(), $this->user1->getUID()]; - $query->execute($args); - $args = ['test', 99, 'target2', IShare::TYPE_GROUP, $this->group2->getGID(), $this->user1->getUID()]; - $query->execute($args); - $args = ['test', 99, 'target3', IShare::TYPE_GROUP, $this->group1->getGID(), $this->user2->getUID()]; - $query->execute($args); - $args = ['test', 99, 'target4', IShare::TYPE_GROUP, $this->group1->getGID(), $this->user4->getUID()]; - $query->execute($args); + // add dummy values to the share table + $query = $this->connection->getQueryBuilder(); + $query->insert('share') + ->values([ + 'item_type' => $query->createParameter('itemType'), + 'item_source' => $query->createParameter('itemSource'), + 'item_target' => $query->createParameter('itemTarget'), + 'share_type' => $query->createParameter('shareType'), + 'share_with' => $query->createParameter('shareWith'), + 'uid_owner' => $query->createParameter('uidOwner') + ]); + $args = [ + ['test', 99, 'target1', IShare::TYPE_GROUP, $this->group1->getGID(), $this->user1->getUID()], + ['test', 99, 'target2', IShare::TYPE_GROUP, $this->group2->getGID(), $this->user1->getUID()], + ['test', 99, 'target3', IShare::TYPE_GROUP, $this->group1->getGID(), $this->user2->getUID()], + ['test', 99, 'target4', IShare::TYPE_GROUP, $this->group1->getGID(), $this->user4->getUID()], + ]; + foreach ($args as $row) { + $query->setParameter('itemType', $row[0]); + $query->setParameter('itemSource', $row[1], IQueryBuilder::PARAM_INT); + $query->setParameter('itemTarget', $row[2]); + $query->setParameter('shareType', $row[3], IQueryBuilder::PARAM_INT); + $query->setParameter('shareWith', $row[4]); + $query->setParameter('uidOwner', $row[5]); + $query->executeStatement(); + } // user2 is in group1 and group2 - $result1 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user2->getUID(), $this->user1->getUID()); + $result1 = Share::getItemSharedWithUser('test', 99, $this->user2->getUID(), $this->user1->getUID()); $this->assertSame(2, count($result1)); $this->verifyResult($result1, ['target1', 'target2']); - $result2 = \OCP\Share::getItemSharedWithUser('test', 99, null, $this->user1->getUID()); + $result2 = Share::getItemSharedWithUser('test', 99, null, $this->user1->getUID()); $this->assertSame(2, count($result2)); $this->verifyResult($result2, ['target1', 'target2']); // user3 is in group1 and group2 - $result3 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user3->getUID()); + $result3 = Share::getItemSharedWithUser('test', 99, $this->user3->getUID()); $this->assertSame(3, count($result3)); $this->verifyResult($result3, ['target1', 'target3', 'target4']); - $result4 = \OCP\Share::getItemSharedWithUser('test', 99, null, null); + $result4 = Share::getItemSharedWithUser('test', 99, null, null); $this->assertSame(4, count($result4)); $this->verifyResult($result4, ['target1', 'target2', 'target3', 'target4']); - $result6 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user6->getUID(), null); + $result6 = Share::getItemSharedWithUser('test', 99, $this->user6->getUID(), null); $this->assertSame(0, count($result6)); } @@ -227,7 +247,7 @@ class ShareTest extends \Test\TestCase { * @param string $expectedResult */ public function testRemoveProtocolFromUrl($url, $expectedResult) { - $share = new \OC\Share\Share(); + $share = new Share(); $result = self::invokePrivate($share, 'removeProtocolFromUrl', [$url]); $this->assertSame($expectedResult, $result); } @@ -316,7 +336,7 @@ class ShareTest extends \Test\TestCase { } } -class DummyShareClass extends \OC\Share\Share { +class DummyShareClass extends Share { public static function groupItemsTest($items) { return parent::groupItems($items, 'test'); } diff --git a/tests/lib/Share20/DefaultShareProviderTest.php b/tests/lib/Share20/DefaultShareProviderTest.php index ed2bc2a4eda..d7b5dbc9b74 100644 --- a/tests/lib/Share20/DefaultShareProviderTest.php +++ b/tests/lib/Share20/DefaultShareProviderTest.php @@ -365,6 +365,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $group0 = $this->createMock(IGroup::class); $group0->method('inGroup')->with($user1)->willReturn(true); + $group0->method('getDisplayName')->willReturn('g0-displayname'); $node = $this->createMock(Folder::class); $node->method('getId')->willReturn(42); @@ -1488,6 +1489,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $group = $this->createMock(IGroup::class); $group->method('getGID')->willReturn('group'); $group->method('inGroup')->with($user2)->willReturn(true); + $group->method('getDisplayName')->willReturn('group-displayname'); $this->groupManager->method('get')->with('group')->willReturn($group); $file = $this->createMock(File::class); @@ -1559,6 +1561,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $group = $this->createMock(IGroup::class); $group->method('getGID')->willReturn('group'); $group->method('inGroup')->with($user2)->willReturn(true); + $group->method('getDisplayName')->willReturn('group-displayname'); $this->groupManager->method('get')->with('group')->willReturn($group); $file = $this->createMock(File::class); @@ -1616,6 +1619,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $group = $this->createMock(IGroup::class); $group->method('getGID')->willReturn('group'); $group->method('inGroup')->with($user2)->willReturn(false); + $group->method('getDisplayName')->willReturn('group-displayname'); $this->groupManager->method('get')->with('group')->willReturn($group); $file = $this->createMock(File::class); @@ -2002,6 +2006,7 @@ class DefaultShareProviderTest extends \Test\TestCase { for ($i = 0; $i < 2; $i++) { $group = $this->createMock(IGroup::class); $group->method('getGID')->willReturn('group'.$i); + $group->method('getDisplayName')->willReturn('group-displayname' . $i); $groups['group'.$i] = $group; } @@ -2080,6 +2085,7 @@ class DefaultShareProviderTest extends \Test\TestCase { for ($i = 0; $i < 2; $i++) { $group = $this->createMock(IGroup::class); $group->method('getGID')->willReturn('group'.$i); + $group->method('getDisplayName')->willReturn('group-displayname'.$i); $groups['group'.$i] = $group; } @@ -2196,6 +2202,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $group0 = $this->createMock(IGroup::class); $group0->method('getGID')->willReturn('group0'); $group0->method('inGroup')->with($user0)->willReturn(true); + $group0->method('getDisplayName')->willReturn('group0-displayname'); $this->groupManager->method('get')->with('group0')->willReturn($group0); diff --git a/tests/lib/Share20/ShareTest.php b/tests/lib/Share20/ShareTest.php index 7d4dc6de2d6..b2419e07683 100644 --- a/tests/lib/Share20/ShareTest.php +++ b/tests/lib/Share20/ShareTest.php @@ -23,6 +23,7 @@ namespace Test\Share20; use OCP\Files\IRootFolder; use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; /** * Class ShareTest @@ -30,9 +31,10 @@ use OCP\IUserManager; * @package Test\Share20 */ class ShareTest extends \Test\TestCase { - - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IRootFolder|MockObject */ protected $rootFolder; + /** @var IUserManager|MockObject */ + protected $userManager; /** @var \OCP\Share\IShare */ protected $share; diff --git a/tests/lib/TagsTest.php b/tests/lib/TagsTest.php index f6acc662424..2a68dfe3124 100644 --- a/tests/lib/TagsTest.php +++ b/tests/lib/TagsTest.php @@ -22,8 +22,10 @@ namespace Test; +use OCP\IDBConnection; use OCP\IUser; use OCP\IUserSession; +use Psr\Log\LoggerInterface; /** * Class TagsTest @@ -60,8 +62,8 @@ class TagsTest extends \Test\TestCase { ->willReturn($this->user); $this->objectType = $this->getUniqueID('type_'); - $this->tagMapper = new \OC\Tagging\TagMapper(\OC::$server->getDatabaseConnection()); - $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession, \OC::$server->getDatabaseConnection()); + $this->tagMapper = new \OC\Tagging\TagMapper(\OC::$server->get(IDBConnection::class)); + $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession, \OC::$server->get(IDBConnection::class), \OC::$server->get(LoggerInterface::class)); } protected function tearDown(): void { @@ -78,7 +80,7 @@ class TagsTest extends \Test\TestCase { ->expects($this->any()) ->method('getUser') ->willReturn(null); - $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession, \OC::$server->getDatabaseConnection()); + $this->tagMgr = new \OC\TagManager($this->tagMapper, $this->userSession, \OC::$server->getDatabaseConnection(), \OC::$server->get(LoggerInterface::class)); $this->assertNull($this->tagMgr->load($this->objectType)); } diff --git a/tests/lib/Template/JSResourceLocatorTest.php b/tests/lib/Template/JSResourceLocatorTest.php index 7dedd4ad3c7..20fd79a91b5 100644 --- a/tests/lib/Template/JSResourceLocatorTest.php +++ b/tests/lib/Template/JSResourceLocatorTest.php @@ -63,9 +63,6 @@ class JSResourceLocatorTest extends \Test\TestCase { ); return new JSResourceLocator( $this->logger, - 'theme', - ['core' => 'map'], - ['3rd' => 'party'], $jsCombiner ); } diff --git a/tests/lib/Template/ResourceLocatorTest.php b/tests/lib/Template/ResourceLocatorTest.php index 0cb28843a53..fa329ca6581 100644 --- a/tests/lib/Template/ResourceLocatorTest.php +++ b/tests/lib/Template/ResourceLocatorTest.php @@ -8,6 +8,7 @@ namespace Test\Template; +use OC\SystemConfig; use OC\Template\ResourceNotFoundException; use Psr\Log\LoggerInterface; @@ -22,20 +23,23 @@ class ResourceLocatorTest extends \Test\TestCase { /** * @param string $theme - * @param array $core_map - * @param array $party_map - * @param array $appsRoots * @return \PHPUnit\Framework\MockObject\MockObject */ - public function getResourceLocator($theme, $core_map, $party_map, $appsRoots) { + public function getResourceLocator($theme) { + $systemConfig = $this->createMock(SystemConfig::class); + $systemConfig + ->expects($this->any()) + ->method('getValue') + ->with('theme', '') + ->willReturn($theme); + $this->overwriteService(SystemConfig::class, $systemConfig); return $this->getMockForAbstractClass('OC\Template\ResourceLocator', - [$this->logger, $theme, $core_map, $party_map, $appsRoots ], + [$this->logger], '', true, true, true, []); } public function testFind() { - $locator = $this->getResourceLocator('theme', - ['core' => 'map'], ['3rd' => 'party'], ['foo' => 'bar']); + $locator = $this->getResourceLocator('theme'); $locator->expects($this->once()) ->method('doFind') ->with('foo'); @@ -47,6 +51,11 @@ class ResourceLocatorTest extends \Test\TestCase { } public function testFindNotFound() { + $systemConfig = $this->createMock(SystemConfig::class); + $systemConfig->method('getValue') + ->with('theme', '') + ->willReturn('theme'); + $this->overwriteService(SystemConfig::class, $systemConfig); $locator = $this->getResourceLocator('theme', ['core' => 'map'], ['3rd' => 'party'], ['foo' => 'bar']); $locator->expects($this->once()) @@ -65,8 +74,7 @@ class ResourceLocatorTest extends \Test\TestCase { } public function testAppendIfExist() { - $locator = $this->getResourceLocator('theme', - [__DIR__ => 'map'], ['3rd' => 'party'], ['foo' => 'bar']); + $locator = $this->getResourceLocator('theme'); /** @var \OC\Template\ResourceLocator $locator */ $method = new \ReflectionMethod($locator, 'appendIfExist'); $method->setAccessible(true); @@ -75,11 +83,7 @@ class ResourceLocatorTest extends \Test\TestCase { $resource1 = [__DIR__, 'webroot', basename(__FILE__)]; $this->assertEquals([$resource1], $locator->getResources()); - $method->invoke($locator, __DIR__, basename(__FILE__)); - $resource2 = [__DIR__, 'map', basename(__FILE__)]; - $this->assertEquals([$resource1, $resource2], $locator->getResources()); - $method->invoke($locator, __DIR__, 'does-not-exist'); - $this->assertEquals([$resource1, $resource2], $locator->getResources()); + $this->assertEquals([$resource1], $locator->getResources()); } } |