diff options
author | Joas Schilling <coding@schilljs.com> | 2025-05-29 00:25:25 +0200 |
---|---|---|
committer | Joas Schilling <coding@schilljs.com> | 2025-05-29 09:17:49 +0200 |
commit | 746145f7f0048387e73521e973091442ccb95cec (patch) | |
tree | af035f563aedf73eff62d21e9c181580901a37ed | |
parent | b7215c932c96e6a7001c26226c7e7eede0ef1368 (diff) | |
download | nextcloud-server-746145f7f0048387e73521e973091442ccb95cec.tar.gz nextcloud-server-746145f7f0048387e73521e973091442ccb95cec.zip |
test: Migrate Federation and Files_Trashbin to PHPUnit 10
Signed-off-by: Joas Schilling <coding@schilljs.com>
18 files changed, 343 insertions, 490 deletions
diff --git a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php index 3da2e2e15e4..7ac68d618a1 100644 --- a/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/GetSharedSecretTest.php @@ -1,5 +1,6 @@ <?php +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -77,12 +78,9 @@ class GetSharedSecretTest extends TestCase { /** * @dataProvider dataTestExecute - * - * @param bool $isTrustedServer - * @param bool $retainBackgroundJob */ public function testExecute(bool $isTrustedServer, bool $retainBackgroundJob): void { - /** @var GetSharedSecret |\PHPUnit\Framework\MockObject\MockObject $getSharedSecret */ + /** @var GetSharedSecret&MockObject $getSharedSecret */ $getSharedSecret = $this->getMockBuilder(GetSharedSecret::class) ->setConstructorArgs( [ @@ -95,8 +93,10 @@ class GetSharedSecretTest extends TestCase { $this->timeFactory, $this->config, ] - )->setMethods(['parentStart'])->getMock(); - $this->invokePrivate($getSharedSecret, 'argument', [['url' => 'url', 'token' => 'token']]); + ) + ->onlyMethods(['parentStart']) + ->getMock(); + self::invokePrivate($getSharedSecret, 'argument', [['url' => 'url', 'token' => 'token']]); $this->trustedServers->expects($this->once())->method('isTrustedServer') ->with('url')->willReturn($isTrustedServer); @@ -105,7 +105,7 @@ class GetSharedSecretTest extends TestCase { } else { $getSharedSecret->expects($this->never())->method('parentStart'); } - $this->invokePrivate($getSharedSecret, 'retainJob', [$retainBackgroundJob]); + self::invokePrivate($getSharedSecret, 'retainJob', [$retainBackgroundJob]); $this->jobList->expects($this->once())->method('remove'); $this->timeFactory->method('getTime')->willReturn(42); @@ -128,7 +128,7 @@ class GetSharedSecretTest extends TestCase { $getSharedSecret->start($this->jobList); } - public function dataTestExecute() { + public static function dataTestExecute(): array { return [ [true, true], [true, false], @@ -138,10 +138,8 @@ class GetSharedSecretTest extends TestCase { /** * @dataProvider dataTestRun - * - * @param int $statusCode */ - public function testRun($statusCode): void { + public function testRun(int $statusCode): void { $target = 'targetURL'; $source = 'sourceURL'; $token = 'token'; @@ -181,18 +179,18 @@ class GetSharedSecretTest extends TestCase { $this->trustedServers->expects($this->never())->method('addSharedSecret'); } - $this->invokePrivate($this->getSharedSecret, 'run', [$argument]); + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); if ( $statusCode !== Http::STATUS_OK && $statusCode !== Http::STATUS_FORBIDDEN ) { - $this->assertTrue($this->invokePrivate($this->getSharedSecret, 'retainJob')); + $this->assertTrue(self::invokePrivate($this->getSharedSecret, 'retainJob')); } else { - $this->assertFalse($this->invokePrivate($this->getSharedSecret, 'retainJob')); + $this->assertFalse(self::invokePrivate($this->getSharedSecret, 'retainJob')); } } - public function dataTestRun() { + public static function dataTestRun(): array { return [ [Http::STATUS_OK], [Http::STATUS_FORBIDDEN], @@ -227,7 +225,7 @@ class GetSharedSecretTest extends TestCase { TrustedServers::STATUS_FAILURE ); - $this->invokePrivate($this->getSharedSecret, 'run', [$argument]); + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); } public function testRunConnectionError(): void { @@ -263,8 +261,8 @@ class GetSharedSecretTest extends TestCase { $this->trustedServers->expects($this->never())->method('addSharedSecret'); - $this->invokePrivate($this->getSharedSecret, 'run', [$argument]); + self::invokePrivate($this->getSharedSecret, 'run', [$argument]); - $this->assertTrue($this->invokePrivate($this->getSharedSecret, 'retainJob')); + $this->assertTrue(self::invokePrivate($this->getSharedSecret, 'retainJob')); } } diff --git a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php index 68f8cc070c8..8bec10c11e1 100644 --- a/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php +++ b/apps/federation/tests/BackgroundJob/RequestSharedSecretTest.php @@ -1,5 +1,6 @@ <?php +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -24,50 +25,28 @@ use Psr\Log\LoggerInterface; use Test\TestCase; class RequestSharedSecretTest extends TestCase { - /** @var MockObject|IClientService */ - private $httpClientService; - - /** @var MockObject|IClient */ - private $httpClient; - - /** @var MockObject|IJobList */ - private $jobList; - - /** @var MockObject|IURLGenerator */ - private $urlGenerator; - - /** @var MockObject|TrustedServers */ - private $trustedServers; - - /** @var MockObject|IResponse */ - private $response; - - /** @var MockObject|IDiscoveryService */ - private $discoveryService; - - /** @var MockObject|LoggerInterface */ - private $logger; - - /** @var MockObject|ITimeFactory */ - private $timeFactory; - - /** @var MockObject|IConfig */ - private $config; - - /** @var RequestSharedSecret */ - private $requestSharedSecret; + private IClientService&MockObject $httpClientService; + private IClient&MockObject $httpClient; + private IJobList&MockObject $jobList; + private IURLGenerator&MockObject $urlGenerator; + private TrustedServers&MockObject $trustedServers; + private IResponse&MockObject $response; + private IDiscoveryService&MockObject $discoveryService; + private LoggerInterface&MockObject $logger; + private ITimeFactory&MockObject $timeFactory; + private IConfig&MockObject $config; + private RequestSharedSecret $requestSharedSecret; protected function setUp(): void { parent::setUp(); $this->httpClientService = $this->createMock(IClientService::class); - $this->httpClient = $this->getMockBuilder(IClient::class)->getMock(); - $this->jobList = $this->getMockBuilder(IJobList::class)->getMock(); - $this->urlGenerator = $this->getMockBuilder(IURLGenerator::class)->getMock(); - $this->trustedServers = $this->getMockBuilder(TrustedServers::class) - ->disableOriginalConstructor()->getMock(); - $this->response = $this->getMockBuilder(IResponse::class)->getMock(); - $this->discoveryService = $this->getMockBuilder(IDiscoveryService::class)->getMock(); + $this->httpClient = $this->createMock(IClient::class); + $this->jobList = $this->createMock(IJobList::class); + $this->urlGenerator = $this->createMock(IURLGenerator::class); + $this->trustedServers = $this->createMock(TrustedServers::class); + $this->response = $this->createMock(IResponse::class); + $this->discoveryService = $this->createMock(IDiscoveryService::class); $this->logger = $this->createMock(LoggerInterface::class); $this->timeFactory = $this->createMock(ITimeFactory::class); $this->config = $this->createMock(IConfig::class); @@ -89,13 +68,10 @@ class RequestSharedSecretTest extends TestCase { /** * @dataProvider dataTestStart - * - * @param bool $isTrustedServer - * @param bool $retainBackgroundJob */ - public function testStart($isTrustedServer, $retainBackgroundJob): void { - /** @var RequestSharedSecret |MockObject $requestSharedSecret */ - $requestSharedSecret = $this->getMockBuilder('OCA\Federation\BackgroundJob\RequestSharedSecret') + public function testStart(bool $isTrustedServer, bool $retainBackgroundJob): void { + /** @var RequestSharedSecret&MockObject $requestSharedSecret */ + $requestSharedSecret = $this->getMockBuilder(RequestSharedSecret::class) ->setConstructorArgs( [ $this->httpClientService, @@ -107,8 +83,10 @@ class RequestSharedSecretTest extends TestCase { $this->timeFactory, $this->config, ] - )->setMethods(['parentStart'])->getMock(); - $this->invokePrivate($requestSharedSecret, 'argument', [['url' => 'url', 'token' => 'token']]); + ) + ->onlyMethods(['parentStart']) + ->getMock(); + self::invokePrivate($requestSharedSecret, 'argument', [['url' => 'url', 'token' => 'token']]); $this->trustedServers->expects($this->once())->method('isTrustedServer') ->with('url')->willReturn($isTrustedServer); @@ -117,7 +95,7 @@ class RequestSharedSecretTest extends TestCase { } else { $requestSharedSecret->expects($this->never())->method('parentStart'); } - $this->invokePrivate($requestSharedSecret, 'retainJob', [$retainBackgroundJob]); + self::invokePrivate($requestSharedSecret, 'retainJob', [$retainBackgroundJob]); $this->jobList->expects($this->once())->method('remove'); $this->timeFactory->method('getTime')->willReturn(42); @@ -141,7 +119,7 @@ class RequestSharedSecretTest extends TestCase { $requestSharedSecret->start($this->jobList); } - public function dataTestStart() { + public static function dataTestStart(): array { return [ [true, true], [true, false], @@ -151,8 +129,6 @@ class RequestSharedSecretTest extends TestCase { /** * @dataProvider dataTestRun - * - * @param int $statusCode */ public function testRun(int $statusCode, int $attempt = 0): void { $target = 'targetURL'; @@ -184,18 +160,18 @@ class RequestSharedSecretTest extends TestCase { $this->response->expects($this->once())->method('getStatusCode') ->willReturn($statusCode); - $this->invokePrivate($this->requestSharedSecret, 'run', [$argument]); + self::invokePrivate($this->requestSharedSecret, 'run', [$argument]); if ( $statusCode !== Http::STATUS_OK && ($statusCode !== Http::STATUS_FORBIDDEN || $attempt < 5) ) { - $this->assertTrue($this->invokePrivate($this->requestSharedSecret, 'retainJob')); + $this->assertTrue(self::invokePrivate($this->requestSharedSecret, 'retainJob')); } else { - $this->assertFalse($this->invokePrivate($this->requestSharedSecret, 'retainJob')); + $this->assertFalse(self::invokePrivate($this->requestSharedSecret, 'retainJob')); } } - public function dataTestRun() { + public static function dataTestRun(): array { return [ [Http::STATUS_OK], [Http::STATUS_FORBIDDEN, 5], @@ -231,7 +207,7 @@ class RequestSharedSecretTest extends TestCase { TrustedServers::STATUS_FAILURE ); - $this->invokePrivate($this->requestSharedSecret, 'run', [$argument]); + self::invokePrivate($this->requestSharedSecret, 'run', [$argument]); } public function testRunConnectionError(): void { @@ -267,7 +243,7 @@ class RequestSharedSecretTest extends TestCase { ] )->willThrowException($this->createMock(ConnectException::class)); - $this->invokePrivate($this->requestSharedSecret, 'run', [$argument]); - $this->assertTrue($this->invokePrivate($this->requestSharedSecret, 'retainJob')); + self::invokePrivate($this->requestSharedSecret, 'run', [$argument]); + $this->assertTrue(self::invokePrivate($this->requestSharedSecret, 'retainJob')); } } diff --git a/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php index 9f2d41a1072..25b0db94e21 100644 --- a/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php +++ b/apps/federation/tests/Controller/OCSAuthAPIControllerTest.php @@ -1,5 +1,6 @@ <?php +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -8,6 +9,7 @@ namespace OCA\Federation\Tests\Controller; use OC\BackgroundJob\JobList; +use OCA\Federation\BackgroundJob\GetSharedSecret; use OCA\Federation\Controller\OCSAuthAPIController; use OCA\Federation\DbHandler; use OCA\Federation\TrustedServers; @@ -16,34 +18,19 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\IRequest; use OCP\Security\Bruteforce\IThrottler; use OCP\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class OCSAuthAPIControllerTest extends TestCase { - /** @var \PHPUnit\Framework\MockObject\MockObject|IRequest */ - private $request; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ISecureRandom */ - private $secureRandom; - - /** @var \PHPUnit\Framework\MockObject\MockObject|JobList */ - private $jobList; - - /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers */ - private $trustedServers; - - /** @var \PHPUnit\Framework\MockObject\MockObject|DbHandler */ - private $dbHandler; - - /** @var \PHPUnit\Framework\MockObject\MockObject|LoggerInterface */ - private $logger; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ITimeFactory */ - private $timeFactory; - - /** @var \PHPUnit\Framework\MockObject\MockObject|IThrottler */ - private $throttler; - + private IRequest&MockObject $request; + private ISecureRandom&MockObject $secureRandom; + private JobList&MockObject $jobList; + private TrustedServers&MockObject $trustedServers; + private DbHandler&MockObject $dbHandler; + private LoggerInterface&MockObject $logger; + private ITimeFactory&MockObject $timeFactory; + private IThrottler&MockObject $throttler; private OCSAuthAPIController $ocsAuthApi; /** @var int simulated timestamp */ @@ -91,7 +78,7 @@ class OCSAuthAPIControllerTest extends TestCase { if ($ok) { $this->jobList->expects($this->once())->method('add') - ->with('OCA\Federation\BackgroundJob\GetSharedSecret', ['url' => $url, 'token' => $token, 'created' => $this->currentTime]); + ->with(GetSharedSecret::class, ['url' => $url, 'token' => $token, 'created' => $this->currentTime]); } else { $this->jobList->expects($this->never())->method('add'); $this->jobList->expects($this->never())->method('remove'); @@ -111,7 +98,7 @@ class OCSAuthAPIControllerTest extends TestCase { } } - public function dataTestRequestSharedSecret() { + public static function dataTestRequestSharedSecret(): array { return [ ['token2', 'token1', true, true], ['token1', 'token2', false, false], @@ -126,8 +113,8 @@ class OCSAuthAPIControllerTest extends TestCase { $url = 'url'; $token = 'token'; - /** @var OCSAuthAPIController | \PHPUnit\Framework\MockObject\MockObject $ocsAuthApi */ - $ocsAuthApi = $this->getMockBuilder('OCA\Federation\Controller\OCSAuthAPIController') + /** @var OCSAuthAPIController&MockObject $ocsAuthApi */ + $ocsAuthApi = $this->getMockBuilder(OCSAuthAPIController::class) ->setConstructorArgs( [ 'federation', @@ -140,7 +127,9 @@ class OCSAuthAPIControllerTest extends TestCase { $this->timeFactory, $this->throttler ] - )->setMethods(['isValidToken'])->getMock(); + ) + ->onlyMethods(['isValidToken']) + ->getMock(); $this->trustedServers ->expects($this->any()) @@ -171,7 +160,7 @@ class OCSAuthAPIControllerTest extends TestCase { } } - public function dataTestGetSharedSecret() { + public static function dataTestGetSharedSecret(): array { return [ [true, true, true], [false, true, false], diff --git a/apps/federation/tests/Controller/SettingsControllerTest.php b/apps/federation/tests/Controller/SettingsControllerTest.php index c3e83945e9a..d88f397da34 100644 --- a/apps/federation/tests/Controller/SettingsControllerTest.php +++ b/apps/federation/tests/Controller/SettingsControllerTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -20,19 +22,18 @@ use Test\TestCase; class SettingsControllerTest extends TestCase { private SettingsController $controller; - private MockObject&IRequest $request; - private MockObject&IL10N $l10n; - private MockObject&TrustedServers $trustedServers; - private MockObject&LoggerInterface $logger; + private IRequest&MockObject $request; + private IL10N&MockObject $l10n; + private TrustedServers&MockObject $trustedServers; + private LoggerInterface&MockObject $logger; protected function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder(IRequest::class)->getMock(); - $this->l10n = $this->getMockBuilder(IL10N::class)->getMock(); - $this->trustedServers = $this->getMockBuilder(TrustedServers::class) - ->disableOriginalConstructor()->getMock(); - $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); + $this->request = $this->createMock(IRequest::class); + $this->l10n = $this->createMock(IL10N::class); + $this->trustedServers = $this->createMock(TrustedServers::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->controller = new SettingsController( 'SettingsControllerTest', @@ -56,7 +57,7 @@ class SettingsControllerTest extends TestCase { ->willReturn(true); $result = $this->controller->addServer('url'); - $this->assertTrue($result instanceof DataResponse); + $this->assertInstanceOf(DataResponse::class, $result); $data = $result->getData(); $this->assertSame(200, $result->getStatus()); @@ -110,7 +111,7 @@ class SettingsControllerTest extends TestCase { ->willReturn(true); $this->assertNull( - $this->invokePrivate($this->controller, 'checkServer', ['url']) + self::invokePrivate($this->controller, 'checkServer', ['url']) ); } @@ -136,14 +137,11 @@ class SettingsControllerTest extends TestCase { } $this->assertTrue( - $this->invokePrivate($this->controller, 'checkServer', ['url']) + self::invokePrivate($this->controller, 'checkServer', ['url']) ); } - /** - * Data to simulate checkServer fails - */ - public function checkServerFails(): array { + public static function checkServerFails(): array { return [ [true, true], [false, false] diff --git a/apps/federation/tests/DAV/FedAuthTest.php b/apps/federation/tests/DAV/FedAuthTest.php index d059fff0481..c49e6f7e86f 100644 --- a/apps/federation/tests/DAV/FedAuthTest.php +++ b/apps/federation/tests/DAV/FedAuthTest.php @@ -1,5 +1,6 @@ <?php +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -9,27 +10,24 @@ namespace OCA\Federation\Tests\DAV; use OCA\Federation\DAV\FedAuth; use OCA\Federation\DbHandler; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class FedAuthTest extends TestCase { /** * @dataProvider providesUser - * - * @param array $expected - * @param string $user - * @param string $password */ - public function testFedAuth($expected, $user, $password): void { - /** @var DbHandler | \PHPUnit\Framework\MockObject\MockObject $db */ - $db = $this->getMockBuilder('OCA\Federation\DbHandler')->disableOriginalConstructor()->getMock(); + public function testFedAuth(bool $expected, string $user, string $password): void { + /** @var DbHandler&MockObject $db */ + $db = $this->createMock(DbHandler::class); $db->method('auth')->willReturn(true); $auth = new FedAuth($db); - $result = $this->invokePrivate($auth, 'validateUserPass', [$user, $password]); + $result = self::invokePrivate($auth, 'validateUserPass', [$user, $password]); $this->assertEquals($expected, $result); } - public function providesUser() { + public static function providesUser(): array { return [ [true, 'system', '123456'] ]; diff --git a/apps/federation/tests/DbHandlerTest.php b/apps/federation/tests/DbHandlerTest.php index 1db9f7f2315..a9abdbf776c 100644 --- a/apps/federation/tests/DbHandlerTest.php +++ b/apps/federation/tests/DbHandlerTest.php @@ -1,5 +1,6 @@ <?php +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -12,30 +13,23 @@ use OCA\Federation\TrustedServers; use OCP\IDBConnection; use OCP\IL10N; use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; /** * @group DB */ class DbHandlerTest extends TestCase { - - /** @var DbHandler */ - private $dbHandler; - - /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ - private $il10n; - - /** @var IDBConnection */ - private $connection; - - /** @var string */ - private $dbTable = 'trusted_servers'; + private DbHandler $dbHandler; + private IL10N&MockObject $il10n; + private IDBConnection $connection; + private string $dbTable = 'trusted_servers'; protected function setUp(): void { parent::setUp(); $this->connection = Server::get(IDBConnection::class); - $this->il10n = $this->getMockBuilder(IL10N::class)->getMock(); + $this->il10n = $this->createMock(IL10N::class); $this->dbHandler = new DbHandler( $this->connection, @@ -44,16 +38,17 @@ class DbHandlerTest extends TestCase { $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); $this->assertEmpty($result, 'we need to start with a empty trusted_servers table'); } protected function tearDown(): void { - parent::tearDown(); $query = $this->connection->getQueryBuilder()->delete($this->dbTable); - $query->execute(); + $query->executeStatement() + ; + parent::tearDown(); } /** @@ -63,7 +58,7 @@ class DbHandlerTest extends TestCase { * @param string $expectedUrl the url we expect to be written to the db * @param string $expectedHash the hash value we expect to be written to the db */ - public function testAddServer($url, $expectedUrl, $expectedHash): void { + public function testAddServer(string $url, string $expectedUrl, string $expectedHash): void { $id = $this->dbHandler->addServer($url); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); @@ -71,14 +66,14 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame($expectedUrl, $result[0]['url']); $this->assertSame($id, (int)$result[0]['id']); $this->assertSame($expectedHash, $result[0]['url_hash']); $this->assertSame(TrustedServers::STATUS_PENDING, (int)$result[0]['status']); } - public function dataTestAddServer() { + public static function dataTestAddServer(): array { return [ ['http://owncloud.org', 'http://owncloud.org', sha1('owncloud.org')], ['https://owncloud.org', 'https://owncloud.org', sha1('owncloud.org')], @@ -95,7 +90,7 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(2, count($result)); + $this->assertCount(2, $result); $this->assertSame('server1', $result[0]['url']); $this->assertSame('server2', $result[1]['url']); $this->assertSame($id1, (int)$result[0]['id']); @@ -107,7 +102,7 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame('server1', $result[0]['url']); $this->assertSame($id1, (int)$result[0]['id']); } @@ -135,19 +130,15 @@ class DbHandlerTest extends TestCase { /** * @dataProvider dataTestServerExists - * - * @param string $serverInTable - * @param string $checkForServer - * @param bool $expected */ - public function testServerExists($serverInTable, $checkForServer, $expected): void { + public function testServerExists(string $serverInTable, string $checkForServer, bool $expected): void { $this->dbHandler->addServer($serverInTable); $this->assertSame($expected, $this->dbHandler->serverExists($checkForServer) ); } - public function dataTestServerExists() { + public static function dataTestServerExists(): array { return [ ['server1', 'server1', true], ['server1', 'http://server1', true], @@ -159,18 +150,18 @@ class DbHandlerTest extends TestCase { $this->dbHandler->addServer('server1'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(null, $result[0]['token']); $this->dbHandler->addToken('http://server1', 'token'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame('token', $result[0]['token']); } @@ -189,7 +180,7 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(null, $result[0]['shared_secret']); $this->dbHandler->addSharedSecret('http://server1', 'secret'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); @@ -197,7 +188,7 @@ class DbHandlerTest extends TestCase { $qResult = $query->execute(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame('secret', $result[0]['shared_secret']); } @@ -213,18 +204,18 @@ class DbHandlerTest extends TestCase { $this->dbHandler->addServer('server1'); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(TrustedServers::STATUS_PENDING, (int)$result[0]['status']); $this->dbHandler->setServerStatus('http://server1', TrustedServers::STATUS_OK); $query = $this->connection->getQueryBuilder()->select('*')->from($this->dbTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(TrustedServers::STATUS_OK, (int)$result[0]['status']); } @@ -245,17 +236,14 @@ class DbHandlerTest extends TestCase { * hash should always be computed with the normalized URL * * @dataProvider dataTestHash - * - * @param string $url - * @param string $expected */ - public function testHash($url, $expected): void { + public function testHash(string $url, string $expected): void { $this->assertSame($expected, $this->invokePrivate($this->dbHandler, 'hash', [$url]) ); } - public function dataTestHash() { + public static function dataTestHash(): array { return [ ['server1', sha1('server1')], ['http://server1', sha1('server1')], @@ -266,17 +254,14 @@ class DbHandlerTest extends TestCase { /** * @dataProvider dataTestNormalizeUrl - * - * @param string $url - * @param string $expected */ - public function testNormalizeUrl($url, $expected): void { + public function testNormalizeUrl(string $url, string $expected): void { $this->assertSame($expected, $this->invokePrivate($this->dbHandler, 'normalizeUrl', [$url]) ); } - public function dataTestNormalizeUrl() { + public static function dataTestNormalizeUrl(): array { return [ ['owncloud.org', 'owncloud.org'], ['http://owncloud.org', 'owncloud.org'], @@ -289,7 +274,7 @@ class DbHandlerTest extends TestCase { /** * @dataProvider providesAuth */ - public function testAuth($expectedResult, $user, $password): void { + public function testAuth(bool $expectedResult, string $user, string $password): void { if ($expectedResult) { $this->dbHandler->addServer('url1'); $this->dbHandler->addSharedSecret('url1', $password); @@ -298,7 +283,7 @@ class DbHandlerTest extends TestCase { $this->assertEquals($expectedResult, $result); } - public function providesAuth() { + public static function providesAuth(): array { return [ [false, 'foo', ''], [true, 'system', '123456789'], diff --git a/apps/federation/tests/Settings/AdminTest.php b/apps/federation/tests/Settings/AdminTest.php index 3d58fae2d7b..b4c7121c5c9 100644 --- a/apps/federation/tests/Settings/AdminTest.php +++ b/apps/federation/tests/Settings/AdminTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -9,17 +11,16 @@ use OCA\Federation\Settings\Admin; use OCA\Federation\TrustedServers; use OCP\AppFramework\Http\TemplateResponse; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class AdminTest extends TestCase { - /** @var Admin */ - private $admin; - /** @var TrustedServers */ - private $trustedServers; + private TrustedServers&MockObject $trustedServers; + private Admin $admin; protected function setUp(): void { parent::setUp(); - $this->trustedServers = $this->getMockBuilder('\OCA\Federation\TrustedServers')->disableOriginalConstructor()->getMock(); + $this->trustedServers = $this->createMock(\OCA\Federation\TrustedServers::class); $this->admin = new Admin( $this->trustedServers, $this->createMock(IL10N::class) diff --git a/apps/federation/tests/SyncFederationAddressbooksTest.php b/apps/federation/tests/SyncFederationAddressbooksTest.php index 39274a11ade..aebd4aa2b93 100644 --- a/apps/federation/tests/SyncFederationAddressbooksTest.php +++ b/apps/federation/tests/SyncFederationAddressbooksTest.php @@ -1,5 +1,6 @@ <?php +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -16,30 +17,21 @@ use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; class SyncFederationAddressbooksTest extends \Test\TestCase { - - /** @var array */ - private $callBacks = []; - - /** @var MockObject | DiscoveryService */ - private $discoveryService; - - /** @var MockObject|LoggerInterface */ - private $logger; + private array $callBacks = []; + private DiscoveryService&MockObject $discoveryService; + private LoggerInterface&MockObject $logger; protected function setUp(): void { parent::setUp(); - $this->discoveryService = $this->getMockBuilder(DiscoveryService::class) - ->disableOriginalConstructor()->getMock(); + $this->discoveryService = $this->createMock(DiscoveryService::class); $this->discoveryService->expects($this->any())->method('discover')->willReturn([]); $this->logger = $this->createMock(LoggerInterface::class); } public function testSync(): void { - /** @var DbHandler | MockObject $dbHandler */ - $dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler') - ->disableOriginalConstructor() - ->getMock(); + /** @var DbHandler&MockObject $dbHandler */ + $dbHandler = $this->createMock(DbHandler::class); $dbHandler->method('getAllServer') ->willReturn([ [ @@ -51,9 +43,7 @@ class SyncFederationAddressbooksTest extends \Test\TestCase { ]); $dbHandler->expects($this->once())->method('setServerStatus')-> with('https://cloud.drop.box', 1, '1'); - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); + $syncService = $this->createMock(SyncService::class); $syncService->expects($this->once())->method('syncRemoteAddressBook') ->willReturn('1'); @@ -62,14 +52,12 @@ class SyncFederationAddressbooksTest extends \Test\TestCase { $s->syncThemAll(function ($url, $ex): void { $this->callBacks[] = [$url, $ex]; }); - $this->assertEquals('1', count($this->callBacks)); + $this->assertCount(1, $this->callBacks); } public function testException(): void { - /** @var DbHandler | MockObject $dbHandler */ - $dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler')-> - disableOriginalConstructor()-> - getMock(); + /** @var DbHandler&MockObject $dbHandler */ + $dbHandler = $this->createMock(DbHandler::class); $dbHandler->method('getAllServer')-> willReturn([ [ @@ -79,9 +67,7 @@ class SyncFederationAddressbooksTest extends \Test\TestCase { 'sync_token' => '0' ] ]); - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); + $syncService = $this->createMock(SyncService::class); $syncService->expects($this->once())->method('syncRemoteAddressBook') ->willThrowException(new \Exception('something did not work out')); @@ -90,14 +76,12 @@ class SyncFederationAddressbooksTest extends \Test\TestCase { $s->syncThemAll(function ($url, $ex): void { $this->callBacks[] = [$url, $ex]; }); - $this->assertEquals(2, count($this->callBacks)); + $this->assertCount(2, $this->callBacks); } public function testSuccessfulSyncWithoutChangesAfterFailure(): void { - /** @var DbHandler | MockObject $dbHandler */ - $dbHandler = $this->getMockBuilder('OCA\Federation\DbHandler') - ->disableOriginalConstructor() - ->getMock(); + /** @var DbHandler&MockObject $dbHandler */ + $dbHandler = $this->createMock(DbHandler::class); $dbHandler->method('getAllServer') ->willReturn([ [ @@ -110,9 +94,7 @@ class SyncFederationAddressbooksTest extends \Test\TestCase { $dbHandler->method('getServerStatus')->willReturn(TrustedServers::STATUS_FAILURE); $dbHandler->expects($this->once())->method('setServerStatus')-> with('https://cloud.drop.box', 1); - $syncService = $this->getMockBuilder('OCA\DAV\CardDAV\SyncService') - ->disableOriginalConstructor() - ->getMock(); + $syncService = $this->createMock(SyncService::class); $syncService->expects($this->once())->method('syncRemoteAddressBook') ->willReturn('0'); @@ -121,6 +103,6 @@ class SyncFederationAddressbooksTest extends \Test\TestCase { $s->syncThemAll(function ($url, $ex): void { $this->callBacks[] = [$url, $ex]; }); - $this->assertEquals('1', count($this->callBacks)); + $this->assertCount(1, $this->callBacks); } } diff --git a/apps/federation/tests/TrustedServersTest.php b/apps/federation/tests/TrustedServersTest.php index c3f0368858b..4d64df7a5e1 100644 --- a/apps/federation/tests/TrustedServersTest.php +++ b/apps/federation/tests/TrustedServersTest.php @@ -1,5 +1,6 @@ <?php +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -7,6 +8,7 @@ */ namespace OCA\Federation\Tests; +use OCA\Federation\BackgroundJob\RequestSharedSecret; use OCA\Federation\DbHandler; use OCA\Federation\TrustedServers; use OCP\AppFramework\Utility\ITimeFactory; @@ -19,57 +21,35 @@ use OCP\Http\Client\IClientService; use OCP\Http\Client\IResponse; use OCP\IConfig; use OCP\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class TrustedServersTest extends TestCase { - /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers */ - private $trustedServers; - - /** @var \PHPUnit\Framework\MockObject\MockObject | DbHandler */ - private $dbHandler; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IClientService */ - private $httpClientService; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IClient */ - private $httpClient; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IResponse */ - private $response; - - /** @var \PHPUnit\Framework\MockObject\MockObject | LoggerInterface */ - private $logger; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IJobList */ - private $jobList; - - /** @var \PHPUnit\Framework\MockObject\MockObject | ISecureRandom */ - private $secureRandom; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IConfig */ - private $config; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IEventDispatcher */ - private $dispatcher; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ITimeFactory */ - private $timeFactory; + private TrustedServers $trustedServers; + private DbHandler&MockObject $dbHandler; + private IClientService&MockObject $httpClientService; + private IClient&MockObject $httpClient; + private IResponse&MockObject $response; + private LoggerInterface&MockObject $logger; + private IJobList&MockObject $jobList; + private ISecureRandom&MockObject $secureRandom; + private IConfig&MockObject $config; + private IEventDispatcher&MockObject $dispatcher; + private ITimeFactory&MockObject $timeFactory; protected function setUp(): void { parent::setUp(); - $this->dbHandler = $this->getMockBuilder(DbHandler::class) - ->disableOriginalConstructor()->getMock(); - $this->dispatcher = $this->getMockBuilder(IEventDispatcher::class) - ->disableOriginalConstructor()->getMock(); - $this->httpClientService = $this->getMockBuilder(IClientService::class)->getMock(); - $this->httpClient = $this->getMockBuilder(IClient::class)->getMock(); - $this->response = $this->getMockBuilder(IResponse::class)->getMock(); - $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock(); - $this->jobList = $this->getMockBuilder(IJobList::class)->getMock(); - $this->secureRandom = $this->getMockBuilder(ISecureRandom::class)->getMock(); - $this->config = $this->getMockBuilder(IConfig::class)->getMock(); + $this->dbHandler = $this->createMock(DbHandler::class); + $this->dispatcher = $this->createMock(IEventDispatcher::class); + $this->httpClientService = $this->createMock(IClientService::class); + $this->httpClient = $this->createMock(IClient::class); + $this->response = $this->createMock(IResponse::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->jobList = $this->createMock(IJobList::class); + $this->secureRandom = $this->createMock(ISecureRandom::class); + $this->config = $this->createMock(IConfig::class); $this->timeFactory = $this->createMock(ITimeFactory::class); $this->trustedServers = new TrustedServers( @@ -85,8 +65,8 @@ class TrustedServersTest extends TestCase { } public function testAddServer(): void { - /** @var \PHPUnit\Framework\MockObject\MockObject|TrustedServers $trustedServers */ - $trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + /** @var TrustedServers&MockObject $trustedServers */ + $trustedServers = $this->getMockBuilder(TrustedServers::class) ->setConstructorArgs( [ $this->dbHandler, @@ -99,7 +79,7 @@ class TrustedServersTest extends TestCase { $this->timeFactory ] ) - ->setMethods(['normalizeUrl', 'updateProtocol']) + ->onlyMethods(['updateProtocol']) ->getMock(); $trustedServers->expects($this->once())->method('updateProtocol') ->with('url')->willReturn('https://url'); @@ -112,12 +92,12 @@ class TrustedServersTest extends TestCase { ->willReturn('token'); $this->dbHandler->expects($this->once())->method('addToken')->with('https://url', 'token'); $this->jobList->expects($this->once())->method('add') - ->with('OCA\Federation\BackgroundJob\RequestSharedSecret', + ->with(RequestSharedSecret::class, ['url' => 'https://url', 'token' => 'token', 'created' => 1234567]); $this->assertSame( - $trustedServers->addServer('url'), - 1 + 1, + $trustedServers->addServer('url') ); } @@ -196,8 +176,8 @@ class TrustedServersTest extends TestCase { public function testIsNextcloudServer(int $statusCode, bool $isValidNextcloudVersion, bool $expected): void { $server = 'server1'; - /** @var \PHPUnit\Framework\MockObject\MockObject | TrustedServers $trustedServers */ - $trustedServers = $this->getMockBuilder('OCA\Federation\TrustedServers') + /** @var TrustedServers&MockObject $trustedServers */ + $trustedServers = $this->getMockBuilder(TrustedServers::class) ->setConstructorArgs( [ $this->dbHandler, @@ -210,7 +190,7 @@ class TrustedServersTest extends TestCase { $this->timeFactory ] ) - ->setMethods(['checkNextcloudVersion']) + ->onlyMethods(['checkNextcloudVersion']) ->getMock(); $this->httpClientService->expects($this->once())->method('newClient') @@ -236,7 +216,7 @@ class TrustedServersTest extends TestCase { ); } - public function dataTestIsNextcloudServer(): array { + public static function dataTestIsNextcloudServer(): array { return [ [200, true, true], [200, false, false], @@ -244,19 +224,17 @@ class TrustedServersTest extends TestCase { ]; } - /** - * @expectedExceptionMessage simulated exception - */ public function testIsNextcloudServerFail(): void { $server = 'server1'; - $this->httpClientService->expects($this->once())->method('newClient') + $this->httpClientService->expects($this->once()) + ->method('newClient') ->willReturn($this->httpClient); - $this->httpClient->expects($this->once())->method('get')->with($server . '/status.php') - ->willReturnCallback(function (): void { - throw new \Exception('simulated exception'); - }); + $this->httpClient->expects($this->once()) + ->method('get') + ->with($server . '/status.php') + ->willThrowException(new \Exception('simulated exception')); $this->assertFalse($this->trustedServers->isNextcloudServer($server)); } @@ -264,11 +242,11 @@ class TrustedServersTest extends TestCase { /** * @dataProvider dataTestCheckNextcloudVersion */ - public function testCheckNextcloudVersion($status): void { - $this->assertTrue($this->invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status])); + public function testCheckNextcloudVersion(string $status): void { + $this->assertTrue(self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status])); } - public function dataTestCheckNextcloudVersion(): array { + public static function dataTestCheckNextcloudVersion(): array { return [ ['{"version":"9.0.0"}'], ['{"version":"9.1.0"}'] @@ -282,10 +260,10 @@ class TrustedServersTest extends TestCase { $this->expectException(HintException::class); $this->expectExceptionMessage('Remote server version is too low. 9.0 is required.'); - $this->invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status]); + self::invokePrivate($this->trustedServers, 'checkNextcloudVersion', [$status]); } - public function dataTestCheckNextcloudVersionTooLow(): array { + public static function dataTestCheckNextcloudVersionTooLow(): array { return [ ['{"version":"8.2.3"}'], ]; @@ -296,11 +274,11 @@ class TrustedServersTest extends TestCase { */ public function testUpdateProtocol(string $url, string $expected): void { $this->assertSame($expected, - $this->invokePrivate($this->trustedServers, 'updateProtocol', [$url]) + self::invokePrivate($this->trustedServers, 'updateProtocol', [$url]) ); } - public function dataTestUpdateProtocol(): array { + public static function dataTestUpdateProtocol(): array { return [ ['http://owncloud.org', 'http://owncloud.org'], ['https://owncloud.org', 'https://owncloud.org'], diff --git a/apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php b/apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php index ee833e6beb8..9468fb7add0 100644 --- a/apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php +++ b/apps/files_trashbin/tests/BackgroundJob/ExpireTrashTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -18,23 +20,12 @@ use Psr\Log\LoggerInterface; use Test\TestCase; class ExpireTrashTest extends TestCase { - /** @var IAppConfig&MockObject */ - private $appConfig; - - /** @var IUserManager&MockObject */ - private $userManager; - - /** @var Expiration&MockObject */ - private $expiration; - - /** @var IJobList&MockObject */ - private $jobList; - - /** @var LoggerInterface&MockObject */ - private $logger; - - /** @var ITimeFactory&MockObject */ - private $time; + private IAppConfig&MockObject $appConfig; + private IUserManager&MockObject $userManager; + private Expiration&MockObject $expiration; + private IJobList&MockObject $jobList; + private LoggerInterface&MockObject $logger; + private ITimeFactory&MockObject $time; protected function setUp(): void { parent::setUp(); diff --git a/apps/files_trashbin/tests/CapabilitiesTest.php b/apps/files_trashbin/tests/CapabilitiesTest.php index a5e4e79aefd..1c460cc5665 100644 --- a/apps/files_trashbin/tests/CapabilitiesTest.php +++ b/apps/files_trashbin/tests/CapabilitiesTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -9,9 +11,7 @@ use OCA\Files_Trashbin\Capabilities; use Test\TestCase; class CapabilitiesTest extends TestCase { - - /** @var Capabilities */ - private $capabilities; + private Capabilities $capabilities; protected function setUp(): void { parent::setUp(); diff --git a/apps/files_trashbin/tests/Command/CleanUpTest.php b/apps/files_trashbin/tests/Command/CleanUpTest.php index 25d38752e91..3dce8f0c92e 100644 --- a/apps/files_trashbin/tests/Command/CleanUpTest.php +++ b/apps/files_trashbin/tests/Command/CleanUpTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -6,12 +8,13 @@ */ namespace OCA\Files_Trashbin\Tests\Command; -use OC\User\Manager; use OCA\Files_Trashbin\Command\CleanUp; use OCP\Files\IRootFolder; use OCP\IDBConnection; +use OCP\IUserManager; use OCP\Server; use OCP\UserInterface; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Exception\InvalidOptionException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\NullOutput; @@ -26,31 +29,17 @@ use Test\TestCase; * @package OCA\Files_Trashbin\Tests\Command */ class CleanUpTest extends TestCase { - - /** @var CleanUp */ - protected $cleanup; - - /** @var \PHPUnit\Framework\MockObject\MockObject | Manager */ - protected $userManager; - - /** @var \PHPUnit\Framework\MockObject\MockObject | IRootFolder */ - protected $rootFolder; - - /** @var IDBConnection */ - protected $dbConnection; - - /** @var string */ - protected $trashTable = 'files_trash'; - - /** @var string */ - protected $user0 = 'user0'; + protected IUserManager&MockObject $userManager; + protected IRootFolder&MockObject $rootFolder; + protected IDBConnection $dbConnection; + protected CleanUp $cleanup; + protected string $trashTable = 'files_trash'; + protected string $user0 = 'user0'; protected function setUp(): void { parent::setUp(); - $this->rootFolder = $this->getMockBuilder('OCP\Files\IRootFolder') - ->disableOriginalConstructor()->getMock(); - $this->userManager = $this->getMockBuilder('OC\User\Manager') - ->disableOriginalConstructor()->getMock(); + $this->rootFolder = $this->createMock(IRootFolder::class); + $this->userManager = $this->createMock(IUserManager::class); $this->dbConnection = Server::get(IDBConnection::class); @@ -60,9 +49,9 @@ class CleanUpTest extends TestCase { /** * populate files_trash table with 10 dummy values */ - public function initTable() { + public function initTable(): void { $query = $this->dbConnection->getQueryBuilder(); - $query->delete($this->trashTable)->execute(); + $query->delete($this->trashTable)->executeStatement(); for ($i = 0; $i < 10; $i++) { $query->insert($this->trashTable) ->values([ @@ -70,19 +59,18 @@ class CleanUpTest extends TestCase { 'timestamp' => $query->expr()->literal($i), 'location' => $query->expr()->literal('.'), 'user' => $query->expr()->literal('user' . $i % 2) - ])->execute(); + ])->executeStatement(); } $getAllQuery = $this->dbConnection->getQueryBuilder(); $result = $getAllQuery->select('id') ->from($this->trashTable) - ->execute() + ->executeQuery() ->fetchAll(); - $this->assertSame(10, count($result)); + $this->assertCount(10, $result); } /** * @dataProvider dataTestRemoveDeletedFiles - * @param boolean $nodeExists */ public function testRemoveDeletedFiles(bool $nodeExists): void { $this->initTable(); @@ -101,7 +89,7 @@ class CleanUpTest extends TestCase { $this->rootFolder->expects($this->never())->method('get'); $this->rootFolder->expects($this->never())->method('delete'); } - $this->invokePrivate($this->cleanup, 'removeDeletedFiles', [$this->user0, new NullOutput(), false]); + self::invokePrivate($this->cleanup, 'removeDeletedFiles', [$this->user0, new NullOutput(), false]); if ($nodeExists) { // if the delete operation was executed only files from user1 @@ -110,11 +98,11 @@ class CleanUpTest extends TestCase { $query->select('user') ->from($this->trashTable); - $qResult = $query->execute(); + $qResult = $query->executeQuery(); $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(5, count($result)); + $this->assertCount(5, $result); foreach ($result as $r) { $this->assertSame('user1', $r['user']); } @@ -124,12 +112,12 @@ class CleanUpTest extends TestCase { $getAllQuery = $this->dbConnection->getQueryBuilder(); $result = $getAllQuery->select('id') ->from($this->trashTable) - ->execute() + ->executeQuery() ->fetchAll(); - $this->assertSame(10, count($result)); + $this->assertCount(10, $result); } } - public function dataTestRemoveDeletedFiles() { + public static function dataTestRemoveDeletedFiles(): array { return [ [true], [false] @@ -141,8 +129,8 @@ class CleanUpTest extends TestCase { */ public function testExecuteDeleteListOfUsers(): void { $userIds = ['user1', 'user2', 'user3']; - $instance = $this->getMockBuilder('OCA\Files_Trashbin\Command\CleanUp') - ->setMethods(['removeDeletedFiles']) + $instance = $this->getMockBuilder(\OCA\Files_Trashbin\Command\CleanUp::class) + ->onlyMethods(['removeDeletedFiles']) ->setConstructorArgs([$this->rootFolder, $this->userManager, $this->dbConnection]) ->getMock(); $instance->expects($this->exactly(count($userIds))) @@ -152,8 +140,7 @@ class CleanUpTest extends TestCase { }); $this->userManager->expects($this->exactly(count($userIds))) ->method('userExists')->willReturn(true); - $inputInterface = $this->getMockBuilder('\Symfony\Component\Console\Input\InputInterface') - ->disableOriginalConstructor()->getMock(); + $inputInterface = $this->createMock(\Symfony\Component\Console\Input\InputInterface::class); $inputInterface->method('getArgument') ->with('user_id') ->willReturn($userIds); @@ -162,9 +149,8 @@ class CleanUpTest extends TestCase { ['all-users', false], ['verbose', false], ]); - $outputInterface = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface') - ->disableOriginalConstructor()->getMock(); - $this->invokePrivate($instance, 'execute', [$inputInterface, $outputInterface]); + $outputInterface = $this->createMock(\Symfony\Component\Console\Output\OutputInterface::class); + self::invokePrivate($instance, 'execute', [$inputInterface, $outputInterface]); } /** @@ -173,8 +159,8 @@ class CleanUpTest extends TestCase { public function testExecuteAllUsers(): void { $userIds = []; $backendUsers = ['user1', 'user2']; - $instance = $this->getMockBuilder('OCA\Files_Trashbin\Command\CleanUp') - ->setMethods(['removeDeletedFiles']) + $instance = $this->getMockBuilder(\OCA\Files_Trashbin\Command\CleanUp::class) + ->onlyMethods(['removeDeletedFiles']) ->setConstructorArgs([$this->rootFolder, $this->userManager, $this->dbConnection]) ->getMock(); $backend = $this->createMock(UserInterface::class); @@ -199,7 +185,7 @@ class CleanUpTest extends TestCase { $this->userManager ->method('getBackends') ->willReturn([$backend]); - $this->invokePrivate($instance, 'execute', [$inputInterface, $outputInterface]); + self::invokePrivate($instance, 'execute', [$inputInterface, $outputInterface]); } public function testExecuteNoUsersAndNoAllUsers(): void { @@ -217,7 +203,7 @@ class CleanUpTest extends TestCase { $this->expectException(InvalidOptionException::class); $this->expectExceptionMessage('Either specify a user_id or --all-users'); - $this->invokePrivate($this->cleanup, 'execute', [$inputInterface, $outputInterface]); + self::invokePrivate($this->cleanup, 'execute', [$inputInterface, $outputInterface]); } public function testExecuteUsersAndAllUsers(): void { @@ -235,6 +221,6 @@ class CleanUpTest extends TestCase { $this->expectException(InvalidOptionException::class); $this->expectExceptionMessage('Either specify a user_id or --all-users'); - $this->invokePrivate($this->cleanup, 'execute', [$inputInterface, $outputInterface]); + self::invokePrivate($this->cleanup, 'execute', [$inputInterface, $outputInterface]); } } diff --git a/apps/files_trashbin/tests/Command/ExpireTest.php b/apps/files_trashbin/tests/Command/ExpireTest.php index 4402e07bbb0..5a66dac8c6e 100644 --- a/apps/files_trashbin/tests/Command/ExpireTest.php +++ b/apps/files_trashbin/tests/Command/ExpireTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2018-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. diff --git a/apps/files_trashbin/tests/Controller/PreviewControllerTest.php b/apps/files_trashbin/tests/Controller/PreviewControllerTest.php index 1076870bb9f..bb951c9c8c7 100644 --- a/apps/files_trashbin/tests/Controller/PreviewControllerTest.php +++ b/apps/files_trashbin/tests/Controller/PreviewControllerTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -20,32 +22,18 @@ use OCP\IPreview; use OCP\IRequest; use OCP\IUser; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class PreviewControllerTest extends TestCase { - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; - - /** @var string */ - private $userId; - - /** @var IMimeTypeDetector|\PHPUnit\Framework\MockObject\MockObject */ - private $mimeTypeDetector; - - /** @var IPreview|\PHPUnit\Framework\MockObject\MockObject */ - private $previewManager; - - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $time; - - /** @var PreviewController */ - private $controller; - - /** @var ITrashManager|\PHPUnit\Framework\MockObject\MockObject */ - private $trashManager; - - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; + private IRootFolder&MockObject $rootFolder; + private string $userId; + private IMimeTypeDetector&MockObject $mimeTypeDetector; + private IPreview&MockObject $previewManager; + private ITimeFactory&MockObject $time; + private ITrashManager&MockObject $trashManager; + private IUserSession&MockObject $userSession; + private PreviewController $controller; protected function setUp(): void { parent::setUp(); diff --git a/apps/files_trashbin/tests/ExpirationTest.php b/apps/files_trashbin/tests/ExpirationTest.php index 7f026c16806..aab07de8162 100644 --- a/apps/files_trashbin/tests/ExpirationTest.php +++ b/apps/files_trashbin/tests/ExpirationTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -16,7 +18,7 @@ class ExpirationTest extends \Test\TestCase { public const FAKE_TIME_NOW = 1000000; - public function expirationData() { + public static function expirationData(): array { $today = 100 * self::SECONDS_PER_DAY; $back10Days = (100 - 10) * self::SECONDS_PER_DAY; $back20Days = (100 - 20) * self::SECONDS_PER_DAY; @@ -82,14 +84,8 @@ class ExpirationTest extends \Test\TestCase { /** * @dataProvider expirationData - * - * @param string $retentionObligation - * @param int $timeNow - * @param int $timestamp - * @param bool $quotaExceeded - * @param string $expectedResult */ - public function testExpiration($retentionObligation, $timeNow, $timestamp, $quotaExceeded, $expectedResult): void { + public function testExpiration(string $retentionObligation, int $timeNow, int $timestamp, bool $quotaExceeded, bool $expectedResult): void { $mockedConfig = $this->getMockedConfig($retentionObligation); $mockedTimeFactory = $this->getMockedTimeFactory($timeNow); @@ -100,7 +96,7 @@ class ExpirationTest extends \Test\TestCase { } - public function timestampTestData(): array { + public static function timestampTestData(): array { return [ [ 'disabled', false], [ 'auto', false ], @@ -116,11 +112,8 @@ class ExpirationTest extends \Test\TestCase { /** * @dataProvider timestampTestData - * - * @param string $configValue - * @param int $expectedMaxAgeTimestamp */ - public function testGetMaxAgeAsTimestamp($configValue, $expectedMaxAgeTimestamp): void { + public function testGetMaxAgeAsTimestamp(string $configValue, bool|int $expectedMaxAgeTimestamp): void { $mockedConfig = $this->getMockedConfig($configValue); $mockedTimeFactory = $this->getMockedTimeFactory( self::FAKE_TIME_NOW @@ -132,10 +125,9 @@ class ExpirationTest extends \Test\TestCase { } /** - * @param int $time * @return ITimeFactory|MockObject */ - private function getMockedTimeFactory($time) { + private function getMockedTimeFactory(int $time) { $mockedTimeFactory = $this->createMock(ITimeFactory::class); $mockedTimeFactory->expects($this->any()) ->method('getTime') @@ -145,10 +137,9 @@ class ExpirationTest extends \Test\TestCase { } /** - * @param string $returnValue * @return IConfig|MockObject */ - private function getMockedConfig($returnValue) { + private function getMockedConfig(string $returnValue) { $mockedConfig = $this->createMock(IConfig::class); $mockedConfig->expects($this->any()) ->method('getSystemValue') diff --git a/apps/files_trashbin/tests/Sabre/TrashbinPluginTest.php b/apps/files_trashbin/tests/Sabre/TrashbinPluginTest.php index 60cc69ba09d..6c566afc738 100644 --- a/apps/files_trashbin/tests/Sabre/TrashbinPluginTest.php +++ b/apps/files_trashbin/tests/Sabre/TrashbinPluginTest.php @@ -1,5 +1,6 @@ <?php +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -33,19 +34,23 @@ class TrashbinPluginTest extends TestCase { */ public function testQuota(int $quota, int $fileSize, bool $expectedResult): void { $fileInfo = $this->createMock(ITrashItem::class); - $fileInfo->method('getSize')->willReturn($fileSize); + $fileInfo->method('getSize') + ->willReturn($fileSize); $trashNode = $this->createMock(ITrash::class); - $trashNode->method('getFileInfo')->willReturn($fileInfo); + $trashNode->method('getFileInfo') + ->willReturn($fileInfo); $restoreNode = $this->createMock(RestoreFolder::class); - $this->server->tree->method('getNodeForPath')->willReturn($trashNode, $restoreNode); + $this->server->tree->method('getNodeForPath') + ->willReturn($trashNode, $restoreNode); $previewManager = $this->createMock(IPreview::class); $view = $this->createMock(View::class); - $view->method('free_space')->willReturn($quota); + $view->method('free_space') + ->willReturn($quota); $plugin = new TrashbinPlugin($previewManager, $view); $plugin->initialize($this->server); @@ -55,7 +60,7 @@ class TrashbinPluginTest extends TestCase { $this->assertEquals($expectedResult, $plugin->beforeMove($sourcePath, $destinationPath)); } - public function quotaProvider(): array { + public static function quotaProvider(): array { return [ [ 1024, 512, true ], [ 512, 513, false ], diff --git a/apps/files_trashbin/tests/StorageTest.php b/apps/files_trashbin/tests/StorageTest.php index 5c73e47b307..2b2508a358b 100644 --- a/apps/files_trashbin/tests/StorageTest.php +++ b/apps/files_trashbin/tests/StorageTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -27,6 +29,7 @@ use OCP\IUserManager; use OCP\Lock\ILockingProvider; use OCP\Server; use OCP\Share\IShare; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\Traits\MountProviderTrait; @@ -50,20 +53,9 @@ class TemporaryNoCross extends Temporary { class StorageTest extends \Test\TestCase { use MountProviderTrait; - /** - * @var string - */ - private $user; - - /** - * @var View - */ - private $rootView; - - /** - * @var View - */ - private $userView; + private string $user; + private View $rootView; + private View $userView; // 239 chars so appended timestamp of 12 chars will exceed max length of 250 chars private const LONG_FILENAME = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.txt'; @@ -121,7 +113,7 @@ class StorageTest extends \Test\TestCase { // check if file is in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('test.txt', substr($name, 0, strrpos($name, '.'))); } @@ -138,7 +130,7 @@ class StorageTest extends \Test\TestCase { // check if folder is in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('folder', substr($name, 0, strrpos($name, '.'))); @@ -162,7 +154,7 @@ class StorageTest extends \Test\TestCase { // check if file is in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals($truncatedFilename, substr($name, 0, strrpos($name, '.'))); } @@ -181,7 +173,7 @@ class StorageTest extends \Test\TestCase { // check if file is in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals($truncatedFilename, substr($name, 0, strrpos($name, '.'))); } @@ -207,7 +199,7 @@ class StorageTest extends \Test\TestCase { // check if file is in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('subfile.txt', substr($name, 0, strrpos($name, '.'))); } @@ -234,12 +226,12 @@ class StorageTest extends \Test\TestCase { // check if folder is in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('folder', substr($name, 0, strrpos($name, '.'))); $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files/' . $name . '/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('subfile.txt', $name); } @@ -262,13 +254,13 @@ class StorageTest extends \Test\TestCase { // check if versions are in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/versions'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('test.txt.v', substr($name, 0, strlen('test.txt.v'))); // versions deleted $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); } /** @@ -279,7 +271,7 @@ class StorageTest extends \Test\TestCase { $this->userView->file_put_contents('folder/inside.txt', 'v1'); $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/folder/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $this->userView->rmdir('folder'); @@ -289,19 +281,19 @@ class StorageTest extends \Test\TestCase { // check if versions are in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/versions'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('folder.d', substr($name, 0, strlen('folder.d'))); // check if versions are in trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/versions/' . $name . '/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('inside.txt.v', substr($name, 0, strlen('inside.txt.v'))); // versions deleted $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/folder/'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); } /** @@ -314,12 +306,12 @@ class StorageTest extends \Test\TestCase { $this->userView->file_put_contents('share/test.txt', 'v2'); $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/share/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $recipientUser = $this->getUniqueId('recipient_'); Server::get(IUserManager::class)->createUser($recipientUser, $recipientUser); - $node = \OC::$server->getUserFolder($this->user)->get('share'); + $node = \OCP\Server::get(IRootFolder::class)->getUserFolder($this->user)->get('share'); $share = Server::get(\OCP\Share\IManager::class)->newShare(); $share->setNode($node) ->setShareType(IShare::TYPE_USER) @@ -341,18 +333,18 @@ class StorageTest extends \Test\TestCase { // check if versions are in trashbin for both users $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/versions'); - $this->assertEquals(1, count($results), 'Versions in owner\'s trashbin'); + $this->assertCount(1, $results, 'Versions in owner\'s trashbin'); $name = $results[0]->getName(); $this->assertEquals('test.txt.v', substr($name, 0, strlen('test.txt.v'))); $results = $this->rootView->getDirectoryContent($recipientUser . '/files_trashbin/versions'); - $this->assertEquals(1, count($results), 'Versions in recipient\'s trashbin'); + $this->assertCount(1, $results, 'Versions in recipient\'s trashbin'); $name = $results[0]->getName(); $this->assertEquals('test.txt.v', substr($name, 0, strlen('test.txt.v'))); // versions deleted $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/share/'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); } /** @@ -366,12 +358,11 @@ class StorageTest extends \Test\TestCase { $this->userView->file_put_contents('share/folder/test.txt', 'v2'); $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/share/folder/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $recipientUser = $this->getUniqueId('recipient_'); Server::get(IUserManager::class)->createUser($recipientUser, $recipientUser); - - $node = \OC::$server->getUserFolder($this->user)->get('share'); + $node = \OCP\Server::get(IRootFolder::class)->getUserFolder($this->user)->get('share'); $share = Server::get(\OCP\Share\IManager::class)->newShare(); $share->setNode($node) ->setShareType(IShare::TYPE_USER) @@ -393,31 +384,31 @@ class StorageTest extends \Test\TestCase { // check if versions are in trashbin for owner $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/versions'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('folder.d', substr($name, 0, strlen('folder.d'))); // check if file versions are in trashbin for owner $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/versions/' . $name . '/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('test.txt.v', substr($name, 0, strlen('test.txt.v'))); // check if versions are in trashbin for recipient $results = $this->rootView->getDirectoryContent($recipientUser . '/files_trashbin/versions'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('folder.d', substr($name, 0, strlen('folder.d'))); // check if file versions are in trashbin for recipient $results = $this->rootView->getDirectoryContent($recipientUser . '/files_trashbin/versions/' . $name . '/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); $name = $results[0]->getName(); $this->assertEquals('test.txt.v', substr($name, 0, strlen('test.txt.v'))); // versions deleted $results = $this->rootView->getDirectoryContent($recipientUser . '/files_versions/share/folder/'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); } /** @@ -433,10 +424,10 @@ class StorageTest extends \Test\TestCase { $this->userView->file_put_contents('test.txt', 'v1'); $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); // move to another storage $this->userView->rename('test.txt', 'substorage/test.txt'); @@ -448,15 +439,15 @@ class StorageTest extends \Test\TestCase { // versions were moved too $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/substorage'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); // check that nothing got trashed by the rename's unlink() call $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); // check that versions were moved and not trashed $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/versions/'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); } /** @@ -472,10 +463,10 @@ class StorageTest extends \Test\TestCase { $this->userView->file_put_contents('folder/inside.txt', 'v1'); $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/folder/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); // move to another storage $this->userView->rename('folder', 'substorage/folder'); @@ -487,15 +478,15 @@ class StorageTest extends \Test\TestCase { // versions were moved too $results = $this->rootView->getDirectoryContent($this->user . '/files_versions/substorage/folder/'); - $this->assertEquals(1, count($results)); + $this->assertCount(1, $results); // check that nothing got trashed by the rename's unlink() call $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); // check that versions were moved and not trashed $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/versions/'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); } /** @@ -503,11 +494,11 @@ class StorageTest extends \Test\TestCase { */ public function testSingleStorageDeleteFileFail(): void { /** - * @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage + * @var Temporary&MockObject $storage */ - $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $storage = $this->getMockBuilder(\OC\Files\Storage\Temporary::class) ->setConstructorArgs([[]]) - ->setMethods(['rename', 'unlink', 'moveFromStorage']) + ->onlyMethods(['rename', 'unlink', 'moveFromStorage']) ->getMock(); $storage->expects($this->any()) @@ -532,7 +523,7 @@ class StorageTest extends \Test\TestCase { // file should not be in the trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files/'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); } /** @@ -540,11 +531,11 @@ class StorageTest extends \Test\TestCase { */ public function testSingleStorageDeleteFolderFail(): void { /** - * @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage + * @var Temporary&MockObject $storage */ - $storage = $this->getMockBuilder('\OC\Files\Storage\Temporary') + $storage = $this->getMockBuilder(\OC\Files\Storage\Temporary::class) ->setConstructorArgs([[]]) - ->setMethods(['rename', 'unlink', 'rmdir']) + ->onlyMethods(['rename', 'unlink', 'rmdir']) ->getMock(); $storage->expects($this->any()) @@ -566,18 +557,17 @@ class StorageTest extends \Test\TestCase { // file should not be in the trashbin $results = $this->rootView->getDirectoryContent($this->user . '/files_trashbin/files/'); - $this->assertEquals(0, count($results)); + $this->assertCount(0, $results); } /** * @dataProvider dataTestShouldMoveToTrash */ - public function testShouldMoveToTrash($mountPoint, $path, $userExists, $appDisablesTrash, $expected): void { + public function testShouldMoveToTrash(string $mountPoint, string $path, bool $userExists, bool $appDisablesTrash, bool $expected): void { $fileID = 1; $cache = $this->createMock(ICache::class); $cache->expects($this->any())->method('getId')->willReturn($fileID); - $tmpStorage = $this->getMockBuilder('\OC\Files\Storage\Temporary') - ->disableOriginalConstructor()->getMock($cache); + $tmpStorage = $this->createMock(\OC\Files\Storage\Temporary::class); $tmpStorage->expects($this->any())->method('getCache')->willReturn($cache); $userManager = $this->getMockBuilder(IUserManager::class) ->disableOriginalConstructor()->getMock(); @@ -606,7 +596,9 @@ class StorageTest extends \Test\TestCase { $eventDispatcher, $rootFolder ] - )->setMethods(['createMoveToTrashEvent'])->getMock(); + ) + ->onlyMethods(['createMoveToTrashEvent']) + ->getMock(); $storage->expects($this->any())->method('createMoveToTrashEvent')->with($node) ->willReturn($event); @@ -616,7 +608,7 @@ class StorageTest extends \Test\TestCase { ); } - public function dataTestShouldMoveToTrash() { + public static function dataTestShouldMoveToTrash(): array { return [ ['/schiesbn/', '/files/test.txt', true, false, true], ['/schiesbn/', '/files/test.txt', false, false, false], diff --git a/apps/files_trashbin/tests/TrashbinTest.php b/apps/files_trashbin/tests/TrashbinTest.php index 3d2ceee0dcd..d8486ccbdc2 100644 --- a/apps/files_trashbin/tests/TrashbinTest.php +++ b/apps/files_trashbin/tests/TrashbinTest.php @@ -1,4 +1,6 @@ <?php + +declare(strict_types=1); /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -22,6 +24,7 @@ use OCP\App\IAppManager; use OCP\AppFramework\Utility\ITimeFactory; use OCP\Constants; use OCP\Files\FileInfo; +use OCP\Files\IRootFolder; use OCP\IConfig; use OCP\IDBConnection; use OCP\IUserManager; @@ -41,16 +44,8 @@ class TrashbinTest extends \Test\TestCase { private $trashRoot2; private static $rememberRetentionObligation; - - /** - * @var bool - */ - private static $trashBinStatus; - - /** - * @var View - */ - private $rootView; + private static bool $trashBinStatus; + private View $rootView; public static function setUpBeforeClass(): void { parent::setUpBeforeClass(); @@ -74,7 +69,7 @@ class TrashbinTest extends \Test\TestCase { $config = Server::get(IConfig::class); //configure trashbin - self::$rememberRetentionObligation = $config->getSystemValue('trashbin_retention_obligation', Expiration::DEFAULT_RETENTION_OBLIGATION); + self::$rememberRetentionObligation = (string)$config->getSystemValue('trashbin_retention_obligation', Expiration::DEFAULT_RETENTION_OBLIGATION); /** @var Expiration $expiration */ $expiration = Server::get(Expiration::class); $expiration->setRetentionObligation('auto, 2'); @@ -190,14 +185,14 @@ class TrashbinTest extends \Test\TestCase { // only file2.txt should be left $remainingFiles = array_slice($manipulatedList, $count); - $this->assertSame(1, count($remainingFiles)); + $this->assertCount(1, $remainingFiles); $remainingFile = reset($remainingFiles); // TODO: failing test #$this->assertSame('file2.txt', $remainingFile['name']); // check that file1.txt and file3.txt was really deleted $newTrashContent = Helper::getTrashFiles('/', self::TEST_TRASHBIN_USER1); - $this->assertSame(1, count($newTrashContent)); + $this->assertCount(1, $newTrashContent); $element = reset($newTrashContent); // TODO: failing test #$this->assertSame('file2.txt', $element['name']); @@ -285,8 +280,8 @@ class TrashbinTest extends \Test\TestCase { * @param FileInfo[] $result * @param string[] $expected */ - private function verifyArray($result, $expected) { - $this->assertSame(count($expected), count($result)); + private function verifyArray(array $result, array $expected): void { + $this->assertCount(count($expected), $result); foreach ($expected as $expectedFile) { $found = false; foreach ($result as $fileInTrash) { @@ -304,10 +299,8 @@ class TrashbinTest extends \Test\TestCase { /** * @param FileInfo[] $files - * @param string $trashRoot - * @param integer $expireDate */ - private function manipulateDeleteTime($files, $trashRoot, $expireDate) { + private function manipulateDeleteTime(array $files, string $trashRoot, int $expireDate): array { $counter = 0; foreach ($files as &$file) { // modify every second file @@ -361,7 +354,7 @@ class TrashbinTest extends \Test\TestCase { * Test restoring a file */ public function testRestoreFileInRoot(): void { - $userFolder = \OC::$server->getUserFolder(); + $userFolder = \OCP\Server::get(IRootFolder::class)->getUserFolder(self::TEST_TRASHBIN_USER1); $file = $userFolder->newFile('file1.txt'); $file->putContent('foo'); @@ -393,7 +386,7 @@ class TrashbinTest extends \Test\TestCase { * Test restoring a file in subfolder */ public function testRestoreFileInSubfolder(): void { - $userFolder = \OC::$server->getUserFolder(); + $userFolder = \OCP\Server::get(IRootFolder::class)->getUserFolder(self::TEST_TRASHBIN_USER1); $folder = $userFolder->newFolder('folder'); $file = $folder->newFile('file1.txt'); $file->putContent('foo'); @@ -426,7 +419,7 @@ class TrashbinTest extends \Test\TestCase { * Test restoring a folder */ public function testRestoreFolder(): void { - $userFolder = \OC::$server->getUserFolder(); + $userFolder = \OCP\Server::get(IRootFolder::class)->getUserFolder(self::TEST_TRASHBIN_USER1); $folder = $userFolder->newFolder('folder'); $file = $folder->newFile('file1.txt'); $file->putContent('foo'); @@ -459,7 +452,7 @@ class TrashbinTest extends \Test\TestCase { * Test restoring a file from inside a trashed folder */ public function testRestoreFileFromTrashedSubfolder(): void { - $userFolder = \OC::$server->getUserFolder(); + $userFolder = \OCP\Server::get(IRootFolder::class)->getUserFolder(self::TEST_TRASHBIN_USER1); $folder = $userFolder->newFolder('folder'); $file = $folder->newFile('file1.txt'); $file->putContent('foo'); @@ -493,7 +486,7 @@ class TrashbinTest extends \Test\TestCase { * The file should then land in the root. */ public function testRestoreFileWithMissingSourceFolder(): void { - $userFolder = \OC::$server->getUserFolder(); + $userFolder = \OCP\Server::get(IRootFolder::class)->getUserFolder(self::TEST_TRASHBIN_USER1); $folder = $userFolder->newFolder('folder'); $file = $folder->newFile('file1.txt'); $file->putContent('foo'); @@ -530,7 +523,7 @@ class TrashbinTest extends \Test\TestCase { * with the same name in the root folder */ public function testRestoreFileDoesNotOverwriteExistingInRoot(): void { - $userFolder = \OC::$server->getUserFolder(); + $userFolder = \OCP\Server::get(IRootFolder::class)->getUserFolder(self::TEST_TRASHBIN_USER1); $file = $userFolder->newFile('file1.txt'); $file->putContent('foo'); @@ -570,7 +563,7 @@ class TrashbinTest extends \Test\TestCase { * with the same name in the source folder */ public function testRestoreFileDoesNotOverwriteExistingInSubfolder(): void { - $userFolder = \OC::$server->getUserFolder(); + $userFolder = \OCP\Server::get(IRootFolder::class)->getUserFolder(self::TEST_TRASHBIN_USER1); $folder = $userFolder->newFolder('folder'); $file = $folder->newFile('file1.txt'); $file->putContent('foo'); @@ -624,7 +617,7 @@ class TrashbinTest extends \Test\TestCase { * the file to root instead */ public function testRestoreFileIntoReadOnlySourceFolder(): void { - $userFolder = \OC::$server->getUserFolder(); + $userFolder = \OCP\Server::get(IRootFolder::class)->getUserFolder(self::TEST_TRASHBIN_USER1); $folder = $userFolder->newFolder('folder'); $file = $folder->newFile('file1.txt'); $file->putContent('foo'); @@ -680,7 +673,7 @@ class TrashbinTest extends \Test\TestCase { Filesystem::tearDown(); \OC_User::setUserId($user); \OC_Util::setupFS($user); - \OC::$server->getUserFolder($user); + \OCP\Server::get(IRootFolder::class)->getUserFolder($user); } } |