diff options
232 files changed, 1669 insertions, 2017 deletions
diff --git a/apps/comments/tests/Unit/Activity/ListenerTest.php b/apps/comments/tests/Unit/Activity/ListenerTest.php index 70dec741978..675a28a16b1 100644 --- a/apps/comments/tests/Unit/Activity/ListenerTest.php +++ b/apps/comments/tests/Unit/Activity/ListenerTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -20,30 +23,17 @@ use OCP\Files\Node; use OCP\IUser; use OCP\IUserSession; use OCP\Share\IShareHelper; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ListenerTest extends TestCase { - - /** @var Listener */ - protected $listener; - - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $activityManager; - - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - protected $session; - - /** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $appManager; - - /** @var IMountProviderCollection|\PHPUnit\Framework\MockObject\MockObject */ - protected $mountProviderCollection; - - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ - protected $rootFolder; - - /** @var IShareHelper|\PHPUnit\Framework\MockObject\MockObject */ - protected $shareHelper; + protected IManager&MockObject $activityManager; + protected IUserSession&MockObject $session; + protected IAppManager&MockObject $appManager; + protected IMountProviderCollection&MockObject $mountProviderCollection; + protected IRootFolder&MockObject $rootFolder; + protected IShareHelper&MockObject $shareHelper; + protected Listener $listener; protected function setUp(): void { parent::setUp(); @@ -76,7 +66,7 @@ class ListenerTest extends TestCase { ->method('getObjectType') ->willReturn('files'); - /** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ + /** @var CommentsEvent|MockObject $event */ $event = $this->createMock(CommentsEvent::class); $event->expects($this->any()) ->method('getComment') @@ -85,13 +75,13 @@ class ListenerTest extends TestCase { ->method('getEvent') ->willReturn(CommentsEvent::EVENT_ADD); - /** @var IUser|\PHPUnit\Framework\MockObject\MockObject $ownerUser */ + /** @var IUser|MockObject $ownerUser */ $ownerUser = $this->createMock(IUser::class); $ownerUser->expects($this->any()) ->method('getUID') ->willReturn('937393'); - /** @var \PHPUnit\Framework\MockObject\MockObject $mount */ + /** @var MockObject $mount */ $mount = $this->createMock(ICachedMountFileInfo::class); $mount->expects($this->any()) ->method('getUser') @@ -133,7 +123,7 @@ class ListenerTest extends TestCase { ->method('getUser') ->willReturn($ownerUser); - /** @var \PHPUnit\Framework\MockObject\MockObject $activity */ + /** @var MockObject $activity */ $activity = $this->createMock(IEvent::class); $activity->expects($this->exactly(count($al['users']))) ->method('setAffectedUser'); diff --git a/apps/comments/tests/Unit/AppInfo/ApplicationTest.php b/apps/comments/tests/Unit/AppInfo/ApplicationTest.php index abd5b188d44..119db5333b5 100644 --- a/apps/comments/tests/Unit/AppInfo/ApplicationTest.php +++ b/apps/comments/tests/Unit/AppInfo/ApplicationTest.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -7,7 +9,12 @@ */ namespace OCA\Comments\Tests\Unit\AppInfo; +use OCA\Comments\Activity\Filter; +use OCA\Comments\Activity\Listener; +use OCA\Comments\Activity\Provider; +use OCA\Comments\Activity\Setting; use OCA\Comments\AppInfo\Application; +use OCA\Comments\Controller\NotificationsController; use OCA\Comments\Notification\Notifier; use OCP\IUserManager; use OCP\IUserSession; @@ -38,12 +45,12 @@ class ApplicationTest extends TestCase { $c = $app->getContainer(); $services = [ - 'OCA\Comments\Controller\NotificationsController', - 'OCA\Comments\Activity\Filter', - 'OCA\Comments\Activity\Listener', - 'OCA\Comments\Activity\Provider', - 'OCA\Comments\Activity\Setting', - 'OCA\Comments\Notification\Listener', + NotificationsController::class, + Filter::class, + Listener::class, + Provider::class, + Setting::class, + \OCA\Comments\Notification\Listener::class, Notifier::class, ]; diff --git a/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php b/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php index c0de0016c31..525bf5e67c8 100644 --- a/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php +++ b/apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php @@ -8,13 +8,12 @@ namespace OCA\Comments\Tests\Unit\Collaboration; use OCA\Comments\Collaboration\CommentersSorter; use OCP\Comments\IComment; use OCP\Comments\ICommentsManager; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class CommentersSorterTest extends TestCase { - /** @var ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $commentsManager; - /** @var CommentersSorter */ - protected $sorter; + protected ICommentsManager&MockObject $commentsManager; + protected CommentersSorter $sorter; protected function setUp(): void { parent::setUp(); @@ -55,7 +54,7 @@ class CommentersSorterTest extends TestCase { $this->assertEquals($data['expected'], $workArray); } - public function sortDataProvider() { + public static function sortDataProvider(): array { return [[ [ #1 – sort properly and otherwise keep existing order diff --git a/apps/comments/tests/Unit/Controller/NotificationsTest.php b/apps/comments/tests/Unit/Controller/NotificationsTest.php index ccd808895c8..59d0b9ccb00 100644 --- a/apps/comments/tests/Unit/Controller/NotificationsTest.php +++ b/apps/comments/tests/Unit/Controller/NotificationsTest.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 ownCloud, Inc. @@ -22,26 +24,16 @@ use OCP\IUser; use OCP\IUserSession; use OCP\Notification\IManager; use OCP\Notification\INotification; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class NotificationsTest extends TestCase { - /** @var NotificationsController */ - protected $notificationsController; - - /** @var ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $commentsManager; - - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ - protected $rootFolder; - - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - protected $session; - - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $notificationManager; - - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ - protected $urlGenerator; + protected ICommentsManager&MockObject $commentsManager; + protected IRootFolder&MockObject $rootFolder; + protected IUserSession&MockObject $session; + protected IManager&MockObject $notificationManager; + protected IURLGenerator&MockObject $urlGenerator; + protected NotificationsController $notificationsController; protected function setUp(): void { parent::setUp(); @@ -81,10 +73,6 @@ class NotificationsTest extends TestCase { $this->urlGenerator->expects($this->exactly(2)) ->method('linkToRoute') - ->withConsecutive( - ['comments.Notifications.view', ['id' => '42']], - ['core.login.showLoginForm', ['redirect_url' => 'link-to-comment']] - ) ->willReturnMap([ ['comments.Notifications.view', ['id' => '42'], 'link-to-comment'], ['core.login.showLoginForm', ['redirect_url' => 'link-to-comment'], 'link-to-login'], diff --git a/apps/comments/tests/Unit/EventHandlerTest.php b/apps/comments/tests/Unit/EventHandlerTest.php index 83ce1af57da..df2876e20a3 100644 --- a/apps/comments/tests/Unit/EventHandlerTest.php +++ b/apps/comments/tests/Unit/EventHandlerTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -10,43 +13,32 @@ use OCA\Comments\Listener\CommentsEventListener; use OCA\Comments\Notification\Listener as NotificationListener; use OCP\Comments\CommentsEvent; use OCP\Comments\IComment; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class EventHandlerTest extends TestCase { - /** @var CommentsEventListener */ - protected $eventHandler; - - /** @var ActivityListener|\PHPUnit\Framework\MockObject\MockObject */ - protected $activityListener; - - /** @var NotificationListener|\PHPUnit\Framework\MockObject\MockObject */ - protected $notificationListener; + protected ActivityListener&MockObject $activityListener; + protected NotificationListener&MockObject $notificationListener; + protected CommentsEventListener $eventHandler; protected function setUp(): void { parent::setUp(); - $this->activityListener = $this->getMockBuilder(ActivityListener::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->notificationListener = $this->getMockBuilder(NotificationListener::class) - ->disableOriginalConstructor() - ->getMock(); + $this->activityListener = $this->createMock(ActivityListener::class); + $this->notificationListener = $this->createMock(NotificationListener::class); $this->eventHandler = new CommentsEventListener($this->activityListener, $this->notificationListener); } public function testNotFiles(): void { - /** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ - $comment = $this->getMockBuilder(IComment::class)->getMock(); + /** @var IComment|MockObject $comment */ + $comment = $this->createMock(IComment::class); $comment->expects($this->once()) ->method('getObjectType') ->willReturn('smiles'); - /** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ - $event = $this->getMockBuilder(CommentsEvent::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var CommentsEvent|MockObject $event */ + $event = $this->createMock(CommentsEvent::class); $event->expects($this->once()) ->method('getComment') ->willReturn($comment); @@ -56,7 +48,7 @@ class EventHandlerTest extends TestCase { $this->eventHandler->handle($event); } - public function handledProvider() { + public static function handledProvider(): array { return [ [CommentsEvent::EVENT_DELETE], [CommentsEvent::EVENT_UPDATE], @@ -67,19 +59,16 @@ class EventHandlerTest extends TestCase { /** * @dataProvider handledProvider - * @param string $eventType */ - public function testHandled($eventType): void { - /** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ - $comment = $this->getMockBuilder(IComment::class)->getMock(); + public function testHandled(string $eventType): void { + /** @var IComment|MockObject $comment */ + $comment = $this->createMock(IComment::class); $comment->expects($this->once()) ->method('getObjectType') ->willReturn('files'); - /** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ - $event = $this->getMockBuilder(CommentsEvent::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var CommentsEvent|MockObject $event */ + $event = $this->createMock(CommentsEvent::class); $event->expects($this->atLeastOnce()) ->method('getComment') ->willReturn($comment); diff --git a/apps/comments/tests/Unit/Notification/ListenerTest.php b/apps/comments/tests/Unit/Notification/ListenerTest.php index a9175b7e203..ae5a3c40bc6 100644 --- a/apps/comments/tests/Unit/Notification/ListenerTest.php +++ b/apps/comments/tests/Unit/Notification/ListenerTest.php @@ -14,25 +14,19 @@ use OCP\IURLGenerator; use OCP\IUserManager; use OCP\Notification\IManager; use OCP\Notification\INotification; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ListenerTest extends TestCase { - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $notificationManager; - - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $userManager; - - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ - protected $urlGenerator; - - /** @var Listener */ - protected $listener; + protected IManager&MockObject $notificationManager; + protected IUserManager&MockObject $userManager; + protected IURLGenerator&MockObject $urlGenerator; + protected Listener $listener; protected function setUp(): void { parent::setUp(); - $this->notificationManager = $this->createMock(\OCP\Notification\IManager::class); + $this->notificationManager = $this->createMock(IManager::class); $this->userManager = $this->createMock(IUserManager::class); $this->listener = new Listener( @@ -41,7 +35,7 @@ class ListenerTest extends TestCase { ); } - public function eventProvider() { + public static function eventProvider(): array { return [ [CommentsEvent::EVENT_ADD, 'notify'], [CommentsEvent::EVENT_UPDATE, 'notify'], @@ -56,8 +50,8 @@ class ListenerTest extends TestCase { * @param string $notificationMethod */ public function testEvaluate($eventType, $notificationMethod): void { - /** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ - $comment = $this->getMockBuilder(IComment::class)->getMock(); + /** @var IComment|MockObject $comment */ + $comment = $this->createMock(IComment::class); $comment->expects($this->any()) ->method('getObjectType') ->willReturn('files'); @@ -78,10 +72,8 @@ class ListenerTest extends TestCase { ->method('getId') ->willReturn('1234'); - /** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ - $event = $this->getMockBuilder(CommentsEvent::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var CommentsEvent|MockObject $event */ + $event = $this->createMock(CommentsEvent::class); $event->expects($this->once()) ->method('getComment') ->willReturn($comment); @@ -89,8 +81,8 @@ class ListenerTest extends TestCase { ->method(('getEvent')) ->willReturn($eventType); - /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ - $notification = $this->getMockBuilder(INotification::class)->getMock(); + /** @var INotification|MockObject $notification */ + $notification = $this->createMock(INotification::class); $notification->expects($this->any()) ->method($this->anything()) ->willReturn($notification); @@ -106,26 +98,24 @@ class ListenerTest extends TestCase { $this->userManager->expects($this->exactly(6)) ->method('userExists') - ->withConsecutive( - ['foobar'], - ['barfoo'], - ['foo@bar.com'], - ['bar@foo.org@foobar.io'], - ['23452-4333-54353-2342'], - ['yolo'] - ) - ->willReturn(true); + ->willReturnMap([ + ['foobar', true], + ['barfoo', true], + ['foo@bar.com', true], + ['bar@foo.org@foobar.io', true], + ['23452-4333-54353-2342', true], + ['yolo', true] + ]); $this->listener->evaluate($event); } /** * @dataProvider eventProvider - * @param string $eventType */ - public function testEvaluateNoMentions($eventType): void { - /** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ - $comment = $this->getMockBuilder(IComment::class)->getMock(); + public function testEvaluateNoMentions(string $eventType): void { + /** @var IComment|MockObject $comment */ + $comment = $this->createMock(IComment::class); $comment->expects($this->any()) ->method('getObjectType') ->willReturn('files'); @@ -136,10 +126,8 @@ class ListenerTest extends TestCase { ->method('getMentions') ->willReturn([]); - /** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ - $event = $this->getMockBuilder(CommentsEvent::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var CommentsEvent|MockObject $event */ + $event = $this->createMock(CommentsEvent::class); $event->expects($this->once()) ->method('getComment') ->willReturn($comment); @@ -161,8 +149,8 @@ class ListenerTest extends TestCase { } public function testEvaluateUserDoesNotExist(): void { - /** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ - $comment = $this->getMockBuilder(IComment::class)->getMock(); + /** @var IComment|MockObject $comment */ + $comment = $this->createMock(IComment::class); $comment->expects($this->any()) ->method('getObjectType') ->willReturn('files'); @@ -176,10 +164,8 @@ class ListenerTest extends TestCase { ->method('getId') ->willReturn('1234'); - /** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ - $event = $this->getMockBuilder(CommentsEvent::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var CommentsEvent|MockObject $event */ + $event = $this->createMock(CommentsEvent::class); $event->expects($this->once()) ->method('getComment') ->willReturn($comment); @@ -187,8 +173,8 @@ class ListenerTest extends TestCase { ->method(('getEvent')) ->willReturn(CommentsEvent::EVENT_ADD); - /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ - $notification = $this->getMockBuilder(INotification::class)->getMock(); + /** @var INotification|MockObject $notification */ + $notification = $this->createMock(INotification::class); $notification->expects($this->any()) ->method($this->anything()) ->willReturn($notification); @@ -203,9 +189,7 @@ class ListenerTest extends TestCase { $this->userManager->expects($this->once()) ->method('userExists') - ->withConsecutive( - ['foobar'] - ) + ->with('foobar') ->willReturn(false); $this->listener->evaluate($event); diff --git a/apps/comments/tests/Unit/Notification/NotifierTest.php b/apps/comments/tests/Unit/Notification/NotifierTest.php index 87b87e646af..37cad0b43df 100644 --- a/apps/comments/tests/Unit/Notification/NotifierTest.php +++ b/apps/comments/tests/Unit/Notification/NotifierTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -23,26 +26,16 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class NotifierTest extends TestCase { - /** @var Notifier */ - protected $notifier; - /** @var IFactory|MockObject */ - protected $l10nFactory; - /** @var IL10N|MockObject */ - protected $l; - /** @var IRootFolder|MockObject */ - protected $folder; - /** @var ICommentsManager|MockObject */ - protected $commentsManager; - /** @var IURLGenerator|MockObject */ - protected $url; - /** @var IUserManager|MockObject */ - protected $userManager; - /** @var INotification|MockObject */ - protected $notification; - /** @var IComment|MockObject */ - protected $comment; - /** @var string */ - protected $lc = 'tlh_KX'; + protected IFactory&MockObject $l10nFactory; + protected IL10N&MockObject $l; + protected IRootFolder&MockObject $folder; + protected ICommentsManager&MockObject $commentsManager; + protected IURLGenerator&MockObject $url; + protected IUserManager&MockObject $userManager; + protected INotification&MockObject $notification; + protected IComment&MockObject $comment; + protected Notifier $notifier; + protected string $lc = 'tlh_KX'; protected function setUp(): void { parent::setUp(); @@ -75,9 +68,8 @@ class NotifierTest extends TestCase { public function testPrepareSuccess(): void { $fileName = 'Gre\'thor.odp'; $displayName = 'Huraga'; - $message = '@Huraga mentioned you in a comment on "Gre\'thor.odp"'; - /** @var Node|MockObject $node */ + /** @var Node&MockObject $node */ $node = $this->createMock(Node::class); $node ->expects($this->atLeastOnce()) @@ -192,7 +184,6 @@ class NotifierTest extends TestCase { public function testPrepareSuccessDeletedUser(): void { $fileName = 'Gre\'thor.odp'; - $message = 'You were mentioned on "Gre\'thor.odp", in a comment by an account that has since been deleted'; /** @var Node|MockObject $node */ $node = $this->createMock(Node::class); diff --git a/apps/contactsinteraction/tests/Db/RecentContactMapperTest.php b/apps/contactsinteraction/tests/Db/RecentContactMapperTest.php index 89e192d9da7..f5df27820d7 100644 --- a/apps/contactsinteraction/tests/Db/RecentContactMapperTest.php +++ b/apps/contactsinteraction/tests/Db/RecentContactMapperTest.php @@ -21,12 +21,8 @@ use Test\TestCase; * @group DB */ class RecentContactMapperTest extends TestCase { - - /** @var RecentContactMapper */ - private $recentContactMapper; - - /** @var ITimeFactory */ - private $time; + private RecentContactMapper $recentContactMapper; + private ITimeFactory $time; protected function setUp(): void { parent::setUp(); diff --git a/apps/dashboard/tests/DashboardServiceTest.php b/apps/dashboard/tests/DashboardServiceTest.php index c603b88e7ff..ebcd06cdf03 100644 --- a/apps/dashboard/tests/DashboardServiceTest.php +++ b/apps/dashboard/tests/DashboardServiceTest.php @@ -40,7 +40,7 @@ class DashboardServiceTest extends TestCase { ); } - public function testGetBirthdate() { + public function testGetBirthdate(): void { $user = $this->createMock(IUser::class); $this->userManager->method('get') ->willReturn($user); @@ -61,7 +61,7 @@ class DashboardServiceTest extends TestCase { $this->assertEquals('2024-12-10T00:00:00.000Z', $birthdate); } - public function testGetBirthdatePropertyDoesNotExist() { + public function testGetBirthdatePropertyDoesNotExist(): void { $user = $this->createMock(IUser::class); $this->userManager->method('get') ->willReturn($user); @@ -75,7 +75,7 @@ class DashboardServiceTest extends TestCase { $this->assertEquals('', $birthdate); } - public function testGetBirthdateUserNotFound() { + public function testGetBirthdateUserNotFound(): void { $this->userManager->method('get') ->willReturn(null); @@ -84,7 +84,7 @@ class DashboardServiceTest extends TestCase { $this->assertEquals('', $birthdate); } - public function testGetBirthdateNoUserId() { + public function testGetBirthdateNoUserId(): void { $service = new DashboardService( $this->config, null, diff --git a/apps/files_external/tests/Storage/FtpTest.php b/apps/files_external/tests/Storage/FtpTest.php index c6a1d8f77ba..81b92e0fae9 100644 --- a/apps/files_external/tests/Storage/FtpTest.php +++ b/apps/files_external/tests/Storage/FtpTest.php @@ -45,7 +45,7 @@ class FtpTest extends \Test\Files\Storage\Storage { /** * ftp has no proper way to handle spaces at the end of file names */ - public function directoryProvider() { + public static function directoryProvider(): array { return array_filter(parent::directoryProvider(), function ($item) { return substr($item[0], -1) !== ' '; }); diff --git a/apps/files_external/tests/Storage/SmbTest.php b/apps/files_external/tests/Storage/SmbTest.php index d5a83905112..51737d05dc6 100644 --- a/apps/files_external/tests/Storage/SmbTest.php +++ b/apps/files_external/tests/Storage/SmbTest.php @@ -49,7 +49,7 @@ class SmbTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - public function directoryProvider() { + public static function directoryProvider(): array { // doesn't support leading/trailing spaces return [['folder']]; } diff --git a/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php b/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php index 6b668f53119..19cab51969b 100644 --- a/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php +++ b/apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php @@ -19,15 +19,9 @@ use Test\TestCase; * @group DB */ class BackupCodeMapperTest extends TestCase { - - /** @var IDBConnection */ - private $db; - - /** @var BackupCodeMapper */ - private $mapper; - - /** @var string */ - private $testUID = 'test123456'; + private IDBConnection $db; + private BackupCodeMapper $mapper; + private string $testUID = 'test123456'; private function resetDB() { $qb = $this->db->getQueryBuilder(); diff --git a/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php b/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php index b556828b924..38d3bd55d11 100644 --- a/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php +++ b/apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php @@ -13,21 +13,16 @@ use OCP\IUser; use OCP\Notification\IManager; use OCP\Notification\INotification; use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; /** * @group DB */ class BackupCodeStorageTest extends TestCase { - - /** @var BackupCodeStorage */ - private $storage; - - /** @var string */ - private $testUID = 'test123456789'; - - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $notificationManager; + private IManager&MockObject $notificationManager; + private string $testUID = 'test123456789'; + private BackupCodeStorage $storage; protected function setUp(): void { parent::setUp(); diff --git a/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php b/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php index e41db8b0a32..a3c6d15902a 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php @@ -15,21 +15,14 @@ use OCP\Activity\IManager; use OCP\IL10N; use OCP\IURLGenerator; use OCP\L10N\IFactory; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ProviderTest extends TestCase { - - /** @var IFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $l10n; - - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; - - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $activityManager; - - /** @var Provider */ - private $provider; + private IFactory&MockObject $l10n; + private IURLGenerator&MockObject $urlGenerator; + private IManager&MockObject $activityManager; + private Provider $provider; protected function setUp(): void { parent::setUp(); @@ -52,7 +45,7 @@ class ProviderTest extends TestCase { $this->provider->parse($lang, $event); } - public function subjectData() { + public static function subjectData(): array { return [ ['codes_generated'], ]; @@ -61,7 +54,7 @@ class ProviderTest extends TestCase { /** * @dataProvider subjectData */ - public function testParse($subject): void { + public function testParse(string $subject): void { $lang = 'ru'; $event = $this->createMock(IEvent::class); $l = $this->createMock(IL10N::class); diff --git a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php index 5b8281e278e..87bc65e4309 100644 --- a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php @@ -20,24 +20,12 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class CheckBackupCodeTest extends TestCase { - - /** @var IUserManager|MockObject */ - private $userManager; - - /** @var IJobList|MockObject */ - private $jobList; - - /** @var IRegistry|MockObject */ - private $registry; - - /** @var Manager|MockObject */ - private $manager; - - /** @var IUser|MockObject */ - private $user; - - /** @var CheckBackupCodes */ - private $checkBackupCodes; + private IUserManager&MockObject $userManager; + private IJobList&MockObject $jobList; + private IRegistry&MockObject $registry; + private Manager&MockObject $manager; + private IUser&MockObject $user; + private CheckBackupCodes $checkBackupCodes; protected function setUp(): void { parent::setUp(); diff --git a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php index 31b7d514246..16a0e8012f7 100644 --- a/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php @@ -17,27 +17,16 @@ use OCP\IUserManager; use OCP\Notification\IManager; use OCP\Notification\INotification; use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RememberBackupCodesJobTest extends TestCase { - - /** @var IRegistry|\PHPUnit\Framework\MockObject\MockObject */ - private $registry; - - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $time; - - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $notificationManager; - - /** @var IJobList|\PHPUnit\Framework\MockObject\MockObject */ - private $jobList; - - /** @var RememberBackupCodesJob */ - private $job; + private IRegistry&MockObject $registry; + private IUserManager&MockObject $userManager; + private ITimeFactory&MockObject $time; + private IManager&MockObject $notificationManager; + private IJobList&MockObject $jobList; + private RememberBackupCodesJob $job; protected function setUp(): void { parent::setUp(); diff --git a/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php b/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php index 85b23e88fee..02c42b65148 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php @@ -14,36 +14,27 @@ use OCP\AppFramework\Http\JSONResponse; use OCP\IRequest; use OCP\IUser; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class SettingsControllerTest extends TestCase { - - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $request; - - /** @var BackupCodeStorage|\PHPUnit\Framework\MockObject\MockObject */ - private $storage; - - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; - - /** @var SettingsController */ - private $controller; + private IRequest&MockObject $request; + private BackupCodeStorage&MockObject $storage; + private IUserSession&MockObject $userSession; + private SettingsController $controller; protected function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder(IRequest::class)->getMock(); - $this->storage = $this->getMockBuilder(BackupCodeStorage::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class)->getMock(); + $this->request = $this->createMock(IRequest::class); + $this->storage = $this->createMock(BackupCodeStorage::class); + $this->userSession = $this->createMock(IUserSession::class); $this->controller = new SettingsController('twofactor_backupcodes', $this->request, $this->storage, $this->userSession); } public function testCreateCodes(): void { - $user = $this->getMockBuilder(IUser::class)->getMock(); + $user = $this->createMock(IUser::class); $codes = ['a', 'b']; $this->userSession->expects($this->once()) diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php index 72ca91ed8eb..bd944dc2396 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php @@ -19,14 +19,9 @@ use Psr\Log\LoggerInterface; use Test\TestCase; class ActivityPublisherTest extends TestCase { - /** @var IManager|MockObject */ - private $activityManager; - - /** @var LoggerInterface */ - private $logger; - - /** @var ActivityPublisher */ - private $listener; + private IManager&MockObject $activityManager; + private LoggerInterface&MockObject $logger; + private ActivityPublisher $listener; protected function setUp(): void { parent::setUp(); diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php index bbefbfbece1..fc80344ac57 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php @@ -15,15 +15,12 @@ use OCP\IUser; use OCP\Notification\IManager; use OCP\Notification\INotification; use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ClearNotificationsTest extends TestCase { - - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $notificationManager; - - /** @var ClearNotifications */ - private $listener; + private IManager&MockObject $notificationManager; + private ClearNotifications $listener; protected function setUp(): void { parent::setUp(); diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php index 7f7b5dc3011..ea4f530cab4 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php @@ -15,11 +15,12 @@ use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserUnregistered; use OCP\BackgroundJob\IJobList; use OCP\EventDispatcher\Event; use OCP\IUser; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ProviderDisabledTest extends TestCase { - private IRegistry $registy; - private IJobList $jobList; + private IRegistry&MockObject $registy; + private IJobList&MockObject $jobList; private ProviderDisabled $listener; protected function setUp(): void { diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php index 145944fccca..50aac6139c0 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php @@ -15,11 +15,12 @@ use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserRegistered; use OCP\BackgroundJob\IJobList; use OCP\EventDispatcher\Event; use OCP\IUser; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ProviderEnabledTest extends TestCase { - private IRegistry $registy; - private IJobList $jobList; + private IRegistry&MockObject $registy; + private IJobList&MockObject $jobList; private ProviderEnabled $listener; protected function setUp(): void { diff --git a/apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php b/apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php index 4f724f888d7..86d890f0d5e 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php @@ -14,18 +14,13 @@ use OCA\TwoFactorBackupCodes\Provider\BackupCodesProvider; use OCP\Authentication\TwoFactorAuth\IRegistry; use OCP\EventDispatcher\Event; use OCP\IUser; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RegistryUpdaterTest extends TestCase { - - /** @var IRegistry */ - private $registry; - - /** @var BackupCodesProvider */ - private $provider; - - /** @var RegistryUpdater */ - private $listener; + private IRegistry&MockObject $registry; + private BackupCodesProvider&MockObject $provider; + private RegistryUpdater $listener; protected function setUp(): void { parent::setUp(); diff --git a/apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php b/apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php index bb959ff08b3..c68ab185116 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php @@ -11,15 +11,12 @@ namespace OCA\TwoFactorBackupCodes\Tests\Unit\Migration; use OCA\TwoFactorBackupCodes\Migration\CheckBackupCodes; use OCP\BackgroundJob\IJobList; use OCP\Migration\IOutput; +use PHPunit\Framework\MockObject\MockObject; use Test\TestCase; class CheckBackupCodeTest extends TestCase { - - /** @var IJobList|\PHPunit\Framework\MockObject\MockObject */ - private $jobList; - - /** @var CheckBackupCodes */ - private $checkBackupsCodes; + private IJobList&MockObject $jobList; + private CheckBackupCodes $checkBackupsCodes; protected function setUp(): void { parent::setUp(); diff --git a/apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php b/apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php index cbda9dd868b..b091d57dbd2 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php @@ -17,15 +17,10 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class NotifierTest extends TestCase { - /** @var Notifier */ - protected $notifier; - - /** @var IFactory|MockObject */ - protected $factory; - /** @var IURLGenerator|MockObject */ - protected $url; - /** @var IL10N|MockObject */ - protected $l; + protected IFactory&MockObject $factory; + protected IURLGenerator&MockObject $url; + protected IL10N&MockObject $l; + protected Notifier $notifier; protected function setUp(): void { parent::setUp(); @@ -52,7 +47,7 @@ class NotifierTest extends TestCase { public function testPrepareWrongApp(): void { $this->expectException(\InvalidArgumentException::class); - /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ + /** @var INotification|MockObject $notification */ $notification = $this->createMock(INotification::class); $notification->expects($this->once()) ->method('getApp') @@ -67,7 +62,7 @@ class NotifierTest extends TestCase { public function testPrepareWrongSubject(): void { $this->expectException(\InvalidArgumentException::class); - /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ + /** @var INotification|MockObject $notification */ $notification = $this->createMock(INotification::class); $notification->expects($this->once()) ->method('getApp') @@ -80,7 +75,7 @@ class NotifierTest extends TestCase { } public function testPrepare(): void { - /** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ + /** @var INotification&MockObject $notification */ $notification = $this->createMock(INotification::class); $notification->expects($this->once()) diff --git a/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php b/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php index 67124a7a928..069e50b71fd 100644 --- a/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php +++ b/apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php @@ -16,24 +16,15 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\IUser; use OCP\Security\IHasher; use OCP\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class BackupCodeStorageTest extends TestCase { - - /** @var BackupCodeMapper|\PHPUnit\Framework\MockObject\MockObject */ - private $mapper; - - /** @var ISecureRandom|\PHPUnit\Framework\MockObject\MockObject */ - private $random; - - /** @var IHasher|\PHPUnit\Framework\MockObject\MockObject */ - private $hasher; - - /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */ - private $eventDispatcher; - - /** @var BackupCodeStorage */ - private $storage; + private BackupCodeMapper&MockObject $mapper; + private ISecureRandom&MockObject $random; + private IHasher&MockObject $hasher; + private IEventDispatcher&MockObject $eventDispatcher; + private BackupCodeStorage $storage; protected function setUp(): void { parent::setUp(); diff --git a/apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php b/apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php index 1b0fe0cbc59..c03d4c48827 100644 --- a/apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php +++ b/apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php @@ -16,9 +16,9 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ResetTokenTest extends TestCase { - private IConfig|MockObject $config; - private IAppConfig|MockObject $appConfig; - private ITimeFactory|MockObject $timeFactory; + private IConfig&MockObject $config; + private IAppConfig&MockObject $appConfig; + private ITimeFactory&MockObject $timeFactory; private BackgroundJobResetToken $resetTokenBackgroundJob; protected function setUp(): void { diff --git a/apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php b/apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php index 36c1d98f2dc..51237cf012e 100644 --- a/apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php +++ b/apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php @@ -26,14 +26,14 @@ use Test\TestCase; class UpdateAvailableNotificationsTest extends TestCase { private ServerVersion&MockObject $serverVersion; - private IConfig|MockObject $config; - private IManager|MockObject $notificationManager; - private IGroupManager|MockObject $groupManager; - private IAppManager|MockObject $appManager; - private IAppConfig|MockObject $appConfig; - private ITimeFactory|MockObject $timeFactory; - private Installer|MockObject $installer; - private VersionCheck|MockObject $versionCheck; + private IConfig&MockObject $config; + private IManager&MockObject $notificationManager; + private IGroupManager&MockObject $groupManager; + private IAppManager&MockObject $appManager; + private IAppConfig&MockObject $appConfig; + private ITimeFactory&MockObject $timeFactory; + private Installer&MockObject $installer; + private VersionCheck&MockObject $versionCheck; protected function setUp(): void { parent::setUp(); @@ -50,10 +50,9 @@ class UpdateAvailableNotificationsTest extends TestCase { } /** - * @param array $methods * @return UpdateAvailableNotifications|MockObject */ - protected function getJob(array $methods = []) { + protected function getJob(array $methods = []): UpdateAvailableNotifications { if (empty($methods)) { return new UpdateAvailableNotifications( $this->timeFactory, @@ -125,7 +124,7 @@ class UpdateAvailableNotificationsTest extends TestCase { self::invokePrivate($job, 'run', [null]); } - public function dataCheckCoreUpdate(): array { + public static function dataCheckCoreUpdate(): array { return [ ['daily', null, null, null, null], ['git', null, null, null, null], @@ -155,14 +154,8 @@ class UpdateAvailableNotificationsTest extends TestCase { /** * @dataProvider dataCheckCoreUpdate - * - * @param string $channel - * @param mixed $versionCheck - * @param null|string $version - * @param null|string $readableVersion - * @param null|int $errorDays */ - public function testCheckCoreUpdate(string $channel, $versionCheck, $version, $readableVersion, $errorDays): void { + public function testCheckCoreUpdate(string $channel, mixed $versionCheck, mixed $version, ?string $readableVersion, ?int $errorDays): void { $job = $this->getJob([ 'createNotifications', 'clearErrorNotifications', @@ -223,7 +216,7 @@ class UpdateAvailableNotificationsTest extends TestCase { self::invokePrivate($job, 'checkCoreUpdate'); } - public function dataCheckAppUpdates(): array { + public static function dataCheckAppUpdates(): array { return [ [ ['app1', 'app2'], @@ -240,10 +233,6 @@ class UpdateAvailableNotificationsTest extends TestCase { /** * @dataProvider dataCheckAppUpdates - * - * @param string[] $apps - * @param array $isUpdateAvailable - * @param array $notifications */ public function testCheckAppUpdates(array $apps, array $isUpdateAvailable, array $notifications): void { $job = $this->getJob([ @@ -271,7 +260,7 @@ class UpdateAvailableNotificationsTest extends TestCase { self::invokePrivate($job, 'checkAppUpdates'); } - public function dataCreateNotifications(): array { + public static function dataCreateNotifications(): array { return [ ['app1', '1.0.0', '1.0.0', false, false, null, null], ['app2', '1.0.1', '1.0.0', '1.0.0', true, ['user1'], [['user1']]], @@ -281,16 +270,8 @@ class UpdateAvailableNotificationsTest extends TestCase { /** * @dataProvider dataCreateNotifications - * - * @param string $app - * @param string $version - * @param string|false $lastNotification - * @param string|false $callDelete - * @param bool $createNotification - * @param string[]|null $users - * @param array|null $userNotifications */ - public function testCreateNotifications(string $app, string $version, $lastNotification, $callDelete, $createNotification, $users, $userNotifications): void { + public function testCreateNotifications(string $app, string $version, string|false $lastNotification, string|false $callDelete, bool $createNotification, ?array $users, ?array $userNotifications): void { $job = $this->getJob([ 'deleteOutdatedNotifications', 'getUsersToNotify', @@ -363,7 +344,7 @@ class UpdateAvailableNotificationsTest extends TestCase { self::invokePrivate($job, 'createNotifications', [$app, $version]); } - public function dataGetUsersToNotify(): array { + public static function dataGetUsersToNotify(): array { return [ [['g1', 'g2'], ['g1' => null, 'g2' => ['u1', 'u2']], ['u1', 'u2']], [['g3', 'g4'], ['g3' => ['u1', 'u2'], 'g4' => ['u2', 'u3']], ['u1', 'u2', 'u3']], @@ -372,9 +353,6 @@ class UpdateAvailableNotificationsTest extends TestCase { /** * @dataProvider dataGetUsersToNotify - * @param string[] $groups - * @param array $groupUsers - * @param string[] $expected */ public function testGetUsersToNotify(array $groups, array $groupUsers, array $expected): void { $job = $this->getJob(); @@ -408,7 +386,7 @@ class UpdateAvailableNotificationsTest extends TestCase { $this->assertEquals($expected, $result); } - public function dataDeleteOutdatedNotifications(): array { + public static function dataDeleteOutdatedNotifications(): array { return [ ['app1', '1.1.0'], ['app2', '1.2.0'], diff --git a/apps/updatenotification/tests/Controller/AdminControllerTest.php b/apps/updatenotification/tests/Controller/AdminControllerTest.php index 877a0276373..2263495fc14 100644 --- a/apps/updatenotification/tests/Controller/AdminControllerTest.php +++ b/apps/updatenotification/tests/Controller/AdminControllerTest.php @@ -22,13 +22,13 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class AdminControllerTest extends TestCase { - private IRequest|MockObject $request; - private IJobList|MockObject $jobList; - private ISecureRandom|MockObject $secureRandom; - private IConfig|MockObject $config; - private ITimeFactory|MockObject $timeFactory; - private IL10N|MockObject $l10n; - private IAppConfig|MockObject $appConfig; + private IRequest&MockObject $request; + private IJobList&MockObject $jobList; + private ISecureRandom&MockObject $secureRandom; + private IConfig&MockObject $config; + private ITimeFactory&MockObject $timeFactory; + private IL10N&MockObject $l10n; + private IAppConfig&MockObject $appConfig; private AdminController $adminController; diff --git a/apps/updatenotification/tests/Notification/NotifierTest.php b/apps/updatenotification/tests/Notification/NotifierTest.php index 4102fdcb773..6d47d0c6b89 100644 --- a/apps/updatenotification/tests/Notification/NotifierTest.php +++ b/apps/updatenotification/tests/Notification/NotifierTest.php @@ -49,9 +49,9 @@ class NotifierTest extends TestCase { /** * @param array $methods - * @return Notifier|\PHPUnit\Framework\MockObject\MockObject + * @return Notifier|MockObject */ - protected function getNotifier(array $methods = []) { + protected function getNotifier(array $methods = []): Notifier { if (empty($methods)) { return new Notifier( $this->urlGenerator, @@ -81,7 +81,7 @@ class NotifierTest extends TestCase { } } - public function dataUpdateAlreadyInstalledCheck(): array { + public static function dataUpdateAlreadyInstalledCheck(): array { return [ ['1.1.0', '1.0.0', false], ['1.1.0', '1.1.0', true], @@ -91,10 +91,6 @@ class NotifierTest extends TestCase { /** * @dataProvider dataUpdateAlreadyInstalledCheck - * - * @param string $versionNotification - * @param string $versionInstalled - * @param bool $exception */ public function testUpdateAlreadyInstalledCheck(string $versionNotification, string $versionInstalled, bool $exception): void { $notifier = $this->getNotifier(); diff --git a/apps/updatenotification/tests/Settings/AdminTest.php b/apps/updatenotification/tests/Settings/AdminTest.php index d228c29f119..cb815bc8b69 100644 --- a/apps/updatenotification/tests/Settings/AdminTest.php +++ b/apps/updatenotification/tests/Settings/AdminTest.php @@ -29,9 +29,6 @@ use Psr\Log\LoggerInterface; use Test\TestCase; class AdminTest extends TestCase { - - private Admin $admin; - private IFactory&MockObject $l10nFactory; private IConfig&MockObject $config; private IAppConfig&MockObject $appConfig; @@ -43,6 +40,7 @@ class AdminTest extends TestCase { private LoggerInterface&MockObject $logger; private IInitialState&MockObject $initialState; private ServerVersion&MockObject $serverVersion; + private Admin $admin; protected function setUp(): void { parent::setUp(); @@ -395,7 +393,7 @@ class AdminTest extends TestCase { $this->assertSame(11, $this->admin->getPriority()); } - public function changesProvider() { + public static function changesProvider(): array { return [ [ #0, all info, en [ diff --git a/apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php b/apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php index 90c85bcdaac..66142082343 100644 --- a/apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php +++ b/apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php @@ -11,18 +11,13 @@ namespace OCA\UserStatus\Tests\BackgroundJob; use OCA\UserStatus\BackgroundJob\ClearOldStatusesBackgroundJob; use OCA\UserStatus\Db\UserStatusMapper; use OCP\AppFramework\Utility\ITimeFactory; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ClearOldStatusesBackgroundJobTest extends TestCase { - - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $time; - - /** @var UserStatusMapper|\PHPUnit\Framework\MockObject\MockObject */ - private $mapper; - - /** @var ClearOldStatusesBackgroundJob */ - private $job; + private ITimeFactory&MockObject $time; + private UserStatusMapper&MockObject $mapper; + private ClearOldStatusesBackgroundJob $job; protected function setUp(): void { parent::setUp(); diff --git a/apps/user_status/tests/Unit/CapabilitiesTest.php b/apps/user_status/tests/Unit/CapabilitiesTest.php index 9e72d49fe31..ef721eaa90b 100644 --- a/apps/user_status/tests/Unit/CapabilitiesTest.php +++ b/apps/user_status/tests/Unit/CapabilitiesTest.php @@ -10,15 +10,12 @@ namespace OCA\UserStatus\Tests; use OCA\UserStatus\Capabilities; use OCP\IEmojiHelper; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class CapabilitiesTest extends TestCase { - - /** @var IEmojiHelper|\PHPUnit\Framework\MockObject\MockObject */ - private $emojiHelper; - - /** @var Capabilities */ - private $capabilities; + private IEmojiHelper&MockObject $emojiHelper; + private Capabilities $capabilities; protected function setUp(): void { parent::setUp(); @@ -28,8 +25,6 @@ class CapabilitiesTest extends TestCase { } /** - * @param bool $supportsEmojis - * * @dataProvider getCapabilitiesDataProvider */ public function testGetCapabilities(bool $supportsEmojis): void { @@ -46,7 +41,7 @@ class CapabilitiesTest extends TestCase { ], $this->capabilities->getCapabilities()); } - public function getCapabilitiesDataProvider(): array { + public static function getCapabilitiesDataProvider(): array { return [ [true], [false], diff --git a/apps/user_status/tests/Unit/Connector/UserStatusProviderTest.php b/apps/user_status/tests/Unit/Connector/UserStatusProviderTest.php index 7e2da883af4..df6c55488d5 100644 --- a/apps/user_status/tests/Unit/Connector/UserStatusProviderTest.php +++ b/apps/user_status/tests/Unit/Connector/UserStatusProviderTest.php @@ -11,15 +11,12 @@ namespace OCA\UserStatus\Tests\Connector; use OCA\UserStatus\Connector\UserStatusProvider; use OCA\UserStatus\Db\UserStatus; use OCA\UserStatus\Service\StatusService; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class UserStatusProviderTest extends TestCase { - - /** @var \PHPUnit\Framework\MockObject\MockObject */ - private $service; - - /** @var UserStatusProvider */ - private $provider; + private StatusService&MockObject $service; + private UserStatusProvider $provider; protected function setUp(): void { parent::setUp(); diff --git a/apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php b/apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php index 5709cdc89cf..0f96f41a524 100644 --- a/apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php +++ b/apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php @@ -11,15 +11,12 @@ namespace OCA\UserStatus\Tests\Controller; use OCA\UserStatus\Controller\PredefinedStatusController; use OCA\UserStatus\Service\PredefinedStatusService; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class PredefinedStatusControllerTest extends TestCase { - - /** @var PredefinedStatusService|\PHPUnit\Framework\MockObject\MockObject */ - private $service; - - /** @var PredefinedStatusController */ - private $controller; + private PredefinedStatusService&MockObject $service; + private PredefinedStatusController $controller; protected function setUp(): void { parent::setUp(); @@ -27,8 +24,7 @@ class PredefinedStatusControllerTest extends TestCase { $request = $this->createMock(IRequest::class); $this->service = $this->createMock(PredefinedStatusService::class); - $this->controller = new PredefinedStatusController('user_status', $request, - $this->service); + $this->controller = new PredefinedStatusController('user_status', $request, $this->service); } public function testFindAll(): void { diff --git a/apps/user_status/tests/Unit/Controller/StatusesControllerTest.php b/apps/user_status/tests/Unit/Controller/StatusesControllerTest.php index fe3e1c56a7e..76d337879c3 100644 --- a/apps/user_status/tests/Unit/Controller/StatusesControllerTest.php +++ b/apps/user_status/tests/Unit/Controller/StatusesControllerTest.php @@ -14,15 +14,12 @@ use OCA\UserStatus\Service\StatusService; use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\OCS\OCSNotFoundException; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class StatusesControllerTest extends TestCase { - - /** @var StatusService|\PHPUnit\Framework\MockObject\MockObject */ - private $service; - - /** @var StatusesController */ - private $controller; + private StatusService&MockObject $service; + private StatusesController $controller; protected function setUp(): void { parent::setUp(); diff --git a/apps/user_status/tests/Unit/Controller/UserStatusControllerTest.php b/apps/user_status/tests/Unit/Controller/UserStatusControllerTest.php index 26b29bcc74c..45ee9c4fdba 100644 --- a/apps/user_status/tests/Unit/Controller/UserStatusControllerTest.php +++ b/apps/user_status/tests/Unit/Controller/UserStatusControllerTest.php @@ -21,22 +21,16 @@ use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\OCS\OCSBadRequestException; use OCP\AppFramework\OCS\OCSNotFoundException; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; use Throwable; class UserStatusControllerTest extends TestCase { - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; - - /** @var StatusService|\PHPUnit\Framework\MockObject\MockObject */ - private $statusService; - - /** @var CalendarStatusService|\PHPUnit\Framework\MockObject\MockObject $calendarStatusService */ - private $calendarStatusService; - - /** @var UserStatusController */ - private $controller; + private LoggerInterface&MockObject $logger; + private StatusService&MockObject $statusService; + private CalendarStatusService&MockObject $calendarStatusService; + private UserStatusController $controller; protected function setUp(): void { parent::setUp(); @@ -94,19 +88,10 @@ class UserStatusControllerTest extends TestCase { } /** - * @param string $statusType - * @param string|null $statusIcon - * @param string|null $message - * @param int|null $clearAt - * @param bool $expectSuccess - * @param bool $expectException - * @param Throwable|null $exception - * @param bool $expectLogger - * @param string|null $expectedLogMessage - * * @dataProvider setStatusDataProvider */ - public function testSetStatus(string $statusType, + public function testSetStatus( + string $statusType, ?string $statusIcon, ?string $message, ?int $clearAt, @@ -114,7 +99,8 @@ class UserStatusControllerTest extends TestCase { bool $expectException, ?Throwable $exception, bool $expectLogger, - ?string $expectedLogMessage): void { + ?string $expectedLogMessage, + ): void { $userStatus = $this->getUserStatus(); if ($expectException) { @@ -155,7 +141,7 @@ class UserStatusControllerTest extends TestCase { } } - public function setStatusDataProvider(): array { + public static function setStatusDataProvider(): array { return [ ['busy', '👨🏽💻', 'Busy developing the status feature', 500, true, false, null, false, null], ['busy', '👨🏽💻', 'Busy developing the status feature', 500, false, true, new InvalidStatusTypeException('Original exception message'), true, @@ -164,23 +150,17 @@ class UserStatusControllerTest extends TestCase { } /** - * @param string $messageId - * @param int|null $clearAt - * @param bool $expectSuccess - * @param bool $expectException - * @param Throwable|null $exception - * @param bool $expectLogger - * @param string|null $expectedLogMessage - * * @dataProvider setPredefinedMessageDataProvider */ - public function testSetPredefinedMessage(string $messageId, + public function testSetPredefinedMessage( + string $messageId, ?int $clearAt, bool $expectSuccess, bool $expectException, ?Throwable $exception, bool $expectLogger, - ?string $expectedLogMessage): void { + ?string $expectedLogMessage, + ): void { $userStatus = $this->getUserStatus(); if ($expectException) { @@ -221,7 +201,7 @@ class UserStatusControllerTest extends TestCase { } } - public function setPredefinedMessageDataProvider(): array { + public static function setPredefinedMessageDataProvider(): array { return [ ['messageId-42', 500, true, false, null, false, null], ['messageId-42', 500, false, true, new InvalidClearAtException('Original exception message'), true, @@ -232,19 +212,10 @@ class UserStatusControllerTest extends TestCase { } /** - * @param string|null $statusIcon - * @param string $message - * @param int|null $clearAt - * @param bool $expectSuccess - * @param bool $expectException - * @param Throwable|null $exception - * @param bool $expectLogger - * @param string|null $expectedLogMessage - * @param bool $expectSuccessAsReset - * * @dataProvider setCustomMessageDataProvider */ - public function testSetCustomMessage(?string $statusIcon, + public function testSetCustomMessage( + ?string $statusIcon, string $message, ?int $clearAt, bool $expectSuccess, @@ -252,7 +223,8 @@ class UserStatusControllerTest extends TestCase { ?Throwable $exception, bool $expectLogger, ?string $expectedLogMessage, - bool $expectSuccessAsReset = false): void { + bool $expectSuccessAsReset = false, + ): void { $userStatus = $this->getUserStatus(); if ($expectException) { @@ -308,7 +280,7 @@ class UserStatusControllerTest extends TestCase { } } - public function setCustomMessageDataProvider(): array { + public static function setCustomMessageDataProvider(): array { return [ ['👨🏽💻', 'Busy developing the status feature', 500, true, false, null, false, null], ['👨🏽💻', '', 500, true, false, null, false, null, false], diff --git a/apps/user_status/tests/Unit/Dashboard/UserStatusWidgetTest.php b/apps/user_status/tests/Unit/Dashboard/UserStatusWidgetTest.php index e776837fac8..8773b04c95f 100644 --- a/apps/user_status/tests/Unit/Dashboard/UserStatusWidgetTest.php +++ b/apps/user_status/tests/Unit/Dashboard/UserStatusWidgetTest.php @@ -16,33 +16,18 @@ use OCP\IL10N; use OCP\IURLGenerator; use OCP\IUserManager; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class UserStatusWidgetTest extends TestCase { - - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ - private $l10n; - - /** @var IDateTimeFormatter|\PHPUnit\Framework\MockObject\MockObject */ - private $dateTimeFormatter; - - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; - - /** @var IInitialState|\PHPUnit\Framework\MockObject\MockObject */ - private $initialState; - - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; - - /** @var StatusService|\PHPUnit\Framework\MockObject\MockObject */ - private $service; - - /** @var UserStatusWidget */ - private $widget; + private IL10N&MockObject $l10n; + private IDateTimeFormatter&MockObject $dateTimeFormatter; + private IURLGenerator&MockObject $urlGenerator; + private IInitialState&MockObject $initialState; + private IUserManager&MockObject $userManager; + private IUserSession&MockObject $userSession; + private StatusService&MockObject $service; + private UserStatusWidget $widget; protected function setUp(): void { parent::setUp(); diff --git a/apps/user_status/tests/Unit/Db/UserStatusMapperTest.php b/apps/user_status/tests/Unit/Db/UserStatusMapperTest.php index 46147c6a822..c9bda492210 100644 --- a/apps/user_status/tests/Unit/Db/UserStatusMapperTest.php +++ b/apps/user_status/tests/Unit/Db/UserStatusMapperTest.php @@ -15,9 +15,7 @@ use OCP\DB\Exception; use Test\TestCase; class UserStatusMapperTest extends TestCase { - - /** @var UserStatusMapper */ - private $mapper; + private UserStatusMapper $mapper; protected function setUp(): void { parent::setUp(); @@ -137,11 +135,6 @@ class UserStatusMapperTest extends TestCase { } /** - * @param string $status - * @param bool $isUserDefined - * @param int $timestamp - * @param bool $expectsClean - * * @dataProvider clearStatusesOlderThanDataProvider */ public function testClearStatusesOlderThan(string $status, bool $isUserDefined, int $timestamp, bool $expectsClean): void { @@ -169,7 +162,7 @@ class UserStatusMapperTest extends TestCase { } } - public function clearStatusesOlderThanDataProvider(): array { + public static function clearStatusesOlderThanDataProvider(): array { return [ ['offline', false, 6000, false], ['online', true, 6000, false], @@ -231,7 +224,7 @@ class UserStatusMapperTest extends TestCase { $this->mapper->insert($userStatus3); } - public function dataCreateBackupStatus(): array { + public static function dataCreateBackupStatus(): array { return [ [false, false, false], [true, false, true], @@ -242,9 +235,6 @@ class UserStatusMapperTest extends TestCase { /** * @dataProvider dataCreateBackupStatus - * @param bool $hasStatus - * @param bool $hasBackup - * @param bool $backupCreated */ public function testCreateBackupStatus(bool $hasStatus, bool $hasBackup, bool $backupCreated): void { if ($hasStatus) { diff --git a/apps/user_status/tests/Unit/Listener/UserDeletedListenerTest.php b/apps/user_status/tests/Unit/Listener/UserDeletedListenerTest.php index 128b5c78c48..fbcea23338d 100644 --- a/apps/user_status/tests/Unit/Listener/UserDeletedListenerTest.php +++ b/apps/user_status/tests/Unit/Listener/UserDeletedListenerTest.php @@ -13,15 +13,12 @@ use OCA\UserStatus\Service\StatusService; use OCP\EventDispatcher\GenericEvent; use OCP\IUser; use OCP\User\Events\UserDeletedEvent; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class UserDeletedListenerTest extends TestCase { - - /** @var StatusService|\PHPUnit\Framework\MockObject\MockObject */ - private $service; - - /** @var UserDeletedListener */ - private $listener; + private StatusService&MockObject $service; + private UserDeletedListener $listener; protected function setUp(): void { parent::setUp(); diff --git a/apps/user_status/tests/Unit/Listener/UserLiveStatusListenerTest.php b/apps/user_status/tests/Unit/Listener/UserLiveStatusListenerTest.php index 421cce046df..c94315a7a93 100644 --- a/apps/user_status/tests/Unit/Listener/UserLiveStatusListenerTest.php +++ b/apps/user_status/tests/Unit/Listener/UserLiveStatusListenerTest.php @@ -11,7 +11,6 @@ namespace OCA\UserStatus\Tests\Listener; use OCA\DAV\CalDAV\Status\StatusService as CalendarStatusService; use OCA\UserStatus\Db\UserStatus; use OCA\UserStatus\Db\UserStatusMapper; -use OCA\UserStatus\Listener\UserDeletedListener; use OCA\UserStatus\Listener\UserLiveStatusListener; use OCA\UserStatus\Service\StatusService; use OCP\AppFramework\Db\DoesNotExistException; @@ -24,20 +23,13 @@ use Psr\Log\LoggerInterface; use Test\TestCase; class UserLiveStatusListenerTest extends TestCase { + private UserStatusMapper&MockObject $mapper; + private StatusService&MockObject $statusService; + private ITimeFactory&MockObject $timeFactory; + private CalendarStatusService&MockObject $calendarStatusService; - /** @var UserStatusMapper|MockObject */ - private $mapper; - /** @var StatusService|MockObject */ - private $statusService; - /** @var ITimeFactory|MockObject */ - private $timeFactory; - - /** @var UserDeletedListener */ - private $listener; - - private CalendarStatusService|MockObject $calendarStatusService; - - private LoggerInterface|MockObject $logger; + private LoggerInterface&MockObject $logger; + private UserLiveStatusListener $listener; protected function setUp(): void { parent::setUp(); @@ -58,25 +50,18 @@ class UserLiveStatusListenerTest extends TestCase { } /** - * @param string $userId - * @param string $previousStatus - * @param int $previousTimestamp - * @param bool $previousIsUserDefined - * @param string $eventStatus - * @param int $eventTimestamp - * @param bool $expectExisting - * @param bool $expectUpdate - * * @dataProvider handleEventWithCorrectEventDataProvider */ - public function testHandleWithCorrectEvent(string $userId, + public function testHandleWithCorrectEvent( + string $userId, string $previousStatus, int $previousTimestamp, bool $previousIsUserDefined, string $eventStatus, int $eventTimestamp, bool $expectExisting, - bool $expectUpdate): void { + bool $expectUpdate, + ): void { $userStatus = new UserStatus(); if ($expectExisting) { @@ -143,7 +128,7 @@ class UserLiveStatusListenerTest extends TestCase { } } - public function handleEventWithCorrectEventDataProvider(): array { + public static function handleEventWithCorrectEventDataProvider(): array { return [ ['john.doe', 'offline', 0, false, 'online', 5000, true, true], ['john.doe', 'offline', 0, false, 'online', 5000, false, true], diff --git a/apps/user_status/tests/Unit/Service/PredefinedStatusServiceTest.php b/apps/user_status/tests/Unit/Service/PredefinedStatusServiceTest.php index 12b34ed0b4d..091466637f0 100644 --- a/apps/user_status/tests/Unit/Service/PredefinedStatusServiceTest.php +++ b/apps/user_status/tests/Unit/Service/PredefinedStatusServiceTest.php @@ -10,15 +10,12 @@ namespace OCA\UserStatus\Tests\Service; use OCA\UserStatus\Service\PredefinedStatusService; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class PredefinedStatusServiceTest extends TestCase { - - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ - protected $l10n; - - /** @var PredefinedStatusService */ - protected $service; + protected IL10N&MockObject $l10n; + protected PredefinedStatusService $service; protected function setUp(): void { parent::setUp(); @@ -97,9 +94,6 @@ class PredefinedStatusServiceTest extends TestCase { } /** - * @param string $id - * @param string|null $expectedIcon - * * @dataProvider getIconForIdDataProvider */ public function testGetIconForId(string $id, ?string $expectedIcon): void { @@ -107,10 +101,7 @@ class PredefinedStatusServiceTest extends TestCase { $this->assertEquals($expectedIcon, $actual); } - /** - * @return array - */ - public function getIconForIdDataProvider(): array { + public static function getIconForIdDataProvider(): array { return [ ['meeting', '📅'], ['commuting', '🚌'], @@ -123,9 +114,6 @@ class PredefinedStatusServiceTest extends TestCase { } /** - * @param string $id - * @param string|null $expected - * * @dataProvider getTranslatedStatusForIdDataProvider */ public function testGetTranslatedStatusForId(string $id, ?string $expected): void { @@ -136,10 +124,7 @@ class PredefinedStatusServiceTest extends TestCase { $this->assertEquals($expected, $actual); } - /** - * @return array - */ - public function getTranslatedStatusForIdDataProvider(): array { + public static function getTranslatedStatusForIdDataProvider(): array { return [ ['meeting', 'In a meeting'], ['commuting', 'Commuting'], @@ -152,9 +137,6 @@ class PredefinedStatusServiceTest extends TestCase { } /** - * @param string $id - * @param bool $expected - * * @dataProvider isValidIdDataProvider */ public function testIsValidId(string $id, bool $expected): void { @@ -162,10 +144,7 @@ class PredefinedStatusServiceTest extends TestCase { $this->assertEquals($expected, $actual); } - /** - * @return array - */ - public function isValidIdDataProvider(): array { + public static function isValidIdDataProvider(): array { return [ ['meeting', true], ['commuting', true], diff --git a/apps/user_status/tests/Unit/Service/StatusServiceTest.php b/apps/user_status/tests/Unit/Service/StatusServiceTest.php index 801d0cea0fc..7aeb1d48448 100644 --- a/apps/user_status/tests/Unit/Service/StatusServiceTest.php +++ b/apps/user_status/tests/Unit/Service/StatusServiceTest.php @@ -31,27 +31,13 @@ use Psr\Log\LoggerInterface; use Test\TestCase; class StatusServiceTest extends TestCase { - - /** @var UserStatusMapper|MockObject */ - private $mapper; - - /** @var ITimeFactory|MockObject */ - private $timeFactory; - - /** @var PredefinedStatusService|MockObject */ - private $predefinedStatusService; - - /** @var IEmojiHelper|MockObject */ - private $emojiHelper; - - /** @var IConfig|MockObject */ - private $config; - - /** @var IUserManager|MockObject */ - private $userManager; - - /** @var LoggerInterface|MockObject */ - private $logger; + private UserStatusMapper&MockObject $mapper; + private ITimeFactory&MockObject $timeFactory; + private PredefinedStatusService&MockObject $predefinedStatusService; + private IEmojiHelper&MockObject $emojiHelper; + private IConfig&MockObject $config; + private IUserManager&MockObject $userManager; + private LoggerInterface&MockObject $logger; private StatusService $service; @@ -236,20 +222,10 @@ class StatusServiceTest extends TestCase { } /** - * @param string $userId - * @param string $status - * @param int|null $statusTimestamp - * @param bool $isUserDefined - * @param bool $expectExisting - * @param bool $expectSuccess - * @param bool $expectTimeFactory - * @param bool $expectException - * @param string|null $expectedExceptionClass - * @param string|null $expectedExceptionMessage - * * @dataProvider setStatusDataProvider */ - public function testSetStatus(string $userId, + public function testSetStatus( + string $userId, string $status, ?int $statusTimestamp, bool $isUserDefined, @@ -258,7 +234,8 @@ class StatusServiceTest extends TestCase { bool $expectTimeFactory, bool $expectException, ?string $expectedExceptionClass, - ?string $expectedExceptionMessage): void { + ?string $expectedExceptionMessage, + ): void { $userStatus = new UserStatus(); if ($expectExisting) { @@ -309,7 +286,7 @@ class StatusServiceTest extends TestCase { } } - public function setStatusDataProvider(): array { + public static function setStatusDataProvider(): array { return [ ['john.doe', 'online', 50, true, true, true, false, false, null, null], ['john.doe', 'online', 50, true, false, true, false, false, null, null], @@ -368,19 +345,10 @@ class StatusServiceTest extends TestCase { } /** - * @param string $userId - * @param string $messageId - * @param bool $isValidMessageId - * @param int|null $clearAt - * @param bool $expectExisting - * @param bool $expectSuccess - * @param bool $expectException - * @param string|null $expectedExceptionClass - * @param string|null $expectedExceptionMessage - * * @dataProvider setPredefinedMessageDataProvider */ - public function testSetPredefinedMessage(string $userId, + public function testSetPredefinedMessage( + string $userId, string $messageId, bool $isValidMessageId, ?int $clearAt, @@ -388,7 +356,8 @@ class StatusServiceTest extends TestCase { bool $expectSuccess, bool $expectException, ?string $expectedExceptionClass, - ?string $expectedExceptionMessage): void { + ?string $expectedExceptionMessage, + ): void { $userStatus = new UserStatus(); if ($expectExisting) { @@ -451,7 +420,7 @@ class StatusServiceTest extends TestCase { } } - public function setPredefinedMessageDataProvider(): array { + public static function setPredefinedMessageDataProvider(): array { return [ ['john.doe', 'sick-leave', true, null, true, true, false, null, null], ['john.doe', 'sick-leave', true, null, false, true, false, null, null], @@ -465,20 +434,10 @@ class StatusServiceTest extends TestCase { } /** - * @param string $userId - * @param string|null $statusIcon - * @param bool $supportsEmoji - * @param string $message - * @param int|null $clearAt - * @param bool $expectExisting - * @param bool $expectSuccess - * @param bool $expectException - * @param string|null $expectedExceptionClass - * @param string|null $expectedExceptionMessage - * * @dataProvider setCustomMessageDataProvider */ - public function testSetCustomMessage(string $userId, + public function testSetCustomMessage( + string $userId, ?string $statusIcon, bool $supportsEmoji, string $message, @@ -487,7 +446,8 @@ class StatusServiceTest extends TestCase { bool $expectSuccess, bool $expectException, ?string $expectedExceptionClass, - ?string $expectedExceptionMessage): void { + ?string $expectedExceptionMessage, + ): void { $userStatus = new UserStatus(); if ($expectExisting) { @@ -548,7 +508,7 @@ class StatusServiceTest extends TestCase { } } - public function setCustomMessageDataProvider(): array { + public static function setCustomMessageDataProvider(): array { return [ ['john.doe', '😁', true, 'Custom message', null, true, true, false, null, null], ['john.doe', '😁', true, 'Custom message', null, false, true, false, null, null], @@ -815,7 +775,7 @@ class StatusServiceTest extends TestCase { $this->service->revertMultipleUserStatus(['john', 'nobackup', 'backuponly', 'nobackupanddnd'], 'call'); } - public function dataSetUserStatus(): array { + public static function dataSetUserStatus(): array { return [ [IUserStatus::MESSAGE_CALENDAR_BUSY, '', false], diff --git a/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php b/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php index be99bccb677..45d66090eae 100644 --- a/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php +++ b/apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php @@ -44,7 +44,7 @@ class WebhookListenerMapperTest extends TestCase { parent::tearDown(); } - protected function pruneTables() { + protected function pruneTables(): void { $query = $this->connection->getQueryBuilder(); $query->delete(WebhookListenerMapper::TABLE_NAME)->executeStatement(); } diff --git a/apps/workflowengine/tests/Check/AbstractStringCheckTest.php b/apps/workflowengine/tests/Check/AbstractStringCheckTest.php index 774f866bf12..d10fcfb4cc3 100644 --- a/apps/workflowengine/tests/Check/AbstractStringCheckTest.php +++ b/apps/workflowengine/tests/Check/AbstractStringCheckTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -7,9 +10,10 @@ namespace OCA\WorkflowEngine\Tests\Check; use OCA\WorkflowEngine\Check\AbstractStringCheck; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; class AbstractStringCheckTest extends \Test\TestCase { - protected function getCheckMock() { + protected function getCheckMock(): AbstractStringCheck|MockObject { $l = $this->getMockBuilder(IL10N::class) ->disableOriginalConstructor() ->getMock(); @@ -19,7 +23,7 @@ class AbstractStringCheckTest extends \Test\TestCase { return sprintf($string, $args); }); - $check = $this->getMockBuilder('OCA\WorkflowEngine\Check\AbstractStringCheck') + $check = $this->getMockBuilder(AbstractStringCheck::class) ->setConstructorArgs([ $l, ]) @@ -32,7 +36,7 @@ class AbstractStringCheckTest extends \Test\TestCase { return $check; } - public function dataExecuteStringCheck() { + public static function dataExecuteStringCheck(): array { return [ ['is', 'same', 'same', true], ['is', 'different', 'not the same', false], @@ -48,19 +52,15 @@ class AbstractStringCheckTest extends \Test\TestCase { /** * @dataProvider dataExecuteStringCheck - * @param string $operation - * @param string $checkValue - * @param string $actualValue - * @param bool $expected */ - public function testExecuteStringCheck($operation, $checkValue, $actualValue, $expected): void { + public function testExecuteStringCheck(string $operation, string $checkValue, string $actualValue, bool $expected): void { $check = $this->getCheckMock(); /** @var AbstractStringCheck $check */ $this->assertEquals($expected, $this->invokePrivate($check, 'executeStringCheck', [$operation, $checkValue, $actualValue])); } - public function dataValidateCheck() { + public static function dataValidateCheck(): array { return [ ['is', '/Invalid(Regex/'], ['!is', '/Invalid(Regex/'], @@ -71,10 +71,8 @@ class AbstractStringCheckTest extends \Test\TestCase { /** * @dataProvider dataValidateCheck - * @param string $operator - * @param string $value */ - public function testValidateCheck($operator, $value): void { + public function testValidateCheck(string $operator, string $value): void { $check = $this->getCheckMock(); /** @var AbstractStringCheck $check */ @@ -83,7 +81,7 @@ class AbstractStringCheckTest extends \Test\TestCase { $this->addToAssertionCount(1); } - public function dataValidateCheckInvalid() { + public static function dataValidateCheckInvalid(): array { return [ ['!!is', '', 1, 'The given operator is invalid'], ['less', '', 1, 'The given operator is invalid'], @@ -94,12 +92,8 @@ class AbstractStringCheckTest extends \Test\TestCase { /** * @dataProvider dataValidateCheckInvalid - * @param $operator - * @param $value - * @param $exceptionCode - * @param $exceptionMessage */ - public function testValidateCheckInvalid($operator, $value, $exceptionCode, $exceptionMessage): void { + public function testValidateCheckInvalid(string $operator, string $value, int $exceptionCode, string $exceptionMessage): void { $check = $this->getCheckMock(); try { @@ -111,7 +105,7 @@ class AbstractStringCheckTest extends \Test\TestCase { } } - public function dataMatch() { + public static function dataMatch(): array { return [ ['/valid/', 'valid', [], true], ['/valid/', 'valid', [md5('/valid/') => [md5('valid') => false]], false], // Cache hit @@ -120,12 +114,8 @@ class AbstractStringCheckTest extends \Test\TestCase { /** * @dataProvider dataMatch - * @param string $pattern - * @param string $subject - * @param array[] $matches - * @param bool $expected */ - public function testMatch($pattern, $subject, $matches, $expected): void { + public function testMatch(string $pattern, string $subject, array $matches, bool $expected): void { $check = $this->getCheckMock(); $this->invokePrivate($check, 'matches', [$matches]); diff --git a/apps/workflowengine/tests/Check/RequestRemoteAddressTest.php b/apps/workflowengine/tests/Check/RequestRemoteAddressTest.php index 47b9138819e..f2f8026e666 100644 --- a/apps/workflowengine/tests/Check/RequestRemoteAddressTest.php +++ b/apps/workflowengine/tests/Check/RequestRemoteAddressTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -8,19 +11,14 @@ namespace OCA\WorkflowEngine\Tests\Check; use OCA\WorkflowEngine\Check\RequestRemoteAddress; use OCP\IL10N; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; class RequestRemoteAddressTest extends \Test\TestCase { - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - protected $request; + protected IRequest&MockObject $request; - /** - * @return IL10N|\PHPUnit\Framework\MockObject\MockObject - */ - protected function getL10NMock() { - $l = $this->getMockBuilder(IL10N::class) - ->disableOriginalConstructor() - ->getMock(); + protected function getL10NMock(): IL10N&MockObject { + $l = $this->createMock(IL10N::class); $l->expects($this->any()) ->method('t') ->willReturnCallback(function ($string, $args) { @@ -32,11 +30,10 @@ class RequestRemoteAddressTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->request = $this->getMockBuilder(IRequest::class) - ->getMock(); + $this->request = $this->createMock(IRequest::class); } - public function dataExecuteCheckIPv4() { + public static function dataExecuteCheckIPv4(): array { return [ ['127.0.0.1/32', '127.0.0.1', true], ['127.0.0.1/32', '127.0.0.0', false], @@ -49,11 +46,8 @@ class RequestRemoteAddressTest extends \Test\TestCase { /** * @dataProvider dataExecuteCheckIPv4 - * @param string $value - * @param string $ip - * @param bool $expected */ - public function testExecuteCheckMatchesIPv4($value, $ip, $expected): void { + public function testExecuteCheckMatchesIPv4(string $value, string $ip, bool $expected): void { $check = new RequestRemoteAddress($this->getL10NMock(), $this->request); $this->request->expects($this->once()) @@ -65,11 +59,8 @@ class RequestRemoteAddressTest extends \Test\TestCase { /** * @dataProvider dataExecuteCheckIPv4 - * @param string $value - * @param string $ip - * @param bool $expected */ - public function testExecuteCheckNotMatchesIPv4($value, $ip, $expected): void { + public function testExecuteCheckNotMatchesIPv4(string $value, string $ip, bool $expected): void { $check = new RequestRemoteAddress($this->getL10NMock(), $this->request); $this->request->expects($this->once()) @@ -79,7 +70,7 @@ class RequestRemoteAddressTest extends \Test\TestCase { $this->assertEquals(!$expected, $check->executeCheck('!matchesIPv4', $value)); } - public function dataExecuteCheckIPv6() { + public static function dataExecuteCheckIPv6(): array { return [ ['::1/128', '::1', true], ['::2/128', '::3', false], @@ -93,11 +84,8 @@ class RequestRemoteAddressTest extends \Test\TestCase { /** * @dataProvider dataExecuteCheckIPv6 - * @param string $value - * @param string $ip - * @param bool $expected */ - public function testExecuteCheckMatchesIPv6($value, $ip, $expected): void { + public function testExecuteCheckMatchesIPv6(string $value, string $ip, bool $expected): void { $check = new RequestRemoteAddress($this->getL10NMock(), $this->request); $this->request->expects($this->once()) @@ -109,11 +97,8 @@ class RequestRemoteAddressTest extends \Test\TestCase { /** * @dataProvider dataExecuteCheckIPv6 - * @param string $value - * @param string $ip - * @param bool $expected */ - public function testExecuteCheckNotMatchesIPv6($value, $ip, $expected): void { + public function testExecuteCheckNotMatchesIPv6(string $value, string $ip, bool $expected): void { $check = new RequestRemoteAddress($this->getL10NMock(), $this->request); $this->request->expects($this->once()) diff --git a/apps/workflowengine/tests/Check/RequestTimeTest.php b/apps/workflowengine/tests/Check/RequestTimeTest.php index 6b56bb9427a..21127d4d56e 100644 --- a/apps/workflowengine/tests/Check/RequestTimeTest.php +++ b/apps/workflowengine/tests/Check/RequestTimeTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -8,19 +11,13 @@ namespace OCA\WorkflowEngine\Tests\Check; use OCA\WorkflowEngine\Check\RequestTime; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; class RequestTimeTest extends \Test\TestCase { + protected ITimeFactory&MockObject $timeFactory; - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ - protected $timeFactory; - - /** - * @return IL10N|\PHPUnit\Framework\MockObject\MockObject - */ - protected function getL10NMock() { - $l = $this->getMockBuilder(IL10N::class) - ->disableOriginalConstructor() - ->getMock(); + protected function getL10NMock(): IL10N&MockObject { + $l = $this->createMock(IL10N::class); $l->expects($this->any()) ->method('t') ->willReturnCallback(function ($string, $args) { @@ -32,11 +29,10 @@ class RequestTimeTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->timeFactory = $this->getMockBuilder('OCP\AppFramework\Utility\ITimeFactory') - ->getMock(); + $this->timeFactory = $this->createMock(ITimeFactory::class); } - public function dataExecuteCheck() { + public static function dataExecuteCheck(): array { return [ [json_encode(['08:00 Europe/Berlin', '17:00 Europe/Berlin']), 1467870105, false], // 2016-07-07T07:41:45+02:00 [json_encode(['08:00 Europe/Berlin', '17:00 Europe/Berlin']), 1467873705, true], // 2016-07-07T08:41:45+02:00 @@ -69,11 +65,8 @@ class RequestTimeTest extends \Test\TestCase { /** * @dataProvider dataExecuteCheck - * @param string $value - * @param int $timestamp - * @param bool $expected */ - public function testExecuteCheckIn($value, $timestamp, $expected): void { + public function testExecuteCheckIn(string $value, int $timestamp, bool $expected): void { $check = new RequestTime($this->getL10NMock(), $this->timeFactory); $this->timeFactory->expects($this->once()) @@ -85,11 +78,8 @@ class RequestTimeTest extends \Test\TestCase { /** * @dataProvider dataExecuteCheck - * @param string $value - * @param int $timestamp - * @param bool $expected */ - public function testExecuteCheckNotIn($value, $timestamp, $expected): void { + public function testExecuteCheckNotIn(string $value, int $timestamp, bool $expected): void { $check = new RequestTime($this->getL10NMock(), $this->timeFactory); $this->timeFactory->expects($this->once()) @@ -99,7 +89,7 @@ class RequestTimeTest extends \Test\TestCase { $this->assertEquals(!$expected, $check->executeCheck('!in', $value)); } - public function dataValidateCheck() { + public static function dataValidateCheck(): array { return [ ['in', '["08:00 Europe/Berlin","17:00 Europe/Berlin"]'], ['!in', '["08:00 Europe/Berlin","17:00 America/North_Dakota/Beulah"]'], @@ -109,16 +99,14 @@ class RequestTimeTest extends \Test\TestCase { /** * @dataProvider dataValidateCheck - * @param string $operator - * @param string $value */ - public function testValidateCheck($operator, $value): void { + public function testValidateCheck(string $operator, string $value): void { $check = new RequestTime($this->getL10NMock(), $this->timeFactory); $check->validateCheck($operator, $value); $this->addToAssertionCount(1); } - public function dataValidateCheckInvalid() { + public static function dataValidateCheckInvalid(): array { return [ ['!!in', '["08:00 Europe/Berlin","17:00 Europe/Berlin"]', 1, 'The given operator is invalid'], ['in', '["28:00 Europe/Berlin","17:00 Europe/Berlin"]', 2, 'The given time span is invalid'], @@ -132,12 +120,8 @@ class RequestTimeTest extends \Test\TestCase { /** * @dataProvider dataValidateCheckInvalid - * @param string $operator - * @param string $value - * @param int $exceptionCode - * @param string $exceptionMessage */ - public function testValidateCheckInvalid($operator, $value, $exceptionCode, $exceptionMessage): void { + public function testValidateCheckInvalid(string $operator, string $value, int $exceptionCode, string $exceptionMessage): void { $check = new RequestTime($this->getL10NMock(), $this->timeFactory); try { diff --git a/apps/workflowengine/tests/Check/RequestUserAgentTest.php b/apps/workflowengine/tests/Check/RequestUserAgentTest.php index 30e389c8236..2fe96bf3bdb 100644 --- a/apps/workflowengine/tests/Check/RequestUserAgentTest.php +++ b/apps/workflowengine/tests/Check/RequestUserAgentTest.php @@ -1,4 +1,7 @@ <?php + +declare(strict_types=1); + /** * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors * SPDX-License-Identifier: AGPL-3.0-or-later @@ -9,24 +12,19 @@ use OCA\WorkflowEngine\Check\AbstractStringCheck; use OCA\WorkflowEngine\Check\RequestUserAgent; use OCP\IL10N; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RequestUserAgentTest extends TestCase { - - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - protected $request; - - /** @var RequestUserAgent */ - protected $check; + protected IRequest&MockObject $request; + protected RequestUserAgent $check; protected function setUp(): void { parent::setUp(); $this->request = $this->createMock(IRequest::class); - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject $l */ - $l = $this->getMockBuilder(IL10N::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var IL10N&MockObject $l */ + $l = $this->createMock(IL10N::class); $l->expects($this->any()) ->method('t') ->willReturnCallback(function ($string, $args) { @@ -36,7 +34,7 @@ class RequestUserAgentTest extends TestCase { $this->check = new RequestUserAgent($l, $this->request); } - public function dataExecuteCheck() { + public static function dataExecuteCheck(): array { return [ ['is', 'android', 'Mozilla/5.0 (Android) Nextcloud-android/2.2.0', true], ['is', 'android', 'Mozilla/5.0 (iOS) Nextcloud-iOS/2.2.0', false], @@ -86,12 +84,8 @@ class RequestUserAgentTest extends TestCase { /** * @dataProvider dataExecuteCheck - * @param string $operation - * @param string $checkValue - * @param string $actualValue - * @param bool $expected */ - public function testExecuteCheck($operation, $checkValue, $actualValue, $expected): void { + public function testExecuteCheck(string $operation, string $checkValue, string $actualValue, bool $expected): void { $this->request->expects($this->once()) ->method('getHeader') ->willReturn($actualValue); diff --git a/lib/private/Support/CrashReport/Registry.php b/lib/private/Support/CrashReport/Registry.php index 93969a81265..77dd8163174 100644 --- a/lib/private/Support/CrashReport/Registry.php +++ b/lib/private/Support/CrashReport/Registry.php @@ -110,6 +110,7 @@ class Registry implements IRegistry { \OC::$server->get(LoggerInterface::class)->critical('Could not load lazy crash reporter: ' . $e->getMessage(), [ 'exception' => $e, ]); + return; } /** * Try to register the loaded reporter. Theoretically it could be of a wrong diff --git a/tests/lib/Accounts/AccountManagerTest.php b/tests/lib/Accounts/AccountManagerTest.php index fab3aaf5fdd..05c7efd08fb 100644 --- a/tests/lib/Accounts/AccountManagerTest.php +++ b/tests/lib/Accounts/AccountManagerTest.php @@ -499,7 +499,7 @@ class AccountManagerTest extends TestCase { $this->invokePrivate($accountManager, 'updateUser', [$user, $newData, $oldData]); } - public function dataTrueFalse(): array { + public static function dataTrueFalse(): array { return [ #$newData | $oldData | $insertNew | $updateExisting [['myProperty' => ['value' => 'newData']], ['myProperty' => ['value' => 'oldData']], false, true], @@ -896,7 +896,7 @@ class AccountManagerTest extends TestCase { } } - public function searchDataProvider(): array { + public static function searchDataProvider(): array { return [ [ #0 Search for an existing name IAccountManager::PROPERTY_DISPLAYNAME, @@ -948,21 +948,22 @@ class AccountManagerTest extends TestCase { ]; } - public function dataCheckEmailVerification(): array { + public static function dataCheckEmailVerification(): array { return [ - [$this->makeUser('steve', 'Steve Smith', 'steve@steve.steve'), null], - [$this->makeUser('emma', 'Emma Morales', 'emma@emma.com'), 'emma@morales.com'], - [$this->makeUser('sarah@web.org', 'Sarah Foster', 'sarah@web.org'), null], - [$this->makeUser('cole@web.org', 'Cole Harrison', 'cole@web.org'), 'cole@example.com'], - [$this->makeUser('8d29e358-cf69-4849-bbf9-28076c0b908b', 'Alice McPherson', 'alice@example.com'), 'alice@mcpherson.com'], - [$this->makeUser('11da2744-3f4d-4c17-8c13-4c057a379237', 'James Loranger', 'james@example.com'), ''], + [['steve', 'Steve Smith', 'steve@steve.steve'], null], + [['emma', 'Emma Morales', 'emma@emma.com'], 'emma@morales.com'], + [['sarah@web.org', 'Sarah Foster', 'sarah@web.org'], null], + [['cole@web.org', 'Cole Harrison', 'cole@web.org'], 'cole@example.com'], + [['8d29e358-cf69-4849-bbf9-28076c0b908b', 'Alice McPherson', 'alice@example.com'], 'alice@mcpherson.com'], + [['11da2744-3f4d-4c17-8c13-4c057a379237', 'James Loranger', 'james@example.com'], ''], ]; } /** * @dataProvider dataCheckEmailVerification */ - public function testCheckEmailVerification(IUser $user, ?string $newEmail): void { + public function testCheckEmailVerification(array $userData, ?string $newEmail): void { + $user = $this->makeUser(...$userData); // Once because of getAccount, once because of getUser $this->config->expects($this->exactly(2))->method('getSystemValue')->with('account_manager.default_property_scope', [])->willReturn([]); $account = $this->accountManager->getAccount($user); @@ -988,7 +989,7 @@ class AccountManagerTest extends TestCase { $this->invokePrivate($this->accountManager, 'checkEmailVerification', [$account, $oldData]); } - public function dataSetDefaultPropertyScopes(): array { + public static function dataSetDefaultPropertyScopes(): array { return [ [ [], diff --git a/tests/lib/Accounts/AccountPropertyTest.php b/tests/lib/Accounts/AccountPropertyTest.php index ae5a6a0f5e7..68e1da41557 100644 --- a/tests/lib/Accounts/AccountPropertyTest.php +++ b/tests/lib/Accounts/AccountPropertyTest.php @@ -56,7 +56,7 @@ class AccountPropertyTest extends TestCase { $this->assertEquals(IAccountManager::SCOPE_LOCAL, $actualReturn->getScope()); } - public function scopesProvider() { + public static function scopesProvider(): array { return [ // current values [IAccountManager::SCOPE_PRIVATE, IAccountManager::SCOPE_PRIVATE], diff --git a/tests/lib/Accounts/HooksTest.php b/tests/lib/Accounts/HooksTest.php index 75772089f43..73cef2e2c65 100644 --- a/tests/lib/Accounts/HooksTest.php +++ b/tests/lib/Accounts/HooksTest.php @@ -96,14 +96,14 @@ class HooksTest extends TestCase { } } + $params['user'] = $this->createMock(IUser::class); $this->hooks->changeUserHook($params['user'], $params['feature'], $params['value']); } - public function dataTestChangeUserHook() { - $user = $this->createMock(IUser::class); + public static function dataTestChangeUserHook(): array { return [ [ - ['user' => $user, 'feature' => '', 'value' => ''], + ['feature' => '', 'value' => ''], [ IAccountManager::PROPERTY_EMAIL => ['value' => ''], IAccountManager::PROPERTY_DISPLAYNAME => ['value' => ''] @@ -111,7 +111,7 @@ class HooksTest extends TestCase { false, false, true ], [ - ['user' => $user, 'feature' => 'foo', 'value' => 'bar'], + ['feature' => 'foo', 'value' => 'bar'], [ IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'], IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName'] @@ -119,7 +119,7 @@ class HooksTest extends TestCase { false, false, false ], [ - ['user' => $user, 'feature' => 'eMailAddress', 'value' => 'newMail@example.com'], + ['feature' => 'eMailAddress', 'value' => 'newMail@example.com'], [ IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'], IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName'] @@ -127,7 +127,7 @@ class HooksTest extends TestCase { true, false, false ], [ - ['user' => $user, 'feature' => 'displayName', 'value' => 'newDisplayName'], + ['feature' => 'displayName', 'value' => 'newDisplayName'], [ IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'], IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName'] diff --git a/tests/lib/Activity/ManagerTest.php b/tests/lib/Activity/ManagerTest.php index 61eeee82c43..f42a38eab53 100644 --- a/tests/lib/Activity/ManagerTest.php +++ b/tests/lib/Activity/ManagerTest.php @@ -74,7 +74,7 @@ class ManagerTest extends TestCase { self::invokePrivate($this->activityManager, 'getConsumers'); } - public function getUserFromTokenThrowInvalidTokenData() { + public static function getUserFromTokenThrowInvalidTokenData(): array { return [ [null, []], ['', []], @@ -98,7 +98,7 @@ class ManagerTest extends TestCase { self::invokePrivate($this->activityManager, 'getUserFromToken'); } - public function getUserFromTokenData() { + public static function getUserFromTokenData(): array { return [ [null, '123456789012345678901234567890', 'user1'], ['user2', null, 'user2'], @@ -190,7 +190,7 @@ class ManagerTest extends TestCase { $this->activityManager->publish($event); } - public function dataPublish() { + public static function dataPublish(): array { return [ [null, ''], ['test_author', 'test_author'], diff --git a/tests/lib/AllConfigTest.php b/tests/lib/AllConfigTest.php index e892e441ecf..b4137c07ac5 100644 --- a/tests/lib/AllConfigTest.php +++ b/tests/lib/AllConfigTest.php @@ -125,7 +125,7 @@ class AllConfigTest extends \Test\TestCase { $config->deleteUserValue('userPreCond', 'appPreCond', 'keyPreCond'); } - public function dataSetUserValueUnexpectedValue() { + public static function dataSetUserValueUnexpectedValue(): array { return [ [true], [false], diff --git a/tests/lib/App/AppManagerTest.php b/tests/lib/App/AppManagerTest.php index 19039366aa8..2e1163cf9db 100644 --- a/tests/lib/App/AppManagerTest.php +++ b/tests/lib/App/AppManagerTest.php @@ -301,7 +301,7 @@ class AppManagerTest extends TestCase { $this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no')); } - public function dataEnableAppForGroupsAllowedTypes() { + public static function dataEnableAppForGroupsAllowedTypes(): array { return [ [[]], [[ @@ -361,7 +361,7 @@ class AppManagerTest extends TestCase { $this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no')); } - public function dataEnableAppForGroupsForbiddenTypes() { + public static function dataEnableAppForGroupsForbiddenTypes(): array { return [ ['filesystem'], ['prelogin'], diff --git a/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php b/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php index e7652d5c50c..5a9c37af7fb 100644 --- a/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php +++ b/tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php @@ -104,7 +104,7 @@ class AppDiscoverFetcherTest extends FetcherBase { } } - public function dataGetETag(): array { + public static function dataGetETag(): array { return [ 'file not found' => [null, true], 'empty file' => [null, false, ''], diff --git a/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php b/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php index 61fe24be1a9..0d311d8878a 100644 --- a/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php +++ b/tests/lib/App/AppStore/Fetcher/AppFetcherTest.php @@ -1840,7 +1840,7 @@ EJL3BaQAQaASSsvFrcozYxrQG4VzEg== $this->registry = $this->createMock(IRegistry::class); $this->fetcher = $this->getMockBuilder(AppFetcher::class) - ->setMethods(['getChannel']) + ->onlyMethods(['getChannel']) ->setConstructorArgs([ $factory, $this->clientService, diff --git a/tests/lib/App/AppStore/Version/VersionParserTest.php b/tests/lib/App/AppStore/Version/VersionParserTest.php index 5bd9ee16b39..c4dd78af496 100644 --- a/tests/lib/App/AppStore/Version/VersionParserTest.php +++ b/tests/lib/App/AppStore/Version/VersionParserTest.php @@ -22,7 +22,7 @@ class VersionParserTest extends TestCase { /** * @return array */ - public function versionProvider() { + public static function versionProvider(): array { return [ [ '*', @@ -66,7 +66,7 @@ class VersionParserTest extends TestCase { $this->assertEquals($expected, $this->versionParser->getVersion($input)); } - + public function testGetVersionException(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('Version cannot be parsed: BogusVersion'); @@ -74,7 +74,7 @@ class VersionParserTest extends TestCase { $this->versionParser->getVersion('BogusVersion'); } - + public function testGetVersionExceptionWithMultiple(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('Version cannot be parsed: >=8.2 <=9.1a'); diff --git a/tests/lib/App/CompareVersionTest.php b/tests/lib/App/CompareVersionTest.php index 0d020428fed..f357e47d670 100644 --- a/tests/lib/App/CompareVersionTest.php +++ b/tests/lib/App/CompareVersionTest.php @@ -23,7 +23,7 @@ class CompareVersionTest extends TestCase { $this->compare = new CompareVersion(); } - public function comparisonData() { + public static function comparisonData(): array { return [ // Compatible versions ['13.0.0.3', '13.0.0', '>=', true], diff --git a/tests/lib/App/DependencyAnalyzerTest.php b/tests/lib/App/DependencyAnalyzerTest.php index 31eeb77d7e5..d3874b5bb60 100644 --- a/tests/lib/App/DependencyAnalyzerTest.php +++ b/tests/lib/App/DependencyAnalyzerTest.php @@ -195,7 +195,7 @@ class DependencyAnalyzerTest extends TestCase { /** * @return array */ - public function providesOC() { + public static function providesOC(): array { return [ // no version -> no missing dependency [ @@ -423,7 +423,7 @@ class DependencyAnalyzerTest extends TestCase { /** * @return array */ - public function providesOS() { + public static function providesOS(): array { return [ [[], null], [[], []], @@ -435,7 +435,7 @@ class DependencyAnalyzerTest extends TestCase { /** * @return array */ - public function providesLibs() { + public static function providesLibs(): array { return [ // we expect curl to exist [[], 'curl'], @@ -465,7 +465,7 @@ class DependencyAnalyzerTest extends TestCase { /** * @return array */ - public function providesCommands() { + public static function providesCommands(): array { return [ [[], null], // grep is known on linux @@ -483,7 +483,7 @@ class DependencyAnalyzerTest extends TestCase { /** * @return array */ - public function providesDatabases() { + public static function providesDatabases(): array { return [ // non BC - in case on databases are defined -> all are supported [[], null], @@ -496,7 +496,7 @@ class DependencyAnalyzerTest extends TestCase { /** * @return array */ - public function providesPhpVersion() { + public static function providesPhpVersion(): array { return [ [[], null, null, null], [[], '5.4', null, null], diff --git a/tests/lib/App/InfoParserTest.php b/tests/lib/App/InfoParserTest.php index 1c429ccc405..3611a562a74 100644 --- a/tests/lib/App/InfoParserTest.php +++ b/tests/lib/App/InfoParserTest.php @@ -45,7 +45,7 @@ class InfoParserTest extends TestCase { $this->parserTest($expectedJson, $xmlFile, self::$cache); } - public function providesInfoXml(): array { + public static function providesInfoXml(): array { return [ ['expected-info.json', 'valid-info.xml'], [null, 'invalid-info.xml'], diff --git a/tests/lib/App/PlatformRepositoryTest.php b/tests/lib/App/PlatformRepositoryTest.php index 921d24159c9..8f621eebce9 100644 --- a/tests/lib/App/PlatformRepositoryTest.php +++ b/tests/lib/App/PlatformRepositoryTest.php @@ -20,7 +20,7 @@ class PlatformRepositoryTest extends \Test\TestCase { $this->assertEquals($expected, $normalizedVersion); } - public function providesVersions() { + public static function providesVersions(): array { return [ 'none' => ['1.0.0', '1.0.0.0'], 'none/2' => ['1.2.3.4', '1.2.3.4'], diff --git a/tests/lib/AppConfigTest.php b/tests/lib/AppConfigTest.php index 518d7909d70..faeaa4c4560 100644 --- a/tests/lib/AppConfigTest.php +++ b/tests/lib/AppConfigTest.php @@ -32,10 +32,10 @@ class AppConfigTest extends TestCase { private array $originalConfig; /** - * @var array<string, array<array<string, string, int, bool, bool>>> - * [appId => [configKey, configValue, valueType, lazy, sensitive]] + * @var array<string, array<string, array<string, string, int, bool, bool>>> + * [appId => [configKey, configValue, valueType, lazy, sensitive]] */ - private array $baseStruct = + private static array $baseStruct = [ 'testapp' => [ 'enabled' => ['enabled', 'true'], @@ -114,14 +114,14 @@ class AppConfigTest extends TestCase { ] ); - foreach ($this->baseStruct as $appId => $appData) { + foreach (self::$baseStruct as $appId => $appData) { foreach ($appData as $key => $row) { $value = $row[1]; $type = $row[2] ?? IAppConfig::VALUE_MIXED; if (($row[4] ?? false) === true) { $type |= IAppConfig::VALUE_SENSITIVE; $value = self::invokePrivate(AppConfig::class, 'ENCRYPTION_PREFIX') . $this->crypto->encrypt($value); - $this->baseStruct[$appId][$key]['encrypted'] = $value; + self::$baseStruct[$appId][$key]['encrypted'] = $value; } $sql->setParameters( @@ -197,7 +197,7 @@ class AppConfigTest extends TestCase { $this->assertSame(true, $status['fastLoaded'], $msg); $this->assertSame(false, $status['lazyLoaded'], $msg); - $apps = array_values(array_diff(array_keys($this->baseStruct), ['only-lazy'])); + $apps = array_values(array_diff(array_keys(self::$baseStruct), ['only-lazy'])); $this->assertEqualsCanonicalizing($apps, array_keys($status['fastCache']), $msg); $this->assertSame([], array_keys($status['lazyCache']), $msg); } @@ -208,7 +208,7 @@ class AppConfigTest extends TestCase { public function testGetApps(): void { $config = $this->generateAppConfig(false); - $this->assertEqualsCanonicalizing(array_keys($this->baseStruct), $config->getApps()); + $this->assertEqualsCanonicalizing(array_keys(self::$baseStruct), $config->getApps()); } /** @@ -217,9 +217,9 @@ class AppConfigTest extends TestCase { * @return array<string, string[]> ['appId' => ['key1', 'key2', ]] * @see testGetKeys */ - public function providerGetAppKeys(): array { + public static function providerGetAppKeys(): array { $appKeys = []; - foreach ($this->baseStruct as $appId => $appData) { + foreach (self::$baseStruct as $appId => $appData) { $keys = []; foreach ($appData as $row) { $keys[] = $row[0]; @@ -238,9 +238,9 @@ class AppConfigTest extends TestCase { * @see testIsLazy * @see testGetKeys */ - public function providerGetKeys(): array { + public static function providerGetKeys(): array { $appKeys = []; - foreach ($this->baseStruct as $appId => $appData) { + foreach (self::$baseStruct as $appId => $appData) { foreach ($appData as $row) { $appKeys[] = [ (string)$appId, $row[0], $row[1], $row[2] ?? IAppConfig::VALUE_MIXED, $row[3] ?? false, @@ -283,7 +283,7 @@ class AppConfigTest extends TestCase { public function testHasKeyOnNonExistentKeyReturnsFalse(): void { $config = $this->generateAppConfig(); - $this->assertEquals(false, $config->hasKey(array_keys($this->baseStruct)[0], 'inexistant-key')); + $this->assertEquals(false, $config->hasKey(array_keys(self::$baseStruct)[0], 'inexistant-key')); } public function testHasKeyOnUnknownAppReturnsFalse(): void { @@ -319,7 +319,7 @@ class AppConfigTest extends TestCase { public function testIsSensitiveOnNonExistentKeyThrowsException(): void { $config = $this->generateAppConfig(); $this->expectException(AppConfigUnknownKeyException::class); - $config->isSensitive(array_keys($this->baseStruct)[0], 'inexistant-key'); + $config->isSensitive(array_keys(self::$baseStruct)[0], 'inexistant-key'); } public function testIsSensitiveOnUnknownAppThrowsException(): void { @@ -362,7 +362,7 @@ class AppConfigTest extends TestCase { public function testIsLazyOnNonExistentKeyThrowsException(): void { $config = $this->generateAppConfig(); $this->expectException(AppConfigUnknownKeyException::class); - $config->isLazy(array_keys($this->baseStruct)[0], 'inexistant-key'); + $config->isLazy(array_keys(self::$baseStruct)[0], 'inexistant-key'); } public function testIsLazyOnUnknownAppThrowsException(): void { @@ -530,7 +530,7 @@ class AppConfigTest extends TestCase { * * @see testGetValueMixed */ - public function providerGetValueMixed(): array { + public static function providerGetValueMixed(): array { return [ // key, value, type ['mixed', 'mix', IAppConfig::VALUE_MIXED], diff --git a/tests/lib/AppFramework/AppTest.php b/tests/lib/AppFramework/AppTest.php index 3c535a4bf7a..87c96fdb9a8 100644 --- a/tests/lib/AppFramework/AppTest.php +++ b/tests/lib/AppFramework/AppTest.php @@ -124,7 +124,7 @@ class AppTest extends \Test\TestCase { App::main($this->controllerName, $this->controllerMethod, $this->container, []); } - public function dataNoOutput() { + public static function dataNoOutput(): array { return [ ['HTTP/2.0 204 No content'], ['HTTP/2.0 304 Not modified'], diff --git a/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php b/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php index 1e0b13b5755..6469a01cce3 100644 --- a/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php +++ b/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php @@ -156,7 +156,7 @@ class RegistrationContextTest extends TestCase { ); } - public function dataProvider_TrueFalse() { + public static function dataProvider_TrueFalse(): array { return[ [true], [false] diff --git a/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php b/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php index d6e0321023e..bcc0daf002f 100644 --- a/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php +++ b/tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php @@ -38,7 +38,7 @@ class AuthPublicShareControllerTest extends \Test\TestCase { $this->request, $this->session, $this->urlGenerator - ])->setMethods([ + ])->onlyMethods([ 'authFailed', 'getPasswordHash', 'isAuthenticated', @@ -64,7 +64,9 @@ class AuthPublicShareControllerTest extends \Test\TestCase { $this->controller->setToken('myToken'); $this->session->method('get') - ->willReturnMap(['public_link_authenticate_redirect', ['foo' => 'bar']]); + ->willReturnMap([ + ['public_link_authenticate_redirect', json_encode(['foo' => 'bar'])], + ]); $this->urlGenerator->method('linkToRoute') ->willReturn('myLink!'); @@ -107,7 +109,9 @@ class AuthPublicShareControllerTest extends \Test\TestCase { $this->session->expects($this->once()) ->method('regenerateId'); $this->session->method('get') - ->willReturnMap(['public_link_authenticate_redirect', ['foo' => 'bar']]); + ->willReturnMap([ + ['public_link_authenticate_redirect', json_encode(['foo' => 'bar'])], + ]); $tokenSet = false; $hashSet = false; diff --git a/tests/lib/AppFramework/Controller/ControllerTest.php b/tests/lib/AppFramework/Controller/ControllerTest.php index 7c466e3a5b7..aa016872847 100644 --- a/tests/lib/AppFramework/Controller/ControllerTest.php +++ b/tests/lib/AppFramework/Controller/ControllerTest.php @@ -66,7 +66,7 @@ class ControllerTest extends \Test\TestCase { ); $this->app = $this->getMockBuilder(DIContainer::class) - ->setMethods(['getAppName']) + ->onlyMethods(['getAppName']) ->setConstructorArgs(['test']) ->getMock(); $this->app->expects($this->any()) diff --git a/tests/lib/AppFramework/Controller/PublicShareControllerTest.php b/tests/lib/AppFramework/Controller/PublicShareControllerTest.php index f8430d42ef1..6f0e433f2fb 100644 --- a/tests/lib/AppFramework/Controller/PublicShareControllerTest.php +++ b/tests/lib/AppFramework/Controller/PublicShareControllerTest.php @@ -57,7 +57,7 @@ class PublicShareControllerTest extends \Test\TestCase { $this->assertEquals('test', $controller->getToken()); } - public function dataIsAuthenticated() { + public static function dataIsAuthenticated(): array { return [ [false, 'token1', 'token1', 'hash1', 'hash1', true], [false, 'token1', 'token1', 'hash1', 'hash2', true], diff --git a/tests/lib/AppFramework/Db/EntityTest.php b/tests/lib/AppFramework/Db/EntityTest.php index 3c844780b07..ccd0ae4bbaf 100644 --- a/tests/lib/AppFramework/Db/EntityTest.php +++ b/tests/lib/AppFramework/Db/EntityTest.php @@ -211,7 +211,7 @@ class EntityTest extends \Test\TestCase { } - public function dataSetterCasts(): array { + public static function dataSetterCasts(): array { return [ ['Id', '3', 3], ['smallInt', '3', 3], diff --git a/tests/lib/AppFramework/Db/QBMapperTest.php b/tests/lib/AppFramework/Db/QBMapperTest.php index 3cf32e56f12..c1d8bf07234 100644 --- a/tests/lib/AppFramework/Db/QBMapperTest.php +++ b/tests/lib/AppFramework/Db/QBMapperTest.php @@ -99,7 +99,7 @@ class QBMapperTest extends \Test\TestCase { $this->mapper = new QBTestMapper($this->db); } - + public function testInsertEntityParameterTypeMapping(): void { $datetime = new \DateTimeImmutable(); $entity = new QBTestEntity(); @@ -117,31 +117,40 @@ class QBMapperTest extends \Test\TestCase { $booleanParam = $this->qb->createNamedParameter('boolean_prop', IQueryBuilder::PARAM_BOOL); $datetimeParam = $this->qb->createNamedParameter('datetime_prop', IQueryBuilder::PARAM_DATETIME_IMMUTABLE); + $createNamedParameterCalls = [ + [123, IQueryBuilder::PARAM_INT, null], + [true, IQueryBuilder::PARAM_BOOL, null], + ['string', IQueryBuilder::PARAM_STR, null], + [456, IQueryBuilder::PARAM_INT, null], + [false, IQueryBuilder::PARAM_BOOL, null], + [$datetime, IQueryBuilder::PARAM_DATETIME_IMMUTABLE, null], + ]; $this->qb->expects($this->exactly(6)) ->method('createNamedParameter') - ->withConsecutive( - [$this->equalTo(123), $this->equalTo(IQueryBuilder::PARAM_INT)], - [$this->equalTo(true), $this->equalTo(IQueryBuilder::PARAM_BOOL)], - [$this->equalTo('string'), $this->equalTo(IQueryBuilder::PARAM_STR)], - [$this->equalTo(456), $this->equalTo(IQueryBuilder::PARAM_INT)], - [$this->equalTo(false), $this->equalTo(IQueryBuilder::PARAM_BOOL)], - [$this->equalTo($datetime), $this->equalTo(IQueryBuilder::PARAM_DATETIME_IMMUTABLE)], - ); + ->willReturnCallback(function () use (&$createNamedParameterCalls) { + $expected = array_shift($createNamedParameterCalls); + $this->assertEquals($expected, func_get_args()); + }); + + $setValueCalls = [ + ['int_prop', $intParam], + ['bool_prop', $boolParam], + ['string_prop', $stringParam], + ['integer_prop', $integerParam], + ['boolean_prop', $booleanParam], + ['datetime_prop', $datetimeParam], + ]; $this->qb->expects($this->exactly(6)) ->method('setValue') - ->withConsecutive( - [$this->equalTo('int_prop'), $this->equalTo($intParam)], - [$this->equalTo('bool_prop'), $this->equalTo($boolParam)], - [$this->equalTo('string_prop'), $this->equalTo($stringParam)], - [$this->equalTo('integer_prop'), $this->equalTo($integerParam)], - [$this->equalTo('boolean_prop'), $this->equalTo($booleanParam)], - [$this->equalTo('datetime_prop'), $this->equalTo($datetimeParam)], - ); + ->willReturnCallback(function () use (&$setValueCalls) { + $expected = array_shift($setValueCalls); + $this->assertEquals($expected, func_get_args()); + }); $this->mapper->insert($entity); } - + public function testUpdateEntityParameterTypeMapping(): void { $datetime = new \DateTimeImmutable(); $entity = new QBTestEntity(); @@ -163,30 +172,38 @@ class QBMapperTest extends \Test\TestCase { $jsonParam = $this->qb->createNamedParameter('json_prop', IQueryBuilder::PARAM_JSON); $datetimeParam = $this->qb->createNamedParameter('datetime_prop', IQueryBuilder::PARAM_DATETIME_IMMUTABLE); + $createNamedParameterCalls = [ + [123, IQueryBuilder::PARAM_INT, null], + [true, IQueryBuilder::PARAM_BOOL, null], + ['string', IQueryBuilder::PARAM_STR, null], + [456, IQueryBuilder::PARAM_INT, null], + [false, IQueryBuilder::PARAM_BOOL, null], + [['hello' => 'world'], IQueryBuilder::PARAM_JSON, null], + [$datetime, IQueryBuilder::PARAM_DATETIME_IMMUTABLE, null], + [789, IQueryBuilder::PARAM_INT, null], + ]; $this->qb->expects($this->exactly(8)) ->method('createNamedParameter') - ->withConsecutive( - [$this->equalTo(123), $this->equalTo(IQueryBuilder::PARAM_INT)], - [$this->equalTo(true), $this->equalTo(IQueryBuilder::PARAM_BOOL)], - [$this->equalTo('string'), $this->equalTo(IQueryBuilder::PARAM_STR)], - [$this->equalTo(456), $this->equalTo(IQueryBuilder::PARAM_INT)], - [$this->equalTo(false), $this->equalTo(IQueryBuilder::PARAM_BOOL)], - [$this->equalTo(['hello' => 'world']), $this->equalTo(IQueryBuilder::PARAM_JSON)], - [$this->equalTo($datetime), $this->equalTo(IQueryBuilder::PARAM_DATETIME_IMMUTABLE)], - [$this->equalTo(789), $this->equalTo(IQueryBuilder::PARAM_INT)], - ); - + ->willReturnCallback(function () use (&$createNamedParameterCalls) { + $expected = array_shift($createNamedParameterCalls); + $this->assertEquals($expected, func_get_args()); + }); + + $setCalls = [ + ['int_prop', $intParam], + ['bool_prop', $boolParam], + ['string_prop', $stringParam], + ['integer_prop', $integerParam], + ['boolean_prop', $booleanParam], + ['json_prop', $datetimeParam], + ['datetime_prop', $datetimeParam], + ]; $this->qb->expects($this->exactly(7)) ->method('set') - ->withConsecutive( - [$this->equalTo('int_prop'), $this->equalTo($intParam)], - [$this->equalTo('bool_prop'), $this->equalTo($boolParam)], - [$this->equalTo('string_prop'), $this->equalTo($stringParam)], - [$this->equalTo('integer_prop'), $this->equalTo($integerParam)], - [$this->equalTo('boolean_prop'), $this->equalTo($booleanParam)], - [$this->equalTo('json_prop'), $this->equalTo($jsonParam)], - [$this->equalTo('datetime_prop'), $this->equalTo($datetimeParam)], - ); + ->willReturnCallback(function () use (&$setCalls) { + $expected = array_shift($setCalls); + $this->assertEquals($expected, func_get_args()); + }); $this->expr->expects($this->once()) ->method('eq') @@ -196,7 +213,7 @@ class QBMapperTest extends \Test\TestCase { $this->mapper->update($entity); } - + public function testGetParameterTypeForProperty(): void { $entity = new QBTestEntity(); diff --git a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php index f3d2cff1ffd..e84b44db9a0 100644 --- a/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php +++ b/tests/lib/AppFramework/DependencyInjection/DIContainerTest.php @@ -29,7 +29,7 @@ class DIContainerTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); $this->container = $this->getMockBuilder(DIContainer::class) - ->setMethods(['isAdminUser']) + ->onlyMethods(['isAdminUser']) ->setConstructorArgs(['name']) ->getMock(); } diff --git a/tests/lib/AppFramework/Http/DispatcherTest.php b/tests/lib/AppFramework/Http/DispatcherTest.php index 7415ecd9486..404d3f4c90b 100644 --- a/tests/lib/AppFramework/Http/DispatcherTest.php +++ b/tests/lib/AppFramework/Http/DispatcherTest.php @@ -8,6 +8,7 @@ namespace Test\AppFramework\Http; +use OC\AppFramework\DependencyInjection\DIContainer; use OC\AppFramework\Http\Dispatcher; use OC\AppFramework\Http\Request; use OC\AppFramework\Middleware\MiddlewareDispatcher; @@ -20,6 +21,7 @@ use OCP\AppFramework\Http\ParameterOutOfRangeException; use OCP\AppFramework\Http\Response; use OCP\Diagnostics\IEventLogger; use OCP\IConfig; +use OCP\IDBConnection; use OCP\IRequest; use OCP\IRequestId; use PHPUnit\Framework\MockObject\MockObject; @@ -63,6 +65,10 @@ class TestController extends Controller { 'text' => [$int, $bool, $test, $test2] ]); } + + public function test(): Response { + return new DataResponse(); + } } /** @@ -104,33 +110,17 @@ class DispatcherTest extends \Test\TestCase { $this->logger = $this->createMock(LoggerInterface::class); $this->eventLogger = $this->createMock(IEventLogger::class); $this->container = $this->createMock(ContainerInterface::class); - $app = $this->getMockBuilder( - 'OC\AppFramework\DependencyInjection\DIContainer') - ->disableOriginalConstructor() - ->getMock(); - $request = $this->getMockBuilder( - '\OC\AppFramework\Http\Request') - ->disableOriginalConstructor() - ->getMock(); - $this->http = $this->getMockBuilder( - \OC\AppFramework\Http::class) - ->disableOriginalConstructor() - ->getMock(); + $app = $this->createMock(DIContainer::class); + $request = $this->createMock(Request::class); + $this->http = $this->createMock(\OC\AppFramework\Http::class); - $this->middlewareDispatcher = $this->getMockBuilder( - '\OC\AppFramework\Middleware\MiddlewareDispatcher') - ->disableOriginalConstructor() - ->getMock(); - $this->controller = $this->getMockBuilder( - '\OCP\AppFramework\Controller') - ->setMethods([$this->controllerMethod]) + $this->middlewareDispatcher = $this->createMock(MiddlewareDispatcher::class); + $this->controller = $this->getMockBuilder(TestController::class) + ->onlyMethods([$this->controllerMethod]) ->setConstructorArgs([$app, $request]) ->getMock(); - $this->request = $this->getMockBuilder( - '\OC\AppFramework\Http\Request') - ->disableOriginalConstructor() - ->getMock(); + $this->request = $this->createMock(Request::class); $this->reflector = new ControllerMethodReflector(); @@ -140,7 +130,7 @@ class DispatcherTest extends \Test\TestCase { $this->reflector, $this->request, $this->config, - \OC::$server->getDatabaseConnection(), + \OCP\Server::get(IDBConnection::class), $this->logger, $this->eventLogger, $this->container, @@ -545,7 +535,7 @@ class DispatcherTest extends \Test\TestCase { } - public function rangeDataProvider(): array { + public static function rangeDataProvider(): array { return [ [PHP_INT_MIN, PHP_INT_MAX, 42, false], [0, 12, -5, true], diff --git a/tests/lib/AppFramework/Http/DownloadResponseTest.php b/tests/lib/AppFramework/Http/DownloadResponseTest.php index ee89e8e55d1..cf179ba270b 100644 --- a/tests/lib/AppFramework/Http/DownloadResponseTest.php +++ b/tests/lib/AppFramework/Http/DownloadResponseTest.php @@ -37,7 +37,7 @@ class DownloadResponseTest extends \Test\TestCase { $this->assertEquals('attachment; filename="' . $expected . '"', $headers['Content-Disposition']); } - public function filenameEncodingProvider() : array { + public static function filenameEncodingProvider() : array { return [ ['TestName.txt', 'TestName.txt'], ['A "Quoted" Filename.txt', 'A \\"Quoted\\" Filename.txt'], diff --git a/tests/lib/AppFramework/Http/JSONResponseTest.php b/tests/lib/AppFramework/Http/JSONResponseTest.php index 175ed852c7b..703e6d89dd1 100644 --- a/tests/lib/AppFramework/Http/JSONResponseTest.php +++ b/tests/lib/AppFramework/Http/JSONResponseTest.php @@ -46,10 +46,7 @@ class JSONResponseTest extends \Test\TestCase { $this->assertEquals($expected, $this->json->render()); } - /** - * @return array - */ - public function renderDataProvider() { + public static function renderDataProvider(): array { return [ [ ['test' => 'hi'], '{"test":"hi"}', diff --git a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php index fae5f5d9f1c..a8273be362b 100644 --- a/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php +++ b/tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php @@ -10,6 +10,7 @@ namespace Test\AppFramework\Middleware; use OC\AppFramework\Http\Request; use OC\AppFramework\Middleware\MiddlewareDispatcher; +use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; use OCP\IConfig; @@ -84,6 +85,10 @@ class TestMiddleware extends Middleware { } } +class TestController extends Controller { + public function method(): void { + } +} class MiddlewareDispatcherTest extends \Test\TestCase { public $exception; @@ -110,8 +115,8 @@ class MiddlewareDispatcherTest extends \Test\TestCase { private function getControllerMock() { - return $this->getMockBuilder('OCP\AppFramework\Controller') - ->setMethods(['method']) + return $this->getMockBuilder(TestController::class) + ->onlyMethods(['method']) ->setConstructorArgs(['app', new Request( ['method' => 'GET'], @@ -131,14 +136,14 @@ class MiddlewareDispatcherTest extends \Test\TestCase { public function testAfterExceptionShouldReturnResponseOfMiddleware(): void { $response = new Response(); - $m1 = $this->getMockBuilder('\OCP\AppFramework\Middleware') - ->setMethods(['afterException', 'beforeController']) + $m1 = $this->getMockBuilder(\OCP\AppFramework\Middleware::class) + ->onlyMethods(['afterException', 'beforeController']) ->getMock(); $m1->expects($this->never()) ->method('afterException'); - $m2 = $this->getMockBuilder('OCP\AppFramework\Middleware') - ->setMethods(['afterException', 'beforeController']) + $m2 = $this->getMockBuilder(\OCP\AppFramework\Middleware::class) + ->onlyMethods(['afterException', 'beforeController']) ->getMock(); $m2->expects($this->once()) ->method('afterException') diff --git a/tests/lib/AppFramework/Middleware/MiddlewareTest.php b/tests/lib/AppFramework/Middleware/MiddlewareTest.php index c1e5c44c4db..addd9683122 100644 --- a/tests/lib/AppFramework/Middleware/MiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/MiddlewareTest.php @@ -36,12 +36,9 @@ class MiddlewareTest extends \Test\TestCase { $this->middleware = new ChildMiddleware(); - $this->api = $this->getMockBuilder(DIContainer::class) - ->disableOriginalConstructor() - ->getMock(); + $this->api = $this->createMock(DIContainer::class); $this->controller = $this->getMockBuilder(Controller::class) - ->setMethods([]) ->setConstructorArgs([ $this->api, new Request( @@ -51,7 +48,7 @@ class MiddlewareTest extends \Test\TestCase { ) ])->getMock(); $this->exception = new \Exception(); - $this->response = $this->getMockBuilder(Response::class)->getMock(); + $this->response = $this->createMock(Response::class); } diff --git a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php index 58ae6b13aed..204cc647cad 100644 --- a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php @@ -32,7 +32,7 @@ class NotModifiedMiddlewareTest extends \Test\TestCase { $this->controller = $this->createMock(Controller::class); } - public function dataModified(): array { + public static function dataModified(): array { $now = new \DateTime(); return [ diff --git a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php index 6724f841c5e..62e20a2dcd0 100644 --- a/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php @@ -12,6 +12,7 @@ use OC\AppFramework\OCS\V1Response; use OC\AppFramework\OCS\V2Response; use OCP\AppFramework\Controller; use OCP\AppFramework\Http; +use OCP\AppFramework\Http\Response; use OCP\AppFramework\OCS\OCSBadRequestException; use OCP\AppFramework\OCS\OCSException; use OCP\AppFramework\OCS\OCSForbiddenException; @@ -32,49 +33,37 @@ class OCSMiddlewareTest extends \Test\TestCase { ->getMock(); } - public function dataAfterException() { - $OCSController = $this->getMockBuilder(OCSController::class) - ->disableOriginalConstructor() - ->getMock(); - $controller = $this->getMockBuilder(Controller::class) - ->disableOriginalConstructor() - ->getMock(); - + public static function dataAfterException(): array { return [ - [$OCSController, new \Exception(), true], - [$OCSController, new OCSException(), false, '', Http::STATUS_INTERNAL_SERVER_ERROR], - [$OCSController, new OCSException('foo'), false, 'foo', Http::STATUS_INTERNAL_SERVER_ERROR], - [$OCSController, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), false, 'foo', Http::STATUS_IM_A_TEAPOT], - [$OCSController, new OCSBadRequestException(), false, '', Http::STATUS_BAD_REQUEST], - [$OCSController, new OCSBadRequestException('foo'), false, 'foo', Http::STATUS_BAD_REQUEST], - [$OCSController, new OCSForbiddenException(), false, '', Http::STATUS_FORBIDDEN], - [$OCSController, new OCSForbiddenException('foo'), false, 'foo', Http::STATUS_FORBIDDEN], - [$OCSController, new OCSNotFoundException(), false, '', Http::STATUS_NOT_FOUND], - [$OCSController, new OCSNotFoundException('foo'), false, 'foo', Http::STATUS_NOT_FOUND], - - [$controller, new \Exception(), true], - [$controller, new OCSException(), true], - [$controller, new OCSException('foo'), true], - [$controller, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), true], - [$controller, new OCSBadRequestException(), true], - [$controller, new OCSBadRequestException('foo'), true], - [$controller, new OCSForbiddenException(), true], - [$controller, new OCSForbiddenException('foo'), true], - [$controller, new OCSNotFoundException(), true], - [$controller, new OCSNotFoundException('foo'), true], + [OCSController::class, new \Exception(), true], + [OCSController::class, new OCSException(), false, '', Http::STATUS_INTERNAL_SERVER_ERROR], + [OCSController::class, new OCSException('foo'), false, 'foo', Http::STATUS_INTERNAL_SERVER_ERROR], + [OCSController::class, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), false, 'foo', Http::STATUS_IM_A_TEAPOT], + [OCSController::class, new OCSBadRequestException(), false, '', Http::STATUS_BAD_REQUEST], + [OCSController::class, new OCSBadRequestException('foo'), false, 'foo', Http::STATUS_BAD_REQUEST], + [OCSController::class, new OCSForbiddenException(), false, '', Http::STATUS_FORBIDDEN], + [OCSController::class, new OCSForbiddenException('foo'), false, 'foo', Http::STATUS_FORBIDDEN], + [OCSController::class, new OCSNotFoundException(), false, '', Http::STATUS_NOT_FOUND], + [OCSController::class, new OCSNotFoundException('foo'), false, 'foo', Http::STATUS_NOT_FOUND], + + [Controller::class, new \Exception(), true], + [Controller::class, new OCSException(), true], + [Controller::class, new OCSException('foo'), true], + [Controller::class, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), true], + [Controller::class, new OCSBadRequestException(), true], + [Controller::class, new OCSBadRequestException('foo'), true], + [Controller::class, new OCSForbiddenException(), true], + [Controller::class, new OCSForbiddenException('foo'), true], + [Controller::class, new OCSNotFoundException(), true], + [Controller::class, new OCSNotFoundException('foo'), true], ]; } /** * @dataProvider dataAfterException - * - * @param Controller $controller - * @param \Exception $exception - * @param bool $forward - * @param string $message - * @param int $code */ - public function testAfterExceptionOCSv1($controller, $exception, $forward, $message = '', $code = 0): void { + public function testAfterExceptionOCSv1(string $controller, \Exception $exception, bool $forward, string $message = '', int $code = 0): void { + $controller = $this->createMock($controller); $this->request ->method('getScriptName') ->willReturn('/ocs/v1.php'); @@ -103,14 +92,9 @@ class OCSMiddlewareTest extends \Test\TestCase { /** * @dataProvider dataAfterException - * - * @param Controller $controller - * @param \Exception $exception - * @param bool $forward - * @param string $message - * @param int $code */ - public function testAfterExceptionOCSv2($controller, $exception, $forward, $message = '', $code = 0): void { + public function testAfterExceptionOCSv2(string $controller, \Exception $exception, bool $forward, string $message = '', int $code = 0): void { + $controller = $this->createMock($controller); $this->request ->method('getScriptName') ->willReturn('/ocs/v2.php'); @@ -137,14 +121,9 @@ class OCSMiddlewareTest extends \Test\TestCase { /** * @dataProvider dataAfterException - * - * @param Controller $controller - * @param \Exception $exception - * @param bool $forward - * @param string $message - * @param int $code */ - public function testAfterExceptionOCSv2SubFolder($controller, $exception, $forward, $message = '', $code = 0): void { + public function testAfterExceptionOCSv2SubFolder(string $controller, \Exception $exception, bool $forward, string $message = '', int $code = 0): void { + $controller = $this->createMock($controller); $this->request ->method('getScriptName') ->willReturn('/mysubfolder/ocs/v2.php'); @@ -152,7 +131,7 @@ class OCSMiddlewareTest extends \Test\TestCase { $OCSMiddleware->beforeController($controller, 'method'); if ($forward) { - $this->expectException(get_class($exception)); + $this->expectException($exception::class); $this->expectExceptionMessage($exception->getMessage()); } @@ -169,39 +148,28 @@ class OCSMiddlewareTest extends \Test\TestCase { $this->assertSame($code, $result->getStatus()); } - public function dataAfterController() { - $OCSController = $this->getMockBuilder(OCSController::class) - ->disableOriginalConstructor() - ->getMock(); - $controller = $this->getMockBuilder(Controller::class) - ->disableOriginalConstructor() - ->getMock(); - + public static function dataAfterController(): array { return [ - [$OCSController, new Http\Response(), false], - [$OCSController, new Http\JSONResponse(), false], - [$OCSController, new Http\JSONResponse(['message' => 'foo']), false], - [$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true, OCSController::RESPOND_UNAUTHORISED], - [$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true], - - [$controller, new Http\Response(), false], - [$controller, new Http\JSONResponse(), false], - [$controller, new Http\JSONResponse(['message' => 'foo']), false], - [$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false], - [$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false], + [OCSController::class, new Response(), false], + [OCSController::class, new Http\JSONResponse(), false], + [OCSController::class, new Http\JSONResponse(['message' => 'foo']), false], + [OCSController::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true, OCSController::RESPOND_UNAUTHORISED], + [OCSController::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true], + + [Controller::class, new Response(), false], + [Controller::class, new Http\JSONResponse(), false], + [Controller::class, new Http\JSONResponse(['message' => 'foo']), false], + [Controller::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false], + [Controller::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false], ]; } /** * @dataProvider dataAfterController - * - * @param Controller $controller - * @param Http\Response $response - * @param bool $converted - * @param int $convertedOCSStatus */ - public function testAfterController($controller, $response, $converted, $convertedOCSStatus = 0): void { + public function testAfterController(string $controller, Response $response, bool $converted, int $convertedOCSStatus = 0): void { + $controller = $this->createMock($controller); $OCSMiddleware = new OCSMiddleware($this->request); $newResponse = $OCSMiddleware->afterController($controller, 'foo', $response); diff --git a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php index 8433aa93f4a..bf0d719f46e 100644 --- a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php @@ -58,7 +58,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase { $this->assertTrue(true); } - public function dataShareApi() { + public static function dataShareApi(): array { return [ ['no', 'no',], ['no', 'yes',], diff --git a/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php index a224ebae949..c516c1e6c89 100644 --- a/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php @@ -98,13 +98,19 @@ class BruteForceMiddlewareTest extends TestCase { ->expects($this->once()) ->method('getRemoteAddress') ->willReturn('::1'); + + $calls = [ + ['::1', 'first'], + ['::1', 'second'], + ]; $this->throttler ->expects($this->exactly(2)) ->method('sleepDelayOrThrowOnMax') - ->withConsecutive( - ['::1', 'first'], - ['::1', 'second'], - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + return 0; + }); $controller = new TestController('test', $this->request); $this->reflector->reflect($controller, 'multipleAttributes'); @@ -221,20 +227,31 @@ class BruteForceMiddlewareTest extends TestCase { ->expects($this->once()) ->method('getRemoteAddress') ->willReturn('::1'); + + $sleepCalls = [ + ['::1', 'first'], + ['::1', 'second'], + ]; $this->throttler ->expects($this->exactly(2)) ->method('sleepDelayOrThrowOnMax') - ->withConsecutive( - ['::1', 'first'], - ['::1', 'second'], - ); + ->willReturnCallback(function () use (&$sleepCalls) { + $expected = array_shift($sleepCalls); + $this->assertEquals($expected, func_get_args()); + return 0; + }); + + $attemptCalls = [ + ['first', '::1', []], + ['second', '::1', []], + ]; $this->throttler ->expects($this->exactly(2)) ->method('registerAttempt') - ->withConsecutive( - ['first', '::1'], - ['second', '::1'], - ); + ->willReturnCallback(function () use (&$attemptCalls) { + $expected = array_shift($attemptCalls); + $this->assertEquals($expected, func_get_args()); + }); $controller = new TestController('test', $this->request); $this->reflector->reflect($controller, 'multipleAttributes'); diff --git a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php index b703b10c554..f22933a5884 100644 --- a/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php @@ -44,7 +44,7 @@ class CORSMiddlewareTest extends \Test\TestCase { ); } - public function dataSetCORSAPIHeader(): array { + public static function dataSetCORSAPIHeader(): array { return [ ['testSetCORSAPIHeader'], ['testSetCORSAPIHeaderAttribute'], @@ -89,7 +89,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers)); } - public function dataNoOriginHeaderNoCORSHEADER(): array { + public static function dataNoOriginHeaderNoCORSHEADER(): array { return [ ['testNoOriginHeaderNoCORSHEADER'], ['testNoOriginHeaderNoCORSHEADERAttribute'], @@ -113,7 +113,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers)); } - public function dataCorsIgnoredIfWithCredentialsHeaderPresent(): array { + public static function dataCorsIgnoredIfWithCredentialsHeaderPresent(): array { return [ ['testCorsIgnoredIfWithCredentialsHeaderPresent'], ['testCorsAttributeIgnoredIfWithCredentialsHeaderPresent'], @@ -143,7 +143,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $middleware->afterController($this->controller, $method, $response); } - public function dataNoCORSOnAnonymousPublicPage(): array { + public static function dataNoCORSOnAnonymousPublicPage(): array { return [ ['testNoCORSOnAnonymousPublicPage'], ['testNoCORSOnAnonymousPublicPageAttribute'], @@ -177,7 +177,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $middleware->beforeController($this->controller, $method); } - public function dataCORSShouldNeverAllowCookieAuth(): array { + public static function dataCORSShouldNeverAllowCookieAuth(): array { return [ ['testCORSShouldNeverAllowCookieAuth'], ['testCORSShouldNeverAllowCookieAuthAttribute'], @@ -211,7 +211,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $middleware->beforeController($this->controller, $method); } - public function dataCORSShouldRelogin(): array { + public static function dataCORSShouldRelogin(): array { return [ ['testCORSShouldRelogin'], ['testCORSAttributeShouldRelogin'], @@ -242,7 +242,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $middleware->beforeController($this->controller, $method); } - public function dataCORSShouldFailIfPasswordLoginIsForbidden(): array { + public static function dataCORSShouldFailIfPasswordLoginIsForbidden(): array { return [ ['testCORSShouldFailIfPasswordLoginIsForbidden'], ['testCORSAttributeShouldFailIfPasswordLoginIsForbidden'], @@ -275,7 +275,7 @@ class CORSMiddlewareTest extends \Test\TestCase { $middleware->beforeController($this->controller, $method); } - public function dataCORSShouldNotAllowCookieAuth(): array { + public static function dataCORSShouldNotAllowCookieAuth(): array { return [ ['testCORSShouldNotAllowCookieAuth'], ['testCORSAttributeShouldNotAllowCookieAuth'], diff --git a/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php index 3dec030d438..e607b19d1ef 100644 --- a/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php @@ -162,7 +162,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase { - public function dataProvider() { + public static function dataProvider(): array { return [ ['foo', 2000, 4000, true], ['foo', 2000, 3000, false], diff --git a/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php index 0ca4a455cba..44897fa21ef 100644 --- a/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php @@ -103,7 +103,7 @@ class SameSiteCookieMiddlewareTest extends TestCase { $middleware = $this->getMockBuilder(SameSiteCookieMiddleware::class) ->setConstructorArgs([$this->request, $this->reflector]) - ->setMethods(['setSameSiteCookie']) + ->onlyMethods(['setSameSiteCookie']) ->getMock(); $middleware->expects($this->once()) diff --git a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php index 07e368fd1e6..3b5861cbba9 100644 --- a/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php @@ -125,7 +125,7 @@ class SecurityMiddlewareTest extends \Test\TestCase { ); } - public function dataNoCSRFRequiredPublicPage(): array { + public static function dataNoCSRFRequiredPublicPage(): array { return [ ['testAnnotationNoCSRFRequiredPublicPage'], ['testAnnotationNoCSRFRequiredAttributePublicPage'], @@ -134,21 +134,21 @@ class SecurityMiddlewareTest extends \Test\TestCase { ]; } - public function dataPublicPage(): array { + public static function dataPublicPage(): array { return [ ['testAnnotationPublicPage'], ['testAttributePublicPage'], ]; } - public function dataNoCSRFRequired(): array { + public static function dataNoCSRFRequired(): array { return [ ['testAnnotationNoCSRFRequired'], ['testAttributeNoCSRFRequired'], ]; } - public function dataPublicPageStrictCookieRequired(): array { + public static function dataPublicPageStrictCookieRequired(): array { return [ ['testAnnotationPublicPageStrictCookieRequired'], ['testAnnotationStrictCookieRequiredAttributePublicPage'], @@ -157,28 +157,28 @@ class SecurityMiddlewareTest extends \Test\TestCase { ]; } - public function dataNoCSRFRequiredPublicPageStrictCookieRequired(): array { + public static function dataNoCSRFRequiredPublicPageStrictCookieRequired(): array { return [ ['testAnnotationNoCSRFRequiredPublicPageStrictCookieRequired'], ['testAttributeNoCSRFRequiredPublicPageStrictCookiesRequired'], ]; } - public function dataNoAdminRequiredNoCSRFRequired(): array { + public static function dataNoAdminRequiredNoCSRFRequired(): array { return [ ['testAnnotationNoAdminRequiredNoCSRFRequired'], ['testAttributeNoAdminRequiredNoCSRFRequired'], ]; } - public function dataNoAdminRequiredNoCSRFRequiredPublicPage(): array { + public static function dataNoAdminRequiredNoCSRFRequiredPublicPage(): array { return [ ['testAnnotationNoAdminRequiredNoCSRFRequiredPublicPage'], ['testAttributeNoAdminRequiredNoCSRFRequiredPublicPage'], ]; } - public function dataNoCSRFRequiredSubAdminRequired(): array { + public static function dataNoCSRFRequiredSubAdminRequired(): array { return [ ['testAnnotationNoCSRFRequiredSubAdminRequired'], ['testAnnotationNoCSRFRequiredAttributeSubAdminRequired'], @@ -429,7 +429,7 @@ class SecurityMiddlewareTest extends \Test\TestCase { $this->middleware->beforeController($this->controller, $method); } - public function dataCsrfOcsController(): array { + public static function dataCsrfOcsController(): array { return [ [NormalController::class, false, false, true], [NormalController::class, false, true, true], @@ -659,7 +659,7 @@ class SecurityMiddlewareTest extends \Test\TestCase { /** * @return array */ - public function exceptionProvider() { + public static function exceptionProvider(): array { return [ [ new AppNotEnabledException(), diff --git a/tests/lib/AppFramework/OCS/V2ResponseTest.php b/tests/lib/AppFramework/OCS/V2ResponseTest.php index 97a227418f3..0037763f163 100644 --- a/tests/lib/AppFramework/OCS/V2ResponseTest.php +++ b/tests/lib/AppFramework/OCS/V2ResponseTest.php @@ -23,7 +23,7 @@ class V2ResponseTest extends \Test\TestCase { $this->assertEquals($expected, $response->getStatus()); } - public function providesStatusCodes(): array { + public static function providesStatusCodes(): array { return [ [Http::STATUS_OK, 200], [Http::STATUS_BAD_REQUEST, 104], diff --git a/tests/lib/AppFramework/Routing/RoutingTest.php b/tests/lib/AppFramework/Routing/RoutingTest.php index 8522382ddcc..703e613f790 100644 --- a/tests/lib/AppFramework/Routing/RoutingTest.php +++ b/tests/lib/AppFramework/Routing/RoutingTest.php @@ -348,23 +348,24 @@ class RoutingTest extends \Test\TestCase { $urlWithParam = $url . '/{' . $paramName . '}'; + $calls = [ + ['name' => 'ocs.app1.' . $resourceName . '.index', 'pattern' => $url, 'route' => $indexRoute], + ['name' => 'ocs.app1.' . $resourceName . '.show', 'pattern' => $urlWithParam, 'route' => $showRoute], + ['name' => 'ocs.app1.' . $resourceName . '.create', 'pattern' => $url, 'route' => $createRoute], + ['name' => 'ocs.app1.' . $resourceName . '.update', 'pattern' => $urlWithParam, 'route' => $updateRoute], + ['name' => 'ocs.app1.' . $resourceName . '.destroy', 'pattern' => $urlWithParam, 'route' => $destroyRoute], + ]; + // we expect create to be called five times: $router ->expects($this->exactly(5)) ->method('create') - ->withConsecutive( - [$this->equalTo('ocs.app1.' . $resourceName . '.index'), $this->equalTo($url)], - [$this->equalTo('ocs.app1.' . $resourceName . '.show'), $this->equalTo($urlWithParam)], - [$this->equalTo('ocs.app1.' . $resourceName . '.create'), $this->equalTo($url)], - [$this->equalTo('ocs.app1.' . $resourceName . '.update'), $this->equalTo($urlWithParam)], - [$this->equalTo('ocs.app1.' . $resourceName . '.destroy'), $this->equalTo($urlWithParam)], - )->willReturnOnConsecutiveCalls( - $indexRoute, - $showRoute, - $createRoute, - $updateRoute, - $destroyRoute, - ); + ->willReturnCallback(function (string $name, string $pattern) use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected['name'], $name); + $this->assertEquals($expected['pattern'], $pattern); + return $expected['route']; + }); // load route configuration $config = new RouteConfig($container, $router, $yaml); @@ -402,23 +403,23 @@ class RoutingTest extends \Test\TestCase { $urlWithParam = $url . '/{' . $paramName . '}'; + $calls = [ + ['name' => 'app1.' . $resourceName . '.index', 'pattern' => $url, 'route' => $indexRoute], + ['name' => 'app1.' . $resourceName . '.show', 'pattern' => $urlWithParam, 'route' => $showRoute], + ['name' => 'app1.' . $resourceName . '.create', 'pattern' => $url, 'route' => $createRoute], + ['name' => 'app1.' . $resourceName . '.update', 'pattern' => $urlWithParam, 'route' => $updateRoute], + ['name' => 'app1.' . $resourceName . '.destroy', 'pattern' => $urlWithParam, 'route' => $destroyRoute], + ]; // we expect create to be called five times: $router ->expects($this->exactly(5)) ->method('create') - ->withConsecutive( - [$this->equalTo('app1.' . $resourceName . '.index'), $this->equalTo($url)], - [$this->equalTo('app1.' . $resourceName . '.show'), $this->equalTo($urlWithParam)], - [$this->equalTo('app1.' . $resourceName . '.create'), $this->equalTo($url)], - [$this->equalTo('app1.' . $resourceName . '.update'), $this->equalTo($urlWithParam)], - [$this->equalTo('app1.' . $resourceName . '.destroy'), $this->equalTo($urlWithParam)], - )->willReturnOnConsecutiveCalls( - $indexRoute, - $showRoute, - $createRoute, - $updateRoute, - $destroyRoute, - ); + ->willReturnCallback(function (string $name, string $pattern) use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected['name'], $name); + $this->assertEquals($expected['pattern'], $pattern); + return $expected['route']; + }); // load route configuration $config = new RouteConfig($container, $router, $yaml); diff --git a/tests/lib/AppFramework/Services/AppConfigTest.php b/tests/lib/AppFramework/Services/AppConfigTest.php index 46f73a8c088..718817a7636 100644 --- a/tests/lib/AppFramework/Services/AppConfigTest.php +++ b/tests/lib/AppFramework/Services/AppConfigTest.php @@ -28,7 +28,7 @@ class AppConfigTest extends TestCase { parent::setUp(); $this->config = $this->createMock(IConfig::class); $this->appConfigCore = $this->createMock(AppConfigCore::class); - + $this->appConfig = new AppConfig($this->config, $this->appConfigCore, self::TEST_APPID); } @@ -46,7 +46,7 @@ class AppConfigTest extends TestCase { * @return array * @see testHasAppKey */ - public function providerHasAppKey(): array { + public static function providerHasAppKey(): array { return [ // lazy, expected [false, true], @@ -76,7 +76,7 @@ class AppConfigTest extends TestCase { * @return array * @see testIsSensitive */ - public function providerIsSensitive(): array { + public static function providerIsSensitive(): array { return [ // lazy, expected [false, true], @@ -123,7 +123,7 @@ class AppConfigTest extends TestCase { * @return array * @see testIsLazy */ - public function providerIsLazy(): array { + public static function providerIsLazy(): array { return [ // expected [true], @@ -161,7 +161,7 @@ class AppConfigTest extends TestCase { * @return array * @see testGetAllAppValues */ - public function providerGetAllAppValues(): array { + public static function providerGetAllAppValues(): array { return [ // key, filtered ['', false], @@ -214,7 +214,7 @@ class AppConfigTest extends TestCase { * @see testSetAppValueArray * @see testSetAppValueArrayException */ - public function providerSetAppValue(): array { + public static function providerSetAppValue(): array { return [ // lazy, sensitive, expected [false, false, true], @@ -340,7 +340,7 @@ class AppConfigTest extends TestCase { * @return array * @see testSetAppValueBool */ - public function providerSetAppValueBool(): array { + public static function providerSetAppValueBool(): array { return [ // lazy, expected [false, true], @@ -456,7 +456,7 @@ class AppConfigTest extends TestCase { * @see testGetAppValueArray * @see testGetAppValueArrayException */ - public function providerGetAppValue(): array { + public static function providerGetAppValue(): array { return [ // lazy, exist [false, false], diff --git a/tests/lib/AppFramework/Utility/SimpleContainerTest.php b/tests/lib/AppFramework/Utility/SimpleContainerTest.php index d3e9dec18e0..754da8e5fb3 100644 --- a/tests/lib/AppFramework/Utility/SimpleContainerTest.php +++ b/tests/lib/AppFramework/Utility/SimpleContainerTest.php @@ -191,7 +191,7 @@ class SimpleContainerTest extends \Test\TestCase { $this->container->query('test'), $this->container->query('test1')); } - public function sanitizeNameProvider() { + public static function sanitizeNameProvider(): array { return [ ['ABC\\Foo', 'ABC\\Foo'], ['\\ABC\\Foo', '\\ABC\\Foo'], diff --git a/tests/lib/AppTest.php b/tests/lib/AppTest.php index 3e4d762a0a4..b817d968910 100644 --- a/tests/lib/AppTest.php +++ b/tests/lib/AppTest.php @@ -34,7 +34,7 @@ class AppTest extends \Test\TestCase { public const TEST_GROUP1 = 'group1'; public const TEST_GROUP2 = 'group2'; - public function appVersionsProvider() { + public static function appVersionsProvider(): array { return [ // exact match [ @@ -335,7 +335,7 @@ class AppTest extends \Test\TestCase { /** * Providers for the app config values */ - public function appConfigValuesProvider() { + public static function appConfigValuesProvider(): array { return [ // logged in user1 [ @@ -591,7 +591,7 @@ class AppTest extends \Test\TestCase { /** * Providers for the app data values */ - public function appDataProvider() { + public static function appDataProvider(): array { return [ [ ['description' => " \t This is a multiline \n test with \n \t \n \n some new lines "], diff --git a/tests/lib/Archive/ZIPTest.php b/tests/lib/Archive/ZIPTest.php index 25707e4b051..59fb91006a3 100644 --- a/tests/lib/Archive/ZIPTest.php +++ b/tests/lib/Archive/ZIPTest.php @@ -16,6 +16,10 @@ class ZIPTest extends TestBase { } protected function getNew() { - return new ZIP(\OC::$server->getTempManager()->getTempBaseDir() . '/newArchive.zip'); + $newZip = \OC::$server->getTempManager()->getTempBaseDir() . '/newArchive.zip'; + if (file_exists($newZip)) { + unlink($newZip); + } + return new ZIP($newZip); } } diff --git a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php index f91371a86b7..a7590cdd244 100644 --- a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php +++ b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php @@ -83,13 +83,18 @@ class UserDeletedTokenCleanupListenerTest extends TestCase { $token2, $token3, ]); + + $calls = [ + ['user123', 1], + ['user123', 2], + ['user123', 3], + ]; $this->manager->expects($this->exactly(3)) ->method('invalidateTokenById') - ->withConsecutive( - ['user123', 1], - ['user123', 2], - ['user123', 3] - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + }); $this->logger->expects($this->never()) ->method('error'); diff --git a/tests/lib/Authentication/Login/ALoginCommandTest.php b/tests/lib/Authentication/Login/ALoginTestCommand.php index 2ab59835bfe..502380bc3fe 100644 --- a/tests/lib/Authentication/Login/ALoginCommandTest.php +++ b/tests/lib/Authentication/Login/ALoginTestCommand.php @@ -8,14 +8,13 @@ declare(strict_types=1); namespace Test\Authentication\Login; -use OC\Authentication\Login\ALoginCommand; use OC\Authentication\Login\LoginData; use OCP\IRequest; use OCP\IUser; use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; -abstract class ALoginCommandTest extends TestCase { +abstract class ALoginTestCommand extends TestCase { /** @var IRequest|MockObject */ protected $request; @@ -36,7 +35,7 @@ abstract class ALoginCommandTest extends TestCase { /** @var IUser|MockObject */ protected $user; - /** @var ALoginCommand */ + /** @var ALoginTestCommand */ protected $cmd; protected function setUp(): void { diff --git a/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php b/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php index 025612e963e..5ff2da28946 100644 --- a/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php +++ b/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php @@ -13,7 +13,7 @@ use OC\Authentication\Login\ClearLostPasswordTokensCommand; use OCP\IConfig; use PHPUnit\Framework\MockObject\MockObject; -class ClearLostPasswordTokensCommandTest extends ALoginCommandTest { +class ClearLostPasswordTokensCommandTest extends ALoginTestCommand { /** @var IConfig|MockObject */ private $config; diff --git a/tests/lib/Authentication/Login/CompleteLoginCommandTest.php b/tests/lib/Authentication/Login/CompleteLoginCommandTest.php index 4ddb26e7648..5b08368671f 100644 --- a/tests/lib/Authentication/Login/CompleteLoginCommandTest.php +++ b/tests/lib/Authentication/Login/CompleteLoginCommandTest.php @@ -13,7 +13,7 @@ use OC\Authentication\Login\CompleteLoginCommand; use OC\User\Session; use PHPUnit\Framework\MockObject\MockObject; -class CompleteLoginCommandTest extends ALoginCommandTest { +class CompleteLoginCommandTest extends ALoginTestCommand { /** @var Session|MockObject */ private $session; diff --git a/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php b/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php index fd6a154ef5d..668c0a6d6ea 100644 --- a/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php +++ b/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php @@ -15,7 +15,7 @@ use OC\User\Session; use OCP\IConfig; use PHPUnit\Framework\MockObject\MockObject; -class CreateSessionTokenCommandTest extends ALoginCommandTest { +class CreateSessionTokenCommandTest extends ALoginTestCommand { /** @var IConfig|MockObject */ private $config; diff --git a/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php b/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php index 4eb4f94055f..499abafa6e3 100644 --- a/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php +++ b/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php @@ -14,7 +14,7 @@ use OC\User\Session; use OCP\IConfig; use PHPUnit\Framework\MockObject\MockObject; -class FinishRememberedLoginCommandTest extends ALoginCommandTest { +class FinishRememberedLoginCommandTest extends ALoginTestCommand { /** @var Session|MockObject */ private $userSession; /** @var IConfig|MockObject */ diff --git a/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php b/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php index ce783050921..7b011d70673 100644 --- a/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php +++ b/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php @@ -15,7 +15,7 @@ use OCP\EventDispatcher\IEventDispatcher; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; -class LoggedInCheckCommandTest extends ALoginCommandTest { +class LoggedInCheckCommandTest extends ALoginTestCommand { /** @var LoggerInterface|MockObject */ private $logger; diff --git a/tests/lib/Authentication/Login/PreLoginHookCommandTest.php b/tests/lib/Authentication/Login/PreLoginHookCommandTest.php index b6d826f1c21..0e5096baf55 100644 --- a/tests/lib/Authentication/Login/PreLoginHookCommandTest.php +++ b/tests/lib/Authentication/Login/PreLoginHookCommandTest.php @@ -14,7 +14,7 @@ use OC\User\Manager; use OCP\IUserManager; use PHPUnit\Framework\MockObject\MockObject; -class PreLoginHookCommandTest extends ALoginCommandTest { +class PreLoginHookCommandTest extends ALoginTestCommand { /** @var IUserManager|MockObject */ private $userManager; diff --git a/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php b/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php index d4e15f68257..fb8240c4b1e 100644 --- a/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php +++ b/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php @@ -14,7 +14,7 @@ use OCP\IConfig; use OCP\ISession; use PHPUnit\Framework\MockObject\MockObject; -class SetUserTimezoneCommandTest extends ALoginCommandTest { +class SetUserTimezoneCommandTest extends ALoginTestCommand { /** @var IConfig|MockObject */ private $config; diff --git a/tests/lib/Authentication/Login/TwoFactorCommandTest.php b/tests/lib/Authentication/Login/TwoFactorCommandTest.php index af7d7446bfb..a95e4b50cbc 100644 --- a/tests/lib/Authentication/Login/TwoFactorCommandTest.php +++ b/tests/lib/Authentication/Login/TwoFactorCommandTest.php @@ -18,7 +18,7 @@ use OCP\Authentication\TwoFactorAuth\IProvider as ITwoFactorAuthProvider; use OCP\IURLGenerator; use PHPUnit\Framework\MockObject\MockObject; -class TwoFactorCommandTest extends ALoginCommandTest { +class TwoFactorCommandTest extends ALoginTestCommand { /** @var Manager|MockObject */ private $twoFactorManager; diff --git a/tests/lib/Authentication/Login/UidLoginCommandTest.php b/tests/lib/Authentication/Login/UidLoginCommandTest.php index 3073aac1859..daae34e2212 100644 --- a/tests/lib/Authentication/Login/UidLoginCommandTest.php +++ b/tests/lib/Authentication/Login/UidLoginCommandTest.php @@ -13,7 +13,7 @@ use OC\Authentication\Login\UidLoginCommand; use OC\User\Manager; use PHPUnit\Framework\MockObject\MockObject; -class UidLoginCommandTest extends ALoginCommandTest { +class UidLoginCommandTest extends ALoginTestCommand { /** @var Manager|MockObject */ private $userManager; diff --git a/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php b/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php index f5760f3f232..1a845a05c23 100644 --- a/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php +++ b/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php @@ -13,7 +13,7 @@ use OC\Authentication\Login\UpdateLastPasswordConfirmCommand; use OCP\ISession; use PHPUnit\Framework\MockObject\MockObject; -class UpdateLastPasswordConfirmCommandTest extends ALoginCommandTest { +class UpdateLastPasswordConfirmCommandTest extends ALoginTestCommand { /** @var ISession|MockObject */ private $session; diff --git a/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php b/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php index 84b1018e5fa..ee4e171d443 100644 --- a/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php +++ b/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php @@ -15,7 +15,7 @@ use OCP\IUserManager; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; -class UserDisabledCheckCommandTest extends ALoginCommandTest { +class UserDisabledCheckCommandTest extends ALoginTestCommand { /** @var IUserManager|MockObject */ private $userManager; diff --git a/tests/lib/Authentication/Token/ManagerTest.php b/tests/lib/Authentication/Token/ManagerTest.php index 4fde9817d09..0f95d1d2f2c 100644 --- a/tests/lib/Authentication/Token/ManagerTest.php +++ b/tests/lib/Authentication/Token/ManagerTest.php @@ -128,10 +128,10 @@ class ManagerTest extends TestCase { $this->assertSame(121, mb_strlen($actual->getName())); } - public function tokenData(): array { + public static function tokenData(): array { return [ [new PublicKeyToken()], - [$this->createMock(IToken::class)], + [IToken::class], ]; } @@ -160,7 +160,11 @@ class ManagerTest extends TestCase { /** * @dataProvider tokenData */ - public function testUpdateToken(IToken $token): void { + public function testUpdateToken(IToken|string $token): void { + if (is_string($token)) { + $token = $this->createMock($token); + } + $this->setNoCall($token); $this->setCall($token, 'updateToken'); $this->setException($token); @@ -171,7 +175,11 @@ class ManagerTest extends TestCase { /** * @dataProvider tokenData */ - public function testUpdateTokenActivity(IToken $token): void { + public function testUpdateTokenActivity(IToken|string $token): void { + if (is_string($token)) { + $token = $this->createMock($token); + } + $this->setNoCall($token); $this->setCall($token, 'updateTokenActivity'); $this->setException($token); @@ -182,7 +190,11 @@ class ManagerTest extends TestCase { /** * @dataProvider tokenData */ - public function testGetPassword(IToken $token): void { + public function testGetPassword(IToken|string $token): void { + if (is_string($token)) { + $token = $this->createMock($token); + } + $this->setNoCall($token); $this->setCall($token, 'getPassword', 'password'); $this->setException($token); @@ -195,7 +207,11 @@ class ManagerTest extends TestCase { /** * @dataProvider tokenData */ - public function testSetPassword(IToken $token): void { + public function testSetPassword(IToken|string $token): void { + if (is_string($token)) { + $token = $this->createMock($token); + } + $this->setNoCall($token); $this->setCall($token, 'setPassword'); $this->setException($token); @@ -358,13 +374,18 @@ class ManagerTest extends TestCase { ->method('getTokenByUser') ->with('theUser') ->willReturn([$t1, $t2]); + + $calls = [ + ['theUser', 123], + ['theUser', 456], + ]; $this->publicKeyTokenProvider ->expects($this->exactly(2)) ->method('invalidateTokenById') - ->withConsecutive( - ['theUser', 123], - ['theUser', 456], - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + }); $this->manager->invalidateTokensOfUser('theUser', null); } diff --git a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php index 6097c1f482d..dc6ec7c7f3e 100644 --- a/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php +++ b/tests/lib/Authentication/Token/PublicKeyTokenProviderTest.php @@ -304,12 +304,17 @@ class PublicKeyTokenProviderTest extends TestCase { } public function testInvalidateToken(): void { + $calls = [ + [hash('sha512', 'token7' . '1f4h9s')], + [hash('sha512', 'token7')] + ]; + $this->mapper->expects($this->exactly(2)) ->method('invalidate') - ->withConsecutive( - [hash('sha512', 'token7' . '1f4h9s')], - [hash('sha512', 'token7')] - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + }); $this->tokenProvider->invalidateToken('token7'); } @@ -336,14 +341,19 @@ class PublicKeyTokenProviderTest extends TestCase { ['token_auth_wipe_token_retention', $wipeTokenLifetime, 500], ['token_auth_token_retention', 60 * 60 * 24 * 365, 800], ]); + + $calls = [ + [$this->time - 150, IToken::TEMPORARY_TOKEN, IToken::DO_NOT_REMEMBER], + [$this->time - 300, IToken::TEMPORARY_TOKEN, IToken::REMEMBER], + [$this->time - 500, IToken::WIPE_TOKEN, null], + [$this->time - 800, IToken::PERMANENT_TOKEN, null], + ]; $this->mapper->expects($this->exactly(4)) ->method('invalidateOld') - ->withConsecutive( - [$this->time - 150, IToken::TEMPORARY_TOKEN, IToken::DO_NOT_REMEMBER], - [$this->time - 300, IToken::TEMPORARY_TOKEN, IToken::REMEMBER], - [$this->time - 500, IToken::WIPE_TOKEN, null], - [$this->time - 800, IToken::PERMANENT_TOKEN, null], - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + }); $this->tokenProvider->invalidateOldTokens(); } @@ -453,16 +463,17 @@ class PublicKeyTokenProviderTest extends TestCase { public function testGetInvalidToken(): void { $this->expectException(InvalidTokenException::class); + $calls = [ + 'unhashedTokentokentokentokentoken' . '1f4h9s', + 'unhashedTokentokentokentokentoken', + ]; $this->mapper->expects($this->exactly(2)) ->method('getToken') - ->withConsecutive( - [$this->callback(function (string $token): bool { - return hash('sha512', 'unhashedTokentokentokentokentoken' . '1f4h9s') === $token; - })], - [$this->callback(function (string $token): bool { - return hash('sha512', 'unhashedTokentokentokentokentoken') === $token; - })] - )->willThrowException(new DoesNotExistException('nope')); + ->willReturnCallback(function (string $token) use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals(hash('sha512', $expected), $token); + throw new DoesNotExistException('nope'); + }); $this->tokenProvider->getToken('unhashedTokentokentokentokentoken'); } diff --git a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php index 52792c29ed0..75691627ce7 100644 --- a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php @@ -204,7 +204,7 @@ class ManagerTest extends TestCase { $this->assertTrue($this->manager->isTwoFactorAuthenticated($this->user)); } - public function providerStatesFixData(): array { + public static function providerStatesFixData(): array { return [ [false, false], [true, true], @@ -356,12 +356,18 @@ class ManagerTest extends TestCase { ->method('get') ->with('two_factor_remember_login') ->willReturn(false); + + $calls = [ + ['two_factor_auth_uid'], + ['two_factor_remember_login'], + ]; $this->session->expects($this->exactly(2)) ->method('remove') - ->withConsecutive( - ['two_factor_auth_uid'], - ['two_factor_remember_login'] - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + }); + $this->session->expects($this->once()) ->method('set') ->with(Manager::SESSION_UID_DONE, 'jos'); @@ -474,14 +480,19 @@ class ManagerTest extends TestCase { public function testNeedsSecondFactor(): void { $user = $this->createMock(IUser::class); + + $calls = [ + ['app_password'], + ['two_factor_auth_uid'], + [Manager::SESSION_UID_DONE], + ]; $this->session->expects($this->exactly(3)) ->method('exists') - ->withConsecutive( - ['app_password'], - ['two_factor_auth_uid'], - [Manager::SESSION_UID_DONE], - ) - ->willReturn(false); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + return false; + }); $this->session->method('getId') ->willReturn('mysessionid'); @@ -513,7 +524,7 @@ class ManagerTest extends TestCase { $this->timeFactory, $this->dispatcher, ]) - ->setMethods(['loadTwoFactorApp', 'isTwoFactorAuthenticated'])// Do not actually load the apps + ->onlyMethods(['isTwoFactorAuthenticated'])// Do not actually load the apps ->getMock(); $manager->method('isTwoFactorAuthenticated') @@ -550,12 +561,16 @@ class ManagerTest extends TestCase { $this->user->method('getUID') ->willReturn('ferdinand'); + $calls = [ + ['two_factor_auth_uid', 'ferdinand'], + ['two_factor_remember_login', true], + ]; $this->session->expects($this->exactly(2)) ->method('set') - ->withConsecutive( - ['two_factor_auth_uid', 'ferdinand'], - ['two_factor_remember_login', true] - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + }); $this->session->method('getId') ->willReturn('mysessionid'); @@ -580,12 +595,16 @@ class ManagerTest extends TestCase { $this->user->method('getUID') ->willReturn('ferdinand'); + $calls = [ + ['two_factor_auth_uid', 'ferdinand'], + ['two_factor_remember_login', false], + ]; $this->session->expects($this->exactly(2)) ->method('set') - ->withConsecutive( - ['two_factor_auth_uid', 'ferdinand'], - ['two_factor_remember_login', false] - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + }); $this->session->method('getId') ->willReturn('mysessionid'); @@ -710,21 +729,29 @@ class ManagerTest extends TestCase { '42', '43', '44' ]); + $deleteUserValueCalls = [ + ['theUserId', 'login_token_2fa', '42'], + ['theUserId', 'login_token_2fa', '43'], + ['theUserId', 'login_token_2fa', '44'], + ]; $this->config->expects($this->exactly(3)) ->method('deleteUserValue') - ->withConsecutive( - ['theUserId', 'login_token_2fa', '42'], - ['theUserId', 'login_token_2fa', '43'], - ['theUserId', 'login_token_2fa', '44'], - ); + ->willReturnCallback(function () use (&$deleteUserValueCalls) { + $expected = array_shift($deleteUserValueCalls); + $this->assertEquals($expected, func_get_args()); + }); + $invalidateCalls = [ + ['theUserId', 42], + ['theUserId', 43], + ['theUserId', 44], + ]; $this->tokenProvider->expects($this->exactly(3)) ->method('invalidateTokenById') - ->withConsecutive( - ['theUserId', 42], - ['theUserId', 43], - ['theUserId', 44], - ); + ->willReturnCallback(function () use (&$invalidateCalls) { + $expected = array_shift($invalidateCalls); + $this->assertEquals($expected, func_get_args()); + }); $this->manager->clearTwoFactorPending('theUserId'); } @@ -736,22 +763,28 @@ class ManagerTest extends TestCase { '42', '43', '44' ]); + $deleteUserValueCalls = [ + ['theUserId', 'login_token_2fa', '42'], + ['theUserId', 'login_token_2fa', '43'], + ['theUserId', 'login_token_2fa', '44'], + ]; $this->config->expects($this->exactly(3)) ->method('deleteUserValue') - ->withConsecutive( - ['theUserId', 'login_token_2fa', '42'], - ['theUserId', 'login_token_2fa', '43'], - ['theUserId', 'login_token_2fa', '44'], - ); + ->willReturnCallback(function () use (&$deleteUserValueCalls) { + $expected = array_shift($deleteUserValueCalls); + $this->assertEquals($expected, func_get_args()); + }); + $invalidateCalls = [ + ['theUserId', 42], + ['theUserId', 43], + ['theUserId', 44], + ]; $this->tokenProvider->expects($this->exactly(3)) ->method('invalidateTokenById') - ->withConsecutive( - ['theUserId', 42], - ['theUserId', 43], - ['theUserId', 44], - ) - ->willReturnCallback(function ($user, $tokenId) { + ->willReturnCallback(function ($user, $tokenId) use (&$invalidateCalls) { + $expected = array_shift($invalidateCalls); + $this->assertEquals($expected, func_get_args()); if ($tokenId === 43) { throw new DoesNotExistException('token does not exist'); } diff --git a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php index 77e619d03a2..252b57e7983 100644 --- a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php @@ -119,12 +119,17 @@ class RegistryTest extends TestCase { 'provider_id' => 'twofactor_u2f', ] ]); + + $calls = [ + [new TwoFactorProviderDisabled('twofactor_u2f')], + [new TwoFactorProviderUserDeleted($user, 'twofactor_u2f')], + ]; $this->dispatcher->expects($this->exactly(2)) ->method('dispatchTyped') - ->withConsecutive( - [new TwoFactorProviderDisabled('twofactor_u2f')], - [new TwoFactorProviderUserDeleted($user, 'twofactor_u2f')], - ); + ->willReturnCallback(function () use (&$calls) { + $expected = array_shift($calls); + $this->assertEquals($expected, func_get_args()); + }); $this->registry->deleteUserData($user); } diff --git a/tests/lib/Avatar/AvatarManagerTest.php b/tests/lib/Avatar/AvatarManagerTest.php index 25e8e1563f5..5fac90e0f34 100644 --- a/tests/lib/Avatar/AvatarManagerTest.php +++ b/tests/lib/Avatar/AvatarManagerTest.php @@ -186,7 +186,7 @@ class AvatarManagerTest extends \Test\TestCase { $this->assertEquals($expected, $this->avatarManager->getAvatar('vaLid-USER')); } - public function dataGetAvatarScopes() { + public static function dataGetAvatarScopes(): array { return [ // public access cannot see real avatar [IAccountManager::SCOPE_PRIVATE, true, false, true], diff --git a/tests/lib/Avatar/UserAvatarTest.php b/tests/lib/Avatar/UserAvatarTest.php index 0e2bfe6872f..633a0fda368 100644 --- a/tests/lib/Avatar/UserAvatarTest.php +++ b/tests/lib/Avatar/UserAvatarTest.php @@ -41,7 +41,7 @@ class UserAvatarTest extends \Test\TestCase { $this->avatar = $this->getUserAvatar($this->user); } - public function avatarTextData() { + public static function avatarTextData(): array { return [ ['', '?'], ['matchish', 'M'], diff --git a/tests/lib/BackgroundJob/JobListTest.php b/tests/lib/BackgroundJob/JobListTest.php index bf21639d3aa..64279c11a35 100644 --- a/tests/lib/BackgroundJob/JobListTest.php +++ b/tests/lib/BackgroundJob/JobListTest.php @@ -73,7 +73,7 @@ class JobListTest extends TestCase { return $jobs; } - public function argumentProvider() { + public static function argumentProvider(): array { return [ [null], [false], diff --git a/tests/lib/Cache/FileCacheTest.php b/tests/lib/Cache/FileCacheTest.php index 1d12147af0d..8d3db539dd0 100644 --- a/tests/lib/Cache/FileCacheTest.php +++ b/tests/lib/Cache/FileCacheTest.php @@ -88,7 +88,7 @@ class FileCacheTest extends TestCache { private function setupMockStorage() { $mockStorage = $this->getMockBuilder(Local::class) - ->setMethods(['filemtime', 'unlink']) + ->onlyMethods(['filemtime', 'unlink']) ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]]) ->getMock(); @@ -125,7 +125,7 @@ class FileCacheTest extends TestCache { $this->instance->gc(); } - public function lockExceptionProvider() { + public static function lockExceptionProvider(): array { return [ [new \OCP\Lock\LockedException('key1')], [new \OCP\Files\LockNotAcquiredException('key1', 1)], diff --git a/tests/lib/Calendar/ManagerTest.php b/tests/lib/Calendar/ManagerTest.php index cecebcfc4cf..1fb64d97f47 100644 --- a/tests/lib/Calendar/ManagerTest.php +++ b/tests/lib/Calendar/ManagerTest.php @@ -199,7 +199,7 @@ class ManagerTest extends TestCase { $this->assertEquals($expected, $result); } - public function searchProvider() { + public static function searchProvider(): array { $search1 = [ [ 'id' => 1, @@ -1096,7 +1096,7 @@ class ManagerTest extends TestCase { $this->userManager, $this->serverFactory, ]) - ->setMethods([ + ->onlyMethods([ 'getCalendarsForPrincipal' ]) ->getMock(); @@ -1544,11 +1544,11 @@ class ManagerTest extends TestCase { $this->userManager, $this->serverFactory, ]) - ->setMethods([ + ->onlyMethods([ 'getCalendarsForPrincipal' ]) ->getMock(); - + $principalUri = 'principals/user/pierre'; $sender = 'clint@stardew-tent-living.com'; $recipient = 'pierre@general-store.com'; @@ -1588,7 +1588,7 @@ class ManagerTest extends TestCase { $this->userManager, $this->serverFactory, ]) - ->setMethods([ + ->onlyMethods([ 'getCalendarsForPrincipal' ]) ->getMock(); diff --git a/tests/lib/Collaboration/Collaborators/MailPluginTest.php b/tests/lib/Collaboration/Collaborators/MailPluginTest.php index 02b1034240f..5112795ec7c 100644 --- a/tests/lib/Collaboration/Collaborators/MailPluginTest.php +++ b/tests/lib/Collaboration/Collaborators/MailPluginTest.php @@ -134,7 +134,7 @@ class MailPluginTest extends TestCase { $this->assertSame($reachedEnd, $moreResults); } - public function dataGetEmail() { + public static function dataGetEmail(): array { return [ // data set 0 ['test', [], true, ['emails' => [], 'exact' => ['emails' => []]], false, false, false], @@ -636,7 +636,7 @@ class MailPluginTest extends TestCase { $this->assertSame($reachedEnd, $moreResults); } - public function dataGetEmailGroupsOnly() { + public static function dataGetEmailGroupsOnly(): array { return [ // The user `User` can share with the current user [ diff --git a/tests/lib/Collaboration/Collaborators/RemotePluginTest.php b/tests/lib/Collaboration/Collaborators/RemotePluginTest.php index 14894aa2df6..aa7e4c8afd5 100644 --- a/tests/lib/Collaboration/Collaborators/RemotePluginTest.php +++ b/tests/lib/Collaboration/Collaborators/RemotePluginTest.php @@ -141,7 +141,7 @@ class RemotePluginTest extends TestCase { $this->plugin->splitUserRemote($id); } - public function dataGetRemote() { + public static function dataGetRemote() { return [ ['test', [], true, ['remotes' => [], 'exact' => ['remotes' => []]], false, true], ['test', [], false, ['remotes' => [], 'exact' => ['remotes' => []]], false, true], @@ -374,7 +374,7 @@ class RemotePluginTest extends TestCase { ]; } - public function dataTestSplitUserRemote() { + public static function dataTestSplitUserRemote(): array { $userPrefix = ['user@name', 'username']; $protocols = ['', 'http://', 'https://']; $remotes = [ @@ -410,7 +410,7 @@ class RemotePluginTest extends TestCase { return $testCases; } - public function dataTestSplitUserRemoteError() { + public static function dataTestSplitUserRemoteError(): array { return [ // Invalid path ['user@'], diff --git a/tests/lib/Collaboration/Collaborators/SearchResultTest.php b/tests/lib/Collaboration/Collaborators/SearchResultTest.php index 6641a2caed1..7a0afe87e4b 100644 --- a/tests/lib/Collaboration/Collaborators/SearchResultTest.php +++ b/tests/lib/Collaboration/Collaborators/SearchResultTest.php @@ -27,7 +27,7 @@ class SearchResultTest extends TestCase { $this->search = new Search($this->container); } - public function dataAddResultSet() { + public static function dataAddResultSet(): array { return [ [[], ['exact' => []]], [['users' => ['exact' => null, 'loose' => []]], ['exact' => ['users' => []], 'users' => []]], @@ -51,7 +51,7 @@ class SearchResultTest extends TestCase { $this->assertEquals($expected, $result->asArray()); } - public function dataHasResult() { + public static function dataHasResult(): array { $result = ['value' => ['shareWith' => 'l1']]; return [ [[],'users', 'n1', false], diff --git a/tests/lib/Collaboration/Collaborators/SearchTest.php b/tests/lib/Collaboration/Collaborators/SearchTest.php index 3e43d6331b2..146befe966e 100644 --- a/tests/lib/Collaboration/Collaborators/SearchTest.php +++ b/tests/lib/Collaboration/Collaborators/SearchTest.php @@ -115,7 +115,7 @@ class SearchTest extends TestCase { $this->assertSame($expectedMoreResults, $moreResults); } - public function dataSearchSharees() { + public static function dataSearchSharees(): array { return [ // #0 [ diff --git a/tests/lib/Collaboration/Collaborators/UserPluginTest.php b/tests/lib/Collaboration/Collaborators/UserPluginTest.php index 453f16c6686..3b342b7938b 100644 --- a/tests/lib/Collaboration/Collaborators/UserPluginTest.php +++ b/tests/lib/Collaboration/Collaborators/UserPluginTest.php @@ -124,7 +124,7 @@ class UserPluginTest extends TestCase { return $group; } - public function dataGetUsers() { + public function dataGetUsers(): array { return [ ['test', false, true, [], [], [], [], true, false], ['test', false, false, [], [], [], [], true, false], @@ -508,7 +508,7 @@ class UserPluginTest extends TestCase { $this->assertSame($reachedEnd, $moreResults); } - public function takeOutCurrentUserProvider() { + public static function takeOutCurrentUserProvider(): array { $inputUsers = [ 'alice' => 'Alice', 'bob' => 'Bob', @@ -555,7 +555,7 @@ class UserPluginTest extends TestCase { $this->assertSame($expectedUIDs, array_keys($users)); } - public function dataSearchEnumeration() { + public static function dataSearchEnumeration(): array { return [ [ 'test', diff --git a/tests/lib/Command/AsyncBusTest.php b/tests/lib/Command/AsyncBusTestCase.php index e8d7a857129..c4f173f8b32 100644 --- a/tests/lib/Command/AsyncBusTest.php +++ b/tests/lib/Command/AsyncBusTestCase.php @@ -15,7 +15,7 @@ use Test\TestCase; class SimpleCommand implements ICommand { public function handle() { - AsyncBusTest::$lastCommand = 'SimpleCommand'; + AsyncBusTestCase::$lastCommand = 'SimpleCommand'; } } @@ -27,7 +27,7 @@ class StateFullCommand implements ICommand { } public function handle() { - AsyncBusTest::$lastCommand = $this->state; + AsyncBusTestCase::$lastCommand = $this->state; } } @@ -35,18 +35,18 @@ class FilesystemCommand implements ICommand { use FileAccess; public function handle() { - AsyncBusTest::$lastCommand = 'FileAccess'; + AsyncBusTestCase::$lastCommand = 'FileAccess'; } } function basicFunction() { - AsyncBusTest::$lastCommand = 'function'; + AsyncBusTestCase::$lastCommand = 'function'; } // clean class to prevent phpunit putting closure in $this class ThisClosureTest { private function privateMethod() { - AsyncBusTest::$lastCommand = 'closure-this'; + AsyncBusTestCase::$lastCommand = 'closure-this'; } public function test(IBus $bus) { @@ -56,7 +56,7 @@ class ThisClosureTest { } } -abstract class AsyncBusTest extends TestCase { +abstract class AsyncBusTestCase extends TestCase { /** * Basic way to check output from a command * @@ -107,7 +107,7 @@ abstract class AsyncBusTest extends TestCase { } public function testStaticCallable(): void { - $this->getBus()->push(['\Test\Command\AsyncBusTest', 'DummyCommand']); + $this->getBus()->push(['\Test\Command\AsyncBusTestCase', 'DummyCommand']); $this->runJobs(); $this->assertEquals('static', self::$lastCommand); } @@ -127,7 +127,7 @@ abstract class AsyncBusTest extends TestCase { public function testClosure(): void { $this->getBus()->push(function () { - AsyncBusTest::$lastCommand = 'closure'; + AsyncBusTestCase::$lastCommand = 'closure'; }); $this->runJobs(); $this->assertEquals('closure', self::$lastCommand); @@ -135,7 +135,7 @@ abstract class AsyncBusTest extends TestCase { public function testClosureSelf(): void { $this->getBus()->push(function () { - AsyncBusTest::$lastCommand = 'closure-self'; + AsyncBusTestCase::$lastCommand = 'closure-self'; }); $this->runJobs(); $this->assertEquals('closure-self', self::$lastCommand); @@ -153,7 +153,7 @@ abstract class AsyncBusTest extends TestCase { public function testClosureBind(): void { $state = 'bar'; $this->getBus()->push(function () use ($state) { - AsyncBusTest::$lastCommand = 'closure-' . $state; + AsyncBusTestCase::$lastCommand = 'closure-' . $state; }); $this->runJobs(); $this->assertEquals('closure-bar', self::$lastCommand); diff --git a/tests/lib/Command/BackgroundModeTest.php b/tests/lib/Command/BackgroundModeTest.php index 941449c98bb..2f874deb78a 100644 --- a/tests/lib/Command/BackgroundModeTest.php +++ b/tests/lib/Command/BackgroundModeTest.php @@ -16,6 +16,9 @@ use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Tester\CommandTester; use Test\TestCase; +/** + * @group DB + */ class BackgroundModeTest extends TestCase { private IAppConfig $appConfig; @@ -49,7 +52,7 @@ class BackgroundModeTest extends TestCase { $this->assertStringContainsString($mode, $output); } - public function dataModeCommand(): array { + public static function dataModeCommand(): array { return [ 'ajax' => ['ajax'], 'cron' => ['cron'], diff --git a/tests/lib/Command/CronBusTest.php b/tests/lib/Command/CronBusTest.php index 96190f717c6..2e5617efb31 100644 --- a/tests/lib/Command/CronBusTest.php +++ b/tests/lib/Command/CronBusTest.php @@ -9,7 +9,10 @@ namespace Test\Command; use OC\Command\CronBus; use Test\BackgroundJob\DummyJobList; -class CronBusTest extends AsyncBusTest { +/** + * @group DB + */ +class CronBusTest extends AsyncBusTestCase { /** * @var \OCP\BackgroundJob\IJobList */ diff --git a/tests/lib/Command/Integrity/SignAppTest.php b/tests/lib/Command/Integrity/SignAppTest.php index d4921c79431..38b5c68e026 100644 --- a/tests/lib/Command/Integrity/SignAppTest.php +++ b/tests/lib/Command/Integrity/SignAppTest.php @@ -44,22 +44,28 @@ class SignAppTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['path'], - ['privateKey'], - ['certificate'], - )->willReturnOnConsecutiveCalls( - null, - 'PrivateKey', - 'Certificate', - ); - + ->willReturnMap([ + ['path', null], + ['privateKey', 'PrivateKey'], + ['certificate', 'Certificate'], + ]); + + $calls = [ + 'This command requires the --path, --privateKey and --certificate.', + '*', + '*', + ]; $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['This command requires the --path, --privateKey and --certificate.'] - ); + ->willReturnCallback(function (string $message) use (&$calls) { + $expected = array_shift($calls); + if ($expected === '*') { + $this->assertNotEmpty($message); + } else { + $this->assertEquals($expected, $message); + } + }); $this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface])); } @@ -71,22 +77,28 @@ class SignAppTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['path'], - ['privateKey'], - ['certificate'], - )->willReturnOnConsecutiveCalls( - 'AppId', - null, - 'Certificate', - ); - + ->willReturnMap([ + ['path', 'AppId'], + ['privateKey', null], + ['certificate', 'Certificate'], + ]); + + $calls = [ + 'This command requires the --path, --privateKey and --certificate.', + '*', + '*', + ]; $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['This command requires the --path, --privateKey and --certificate.'] - ); + ->willReturnCallback(function (string $message) use (&$calls) { + $expected = array_shift($calls); + if ($expected === '*') { + $this->assertNotEmpty($message); + } else { + $this->assertEquals($expected, $message); + } + }); $this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface])); } @@ -98,22 +110,28 @@ class SignAppTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['path'], - ['privateKey'], - ['certificate'], - )->willReturnOnConsecutiveCalls( - 'AppId', - 'privateKey', - null, - ); - + ->willReturnMap([ + ['path', 'AppId'], + ['privateKey', 'PrivateKey'], + ['certificate', null], + ]); + + $calls = [ + 'This command requires the --path, --privateKey and --certificate.', + '*', + '*', + ]; $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['This command requires the --path, --privateKey and --certificate.'] - ); + ->willReturnCallback(function (string $message) use (&$calls) { + $expected = array_shift($calls); + if ($expected === '*') { + $this->assertNotEmpty($message); + } else { + $this->assertEquals($expected, $message); + } + }); $this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface])); } @@ -125,29 +143,26 @@ class SignAppTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['path'], - ['privateKey'], - ['certificate'], - )->willReturnOnConsecutiveCalls( - 'AppId', - 'privateKey', - 'certificate', - ); + ->willReturnMap([ + ['path', 'AppId'], + ['privateKey', 'privateKey'], + ['certificate', 'certificate'], + ]); $this->fileAccessHelper ->expects($this->any()) ->method('file_get_contents') - ->withConsecutive(['privateKey']) - ->willReturnOnConsecutiveCalls(false); + ->willReturnMap([ + ['privateKey', false], + ]); $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['Private key "privateKey" does not exists.'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('Private key "privateKey" does not exists.', $message); + }); $this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface])); } @@ -159,34 +174,26 @@ class SignAppTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['path'], - ['privateKey'], - ['certificate'], - )->willReturnOnConsecutiveCalls( - 'AppId', - 'privateKey', - 'certificate', - ); + ->willReturnMap([ + ['path', 'AppId'], + ['privateKey', 'privateKey'], + ['certificate', 'certificate'], + ]); $this->fileAccessHelper ->expects($this->any()) ->method('file_get_contents') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ) - ->willReturnOnConsecutiveCalls( - \OC::$SERVERROOT . '/tests/data/integritycheck/core.key', - false - ); + ->willReturnMap([ + ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')], + ['certificate', false], + ]); $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['Certificate "certificate" does not exists.'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('Certificate "certificate" does not exists.', $message); + }); $this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface])); } @@ -198,27 +205,19 @@ class SignAppTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['path'], - ['privateKey'], - ['certificate'], - )->willReturnOnConsecutiveCalls( - 'AppId', - 'privateKey', - 'certificate', - ); + ->willReturnMap([ + ['path', 'AppId'], + ['privateKey', 'privateKey'], + ['certificate', 'certificate'], + ]); $this->fileAccessHelper ->expects($this->any()) ->method('file_get_contents') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ) - ->willReturnOnConsecutiveCalls( - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'), - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'), - ); + ->willReturnMap([ + ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')], + ['certificate', \OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'], + ]); $this->checker ->expects($this->once()) @@ -228,9 +227,9 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['Error: My error message'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('Error: My error message', $message); + }); $this->assertSame(1, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface])); } @@ -242,27 +241,19 @@ class SignAppTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['path'], - ['privateKey'], - ['certificate'], - )->willReturnOnConsecutiveCalls( - 'AppId', - 'privateKey', - 'certificate', - ); + ->willReturnMap([ + ['path', 'AppId'], + ['privateKey', 'privateKey'], + ['certificate', 'certificate'], + ]); $this->fileAccessHelper ->expects($this->any()) ->method('file_get_contents') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ) - ->willReturnOnConsecutiveCalls( - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'), - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'), - ); + ->willReturnMap([ + ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')], + ['certificate', \OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'], + ]); $this->checker ->expects($this->once()) @@ -271,9 +262,9 @@ class SignAppTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['Successfully signed "AppId"'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('Successfully signed "AppId"', $message); + }); $this->assertSame(0, self::invokePrivate($this->signApp, 'execute', [$inputInterface, $outputInterface])); } diff --git a/tests/lib/Command/Integrity/SignCoreTest.php b/tests/lib/Command/Integrity/SignCoreTest.php index bbb68e00a84..66227322dda 100644 --- a/tests/lib/Command/Integrity/SignCoreTest.php +++ b/tests/lib/Command/Integrity/SignCoreTest.php @@ -39,22 +39,18 @@ class SignCoreTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ['path'], - )->willReturnOnConsecutiveCalls( - null, - 'certificate', - 'certificate', - ); + ->willReturnMap([ + ['privateKey', null], + ['certificate', 'certificate'], + ['path', 'certificate'], + ]); $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['--privateKey, --certificate and --path are required.'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('--privateKey, --certificate and --path are required.', $message); + }); $this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface])); } @@ -66,22 +62,18 @@ class SignCoreTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ['path'], - )->willReturnOnConsecutiveCalls( - 'privateKey', - null, - 'certificate', - ); + ->willReturnMap([ + ['privateKey', 'privateKey'], + ['certificate', null], + ['path', 'certificate'], + ]); $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['--privateKey, --certificate and --path are required.'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('--privateKey, --certificate and --path are required.', $message); + }); $this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface])); } @@ -93,32 +85,24 @@ class SignCoreTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ['path'], - )->willReturnOnConsecutiveCalls( - 'privateKey', - 'certificate', - 'certificate', - ); + ->willReturnMap([ + ['privateKey', 'privateKey'], + ['certificate', 'certificate'], + ['path', 'certificate'], + ]); $this->fileAccessHelper - ->expects($this->any()) ->method('file_get_contents') - ->withConsecutive( - ['privateKey'], - ) - ->willReturnOnConsecutiveCalls( - false, - ); + ->willReturnMap([ + ['privateKey', false], + ]); $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['Private key "privateKey" does not exists.'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('Private key "privateKey" does not exists.', $message); + }); $this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface])); } @@ -130,34 +114,26 @@ class SignCoreTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ['path'], - )->willReturnOnConsecutiveCalls( - 'privateKey', - 'certificate', - 'certificate', - ); + ->willReturnMap([ + ['privateKey', 'privateKey'], + ['certificate', 'certificate'], + ['path', 'certificate'], + ]); $this->fileAccessHelper ->expects($this->any()) ->method('file_get_contents') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ) - ->willReturnOnConsecutiveCalls( - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'), - false, - ); + ->willReturnMap([ + ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')], + ['certificate', false], + ]); $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['Certificate "certificate" does not exists.'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('Certificate "certificate" does not exists.', $message); + }); $this->assertSame(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface])); } @@ -169,27 +145,19 @@ class SignCoreTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ['path'], - )->willReturnOnConsecutiveCalls( - 'privateKey', - 'certificate', - 'certificate', - ); + ->willReturnMap([ + ['privateKey', 'privateKey'], + ['certificate', 'certificate'], + ['path', 'certificate'], + ]); $this->fileAccessHelper ->expects($this->any()) ->method('file_get_contents') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ) - ->willReturnOnConsecutiveCalls( - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'), - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'), - ); + ->willReturnMap([ + ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')], + ['certificate', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt')], + ]); $this->checker ->expects($this->once()) @@ -199,9 +167,9 @@ class SignCoreTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['Error: My exception message'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('Error: My exception message', $message); + }); $this->assertEquals(1, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface])); } @@ -213,27 +181,19 @@ class SignCoreTest extends TestCase { $inputInterface ->expects($this->exactly(3)) ->method('getOption') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ['path'], - )->willReturnOnConsecutiveCalls( - 'privateKey', - 'certificate', - 'certificate', - ); + ->willReturnMap([ + ['privateKey', 'privateKey'], + ['certificate', 'certificate'], + ['path', 'certificate'], + ]); $this->fileAccessHelper ->expects($this->any()) ->method('file_get_contents') - ->withConsecutive( - ['privateKey'], - ['certificate'], - ) - ->willReturnOnConsecutiveCalls( - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key'), - file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'), - ); + ->willReturnMap([ + ['privateKey', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.key')], + ['certificate', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt')], + ]); $this->checker ->expects($this->once()) @@ -242,9 +202,9 @@ class SignCoreTest extends TestCase { $outputInterface ->expects($this->any()) ->method('writeln') - ->withConsecutive( - ['Successfully signed "core"'] - ); + ->willReturnCallback(function (string $message) { + $this->assertEquals('Successfully signed "core"', $message); + }); $this->assertEquals(0, self::invokePrivate($this->signCore, 'execute', [$inputInterface, $outputInterface])); } diff --git a/tests/lib/Comments/CommentTest.php b/tests/lib/Comments/CommentTest.php index 3cfc897b28e..988ffbe0e0b 100644 --- a/tests/lib/Comments/CommentTest.php +++ b/tests/lib/Comments/CommentTest.php @@ -81,7 +81,7 @@ class CommentTest extends TestCase { $this->assertSame('', $comment->getId()); } - public function simpleSetterProvider() { + public static function simpleSetterProvider(): array { return [ ['Id', true], ['TopmostParentId', true], @@ -105,7 +105,7 @@ class CommentTest extends TestCase { $comment->$setter($input); } - public function roleSetterProvider() { + public static function roleSetterProvider(): array { return [ ['Actor', true, true], ['Actor', 'users', true], @@ -138,7 +138,7 @@ class CommentTest extends TestCase { $comment->setMessage($msg); } - public function mentionsProvider(): array { + public static function mentionsProvider(): array { return [ [ '@alice @bob look look, a cook!', diff --git a/tests/lib/Config/UserConfigTest.php b/tests/lib/Config/UserConfigTest.php index f9a9b5c5272..7bd1e06e297 100644 --- a/tests/lib/Config/UserConfigTest.php +++ b/tests/lib/Config/UserConfigTest.php @@ -333,10 +333,7 @@ class UserConfigTest extends TestCase { ); } - /** - * @return array[] - */ - public function providerHasKey(): array { + public static function providerHasKey(): array { return [ ['user1', 'app1', 'key1', false, true], ['user0', 'app1', 'key1', false, false], @@ -358,10 +355,7 @@ class UserConfigTest extends TestCase { $this->assertEquals($result, $userConfig->hasKey($userId, $appId, $key, $lazy)); } - /** - * @return array[] - */ - public function providerIsSensitive(): array { + public static function providerIsSensitive(): array { return [ ['user1', 'app1', 'key1', false, false, false], ['user0', 'app1', 'key1', false, false, true], @@ -399,10 +393,7 @@ class UserConfigTest extends TestCase { $this->assertEquals($result, $userConfig->isSensitive($userId, $appId, $key, $lazy)); } - /** - * @return array[] - */ - public function providerIsLazy(): array { + public static function providerIsLazy(): array { return [ ['user1', 'app1', 'key1', false, false], ['user0', 'app1', 'key1', false, true], @@ -432,7 +423,7 @@ class UserConfigTest extends TestCase { $this->assertEquals($result, $userConfig->isLazy($userId, $appId, $key)); } - public function providerGetValues(): array { + public static function providerGetValues(): array { return [ [ 'user1', 'app1', '', true, @@ -565,7 +556,7 @@ class UserConfigTest extends TestCase { ); } - public function providerGetAllValues(): array { + public static function providerGetAllValues(): array { return [ [ 'user2', false, @@ -662,7 +653,7 @@ class UserConfigTest extends TestCase { $this->assertEqualsCanonicalizing($result, $userConfig->getAllValues($userId, $filtered)); } - public function providerSearchValuesByApps(): array { + public static function providerSearchValuesByApps(): array { return [ [ 'user1', 'key1', false, null, @@ -708,7 +699,7 @@ class UserConfigTest extends TestCase { $this->assertEquals($result, $userConfig->getValuesByApps($userId, $key, $lazy, $typedAs)); } - public function providerSearchValuesByUsers(): array { + public static function providerSearchValuesByUsers(): array { return [ [ 'app2', 'key2', null, null, @@ -760,7 +751,7 @@ class UserConfigTest extends TestCase { ); } - public function providerSearchValuesByValueString(): array { + public static function providerSearchValuesByValueString(): array { return [ ['app2', 'key2', 'value2a', false, ['user1']], ['app2', 'key2', 'value2A', false, ['user4']], @@ -782,7 +773,7 @@ class UserConfigTest extends TestCase { $this->assertEqualsCanonicalizing($result, iterator_to_array($userConfig->searchUsersByValueString($app, $key, $value, $ci))); } - public function providerSearchValuesByValueInt(): array { + public static function providerSearchValuesByValueInt(): array { return [ ['app3', 'key8', 12, []], // sensitive value, cannot search ['app2', 'key8', 12, ['user2', 'user5']], // sensitive value, cannot search @@ -803,7 +794,7 @@ class UserConfigTest extends TestCase { $this->assertEqualsCanonicalizing($result, iterator_to_array($userConfig->searchUsersByValueInt($app, $key, $value))); } - public function providerSearchValuesByValues(): array { + public static function providerSearchValuesByValues(): array { return [ ['app2', 'key2', ['value2a', 'value2b'], ['user1', 'user2']], ['app2', 'key2', ['value2a', 'value2c'], ['user1', 'user3']], @@ -823,7 +814,7 @@ class UserConfigTest extends TestCase { $this->assertEqualsCanonicalizing($result, iterator_to_array($userConfig->searchUsersByValues($app, $key, $values))); } - public function providerSearchValuesByValueBool(): array { + public static function providerSearchValuesByValueBool(): array { return [ ['app3', 'key10', true, ['user1', 'user4']], ['app3', 'key10', false, ['user2']], @@ -843,7 +834,7 @@ class UserConfigTest extends TestCase { $this->assertEqualsCanonicalizing($result, iterator_to_array($userConfig->searchUsersByValueBool($app, $key, $value))); } - public function providerGetValueMixed(): array { + public static function providerGetValueMixed(): array { return [ [ ['user1'], 'user1', 'app1', 'key0', 'default_because_unknown_key', true, @@ -943,7 +934,7 @@ class UserConfigTest extends TestCase { $this->assertEquals($result, $userConfig->getValueString($userId, $app, $key, $default, $lazy)); } - public function providerGetValueInt(): array { + public static function providerGetValueInt(): array { return [ [['user1'], 'user1', 'app1', 'key0', 54321, true, 54321], [null, 'user1', 'app1', 'key0', 54321, true, 54321], @@ -985,7 +976,7 @@ class UserConfigTest extends TestCase { $this->assertEquals($result, $userConfig->getValueInt($userId, $app, $key, $default, $lazy)); } - public function providerGetValueFloat(): array { + public static function providerGetValueFloat(): array { return [ [['user1'], 'user1', 'app1', 'key0', 54.321, true, 54.321], [null, 'user1', 'app1', 'key0', 54.321, true, 54.321], @@ -1026,7 +1017,7 @@ class UserConfigTest extends TestCase { $this->assertEquals($result, $userConfig->getValueFloat($userId, $app, $key, $default, $lazy)); } - public function providerGetValueBool(): array { + public static function providerGetValueBool(): array { return [ [['user1'], 'user1', 'app1', 'key0', false, true, false], [null, 'user1', 'app1', 'key0', false, true, false], @@ -1087,7 +1078,7 @@ class UserConfigTest extends TestCase { $this->assertEquals($result, $userConfig->getValueBool($userId, $app, $key, $default, $lazy)); } - public function providerGetValueArray(): array { + public static function providerGetValueArray(): array { return [ [ ['user1'], 'user1', 'app1', 'key0', ['default_because_unknown_key'], true, @@ -1126,7 +1117,7 @@ class UserConfigTest extends TestCase { ); } - public function providerGetValueType(): array { + public static function providerGetValueType(): array { return [ [null, 'user1', 'app1', 'key1', false, ValueType::MIXED], [null, 'user1', 'app1', 'key1', true, null, UnknownKeyException::class], @@ -1187,7 +1178,7 @@ class UserConfigTest extends TestCase { } } - public function providerSetValueMixed(): array { + public static function providerSetValueMixed(): array { return [ [null, 'user1', 'app1', 'key1', 'value', false, false, true], [null, 'user1', 'app1', 'key1', '12345', true, false, true], @@ -1250,7 +1241,7 @@ class UserConfigTest extends TestCase { } - public function providerSetValueString(): array { + public static function providerSetValueString(): array { return [ [null, 'user1', 'app1', 'key1', 'value', false, false, true], [null, 'user1', 'app1', 'key1', '12345', true, false, true], @@ -1325,7 +1316,7 @@ class UserConfigTest extends TestCase { } } - public function providerSetValueInt(): array { + public static function providerSetValueInt(): array { return [ [null, 'user1', 'app1', 'key1', 12345, false, false, true], [null, 'user1', 'app1', 'key1', 12345, true, false, true], @@ -1389,7 +1380,7 @@ class UserConfigTest extends TestCase { } } - public function providerSetValueFloat(): array { + public static function providerSetValueFloat(): array { return [ [null, 'user1', 'app1', 'key1', 12.345, false, false, true], [null, 'user1', 'app1', 'key1', 12.345, true, false, true], @@ -1453,7 +1444,7 @@ class UserConfigTest extends TestCase { } - public function providerSetValueArray(): array { + public static function providerSetValueArray(): array { return [ [null, 'user1', 'app1', 'key1', [], false, false, true], [null, 'user1', 'app1', 'key1', [], true, false, true], @@ -1520,7 +1511,7 @@ class UserConfigTest extends TestCase { } } - public function providerUpdateSensitive(): array { + public static function providerUpdateSensitive(): array { return [ [null, 'user1', 'app1', 'key1', false, false], [['user1'], 'user1', 'app1', 'key1', false, false], @@ -1566,7 +1557,7 @@ class UserConfigTest extends TestCase { } } - public function providerUpdateGlobalSensitive(): array { + public static function providerUpdateGlobalSensitive(): array { return [[true], [false]]; } @@ -1610,7 +1601,7 @@ class UserConfigTest extends TestCase { } } - public function providerUpdateLazy(): array { + public static function providerUpdateLazy(): array { return [ [null, 'user1', 'app1', 'key1', false, false], [['user1'], 'user1', 'app1', 'key1', false, false], @@ -1649,7 +1640,7 @@ class UserConfigTest extends TestCase { } } - public function providerUpdateGlobalLazy(): array { + public static function providerUpdateGlobalLazy(): array { return [[true], [false]]; } @@ -1679,7 +1670,7 @@ class UserConfigTest extends TestCase { } } - public function providerGetDetails(): array { + public static function providerGetDetails(): array { return [ [ 'user3', 'app2', 'key2', @@ -1732,7 +1723,7 @@ class UserConfigTest extends TestCase { } - public function providerDeletePreference(): array { + public static function providerDeletePreference(): array { return [ [null, 'user1', 'app1', 'key22'], [['user1'], 'user1', 'app1', 'fast_string_sensitive'], @@ -1763,7 +1754,7 @@ class UserConfigTest extends TestCase { $this->assertEquals(false, $userConfig->hasKey($userId, $app, $key, $lazy)); } - public function providerDeleteKey(): array { + public static function providerDeleteKey(): array { return [ [null, 'app2', 'key3'], [['user1'], 'app2', 'key3'], @@ -1832,7 +1823,7 @@ class UserConfigTest extends TestCase { 'fastCache' => [], 'lazyLoaded' => [], 'lazyCache' => [], - 'valueTypes' => [], + 'valueDetails' => [], ], $userConfig->statusCache() ); diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php index 7586b063883..6fea6b39e92 100644 --- a/tests/lib/ContactsManagerTest.php +++ b/tests/lib/ContactsManagerTest.php @@ -17,7 +17,7 @@ class ContactsManagerTest extends \Test\TestCase { $this->cm = new \OC\ContactsManager(); } - public function searchProvider() { + public static function searchProvider(): array { $search1 = [ 0 => [ 'N' => [0 => '', 1 => 'Jan', 2 => 'Jansen', 3 => '', 4 => '',], diff --git a/tests/lib/DB/ConnectionFactoryTest.php b/tests/lib/DB/ConnectionFactoryTest.php index 23bde34a8fb..31dd8037964 100644 --- a/tests/lib/DB/ConnectionFactoryTest.php +++ b/tests/lib/DB/ConnectionFactoryTest.php @@ -12,7 +12,7 @@ use OCP\ICacheFactory; use Test\TestCase; class ConnectionFactoryTest extends TestCase { - public function splitHostFromPortAndSocketData() { + public static function splitHostFromPortAndSocketData(): array { return [ ['127.0.0.1', ['host' => '127.0.0.1']], ['db.example.org', ['host' => 'db.example.org']], diff --git a/tests/lib/DB/Exception/DbalExceptionTest.php b/tests/lib/DB/Exception/DbalExceptionTest.php index 470beff9080..c37e65aea0e 100644 --- a/tests/lib/DB/Exception/DbalExceptionTest.php +++ b/tests/lib/DB/Exception/DbalExceptionTest.php @@ -44,7 +44,7 @@ class DbalExceptionTest extends \Test\TestCase { $this->assertSame($reason, $result->getReason()); } - public function dataDriverException(): array { + public static function dataDriverException(): array { return [ [LockWaitTimeoutException::class, DbalException::REASON_LOCK_WAIT_TIMEOUT], [ForeignKeyConstraintViolationException::class, DbalException::REASON_FOREIGN_KEY_VIOLATION], diff --git a/tests/lib/DB/MigrationsTest.php b/tests/lib/DB/MigrationsTest.php index 57ffb91e37e..f5379b30be9 100644 --- a/tests/lib/DB/MigrationsTest.php +++ b/tests/lib/DB/MigrationsTest.php @@ -175,7 +175,7 @@ class MigrationsTest extends \Test\TestCase { $this->migrationService->executeStep('20170130180000'); } - public function dataGetMigration() { + public static function dataGetMigration(): array { return [ ['current', '20170130180001'], ['prev', '20170130180000'], diff --git a/tests/lib/DB/MigratorTest.php b/tests/lib/DB/MigratorTest.php index c6afe5a053a..46724afee86 100644 --- a/tests/lib/DB/MigratorTest.php +++ b/tests/lib/DB/MigratorTest.php @@ -261,7 +261,7 @@ class MigratorTest extends \Test\TestCase { $this->assertTrue($startSchema->getTable($this->tableNameTmp)->hasForeignKey($fkName)); } - public function dataNotNullEmptyValuesFailOracle(): array { + public static function dataNotNullEmptyValuesFailOracle(): array { return [ [ParameterType::BOOLEAN, true, Types::BOOLEAN, false], [ParameterType::BOOLEAN, false, Types::BOOLEAN, true], diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php index 392fe9ff937..dc0bca9be95 100644 --- a/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php +++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderDBTest.php @@ -11,6 +11,7 @@ use OC\DB\QueryBuilder\Literal; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\DB\Types; use OCP\IConfig; +use OCP\IDBConnection; use OCP\Server; use Test\TestCase; @@ -29,8 +30,8 @@ class ExpressionBuilderDBTest extends TestCase { $this->prepareTestingTable(); } - public function likeProvider() { - $connection = \OC::$server->getDatabaseConnection(); + public static function likeProvider(): array { + $connection = \OCP\Server::get(IDBConnection::class); return [ ['foo', 'bar', false], @@ -65,8 +66,8 @@ class ExpressionBuilderDBTest extends TestCase { $this->assertEquals($match, $column); } - public function ilikeProvider() { - $connection = \OC::$server->getDatabaseConnection(); + public static function ilikeProvider(): array { + $connection = \OCP\Server::get(IDBConnection::class); return [ ['foo', 'bar', false], diff --git a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php index c14c55e6d02..ab3d1a5081f 100644 --- a/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/ExpressionBuilderTest.php @@ -50,8 +50,8 @@ class ExpressionBuilderTest extends TestCase { $this->doctrineExpressionBuilder = new DoctrineExpressionBuilder($this->internalConnection); } - public function dataComparison() { - $valueSets = $this->dataComparisons(); + public static function dataComparison(): array { + $valueSets = self::dataComparisons(); $comparisonOperators = ['=', '<>', '<', '>', '<=', '>=']; $testSets = []; @@ -82,7 +82,7 @@ class ExpressionBuilderTest extends TestCase { ); } - public function dataComparisons() { + public static function dataComparisons(): array { return [ ['value', false, 'value', false], ['value', false, 'value', true], @@ -213,7 +213,7 @@ class ExpressionBuilderTest extends TestCase { ); } - public function dataLike() { + public static function dataLike(): array { return [ ['value', false], ['value', true], @@ -250,7 +250,7 @@ class ExpressionBuilderTest extends TestCase { ); } - public function dataIn() { + public static function dataIn(): array { return [ ['value', false], ['value', true], @@ -317,7 +317,7 @@ class ExpressionBuilderTest extends TestCase { return [$doctrineInput, $ocInput]; } - public function dataLiteral() { + public static function dataLiteral(): array { return [ ['value', null], ['1', null], @@ -345,7 +345,7 @@ class ExpressionBuilderTest extends TestCase { ); } - public function dataClobComparisons() { + public static function dataClobComparisons(): array { return [ ['eq', '5', IQueryBuilder::PARAM_STR, false, 3], ['eq', '5', IQueryBuilder::PARAM_STR, true, 1], diff --git a/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php b/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php index f3007ace85c..682aedc9ff7 100644 --- a/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/FunctionBuilderTest.php @@ -49,7 +49,7 @@ class FunctionBuilderTest extends TestCase { $this->assertEquals($return, $column); } - public function providerTestConcatString(): array { + public static function providerTestConcatString(): array { return [ '1 column: string param unicode' => [function ($q) { @@ -323,7 +323,7 @@ class FunctionBuilderTest extends TestCase { $this->assertGreaterThan(1, $column); } - public function octetLengthProvider() { + public static function octetLengthProvider(): array { return [ ['', 0], ['foobar', 6], @@ -348,7 +348,7 @@ class FunctionBuilderTest extends TestCase { $this->assertEquals($bytes, $column); } - public function charLengthProvider() { + public static function charLengthProvider(): array { return [ ['', 0], ['foobar', 6], diff --git a/tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php b/tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php index a8ebf11c2c2..3d34ad389bc 100644 --- a/tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php +++ b/tests/lib/DB/QueryBuilder/Partitioned/JoinConditionTest.php @@ -22,7 +22,7 @@ class JoinConditionTest extends TestCase { parent::setUp(); } - public function platformProvider(): array { + public static function platformProvider(): array { return [ [IDBConnection::PLATFORM_SQLITE], [IDBConnection::PLATFORM_POSTGRES], diff --git a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php index 508748f13b2..20086335198 100644 --- a/tests/lib/DB/QueryBuilder/QueryBuilderTest.php +++ b/tests/lib/DB/QueryBuilder/QueryBuilderTest.php @@ -88,7 +88,7 @@ class QueryBuilderTest extends \Test\TestCase { ->execute(); } - public function dataFirstResult() { + public static function dataFirstResult(): array { return [ [0, [99, 98, 97, 96, 95, 94, 93, 92, 91]], [0, [99, 98, 97, 96, 95, 94, 93, 92, 91]], @@ -124,7 +124,7 @@ class QueryBuilderTest extends \Test\TestCase { $this->deleteTestingRows(); } - public function dataMaxResults() { + public static function dataMaxResults(): array { return [ [null, [99, 98, 97, 96, 95, 94, 93, 92, 91]], // Limit 0 gives mixed results: either all entries or none is returned @@ -161,7 +161,7 @@ class QueryBuilderTest extends \Test\TestCase { $this->deleteTestingRows(); } - public function dataSelect() { + public function dataSelect(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); @@ -229,7 +229,7 @@ class QueryBuilderTest extends \Test\TestCase { $this->deleteTestingRows(); } - public function dataSelectAlias() { + public function dataSelectAlias(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); @@ -338,7 +338,7 @@ class QueryBuilderTest extends \Test\TestCase { $this->deleteTestingRows('testFirstResult2'); } - public function dataAddSelect() { + public function dataAddSelect(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); $queryBuilder = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); @@ -408,7 +408,7 @@ class QueryBuilderTest extends \Test\TestCase { $this->deleteTestingRows(); } - public function dataDelete() { + public static function dataDelete(): array { return [ ['data', null, ['table' => '`*PREFIX*data`', 'alias' => null], '`*PREFIX*data`'], ['data', 't', ['table' => '`*PREFIX*data`', 'alias' => 't'], '`*PREFIX*data` t'], @@ -437,7 +437,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataUpdate() { + public static function dataUpdate(): array { return [ ['data', null, ['table' => '`*PREFIX*data`', 'alias' => null], '`*PREFIX*data`'], ['data', 't', ['table' => '`*PREFIX*data`', 'alias' => 't'], '`*PREFIX*data` t'], @@ -466,7 +466,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataInsert() { + public static function dataInsert(): array { return [ ['data', ['table' => '`*PREFIX*data`'], '`*PREFIX*data`'], ]; @@ -493,7 +493,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataFrom() { + public function dataFrom(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); $qb = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); @@ -541,7 +541,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataJoin() { + public static function dataJoin(): array { return [ [ 'd1', 'data2', null, null, @@ -622,7 +622,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataLeftJoin() { + public static function dataLeftJoin(): array { return [ [ 'd1', 'data2', null, null, @@ -672,7 +672,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataRightJoin() { + public static function dataRightJoin(): array { return [ [ 'd1', 'data2', null, null, @@ -722,7 +722,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataSet() { + public static function dataSet(): array { return [ ['column1', new Literal('value'), null, null, ['`column1` = value'], '`column1` = value'], ['column1', new Parameter(':param'), null, null, ['`column1` = :param'], '`column1` = :param'], @@ -759,7 +759,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataWhere() { + public static function dataWhere(): array { return [ [['where1'], new CompositeExpression('AND', ['where1']), 'where1'], [['where1', 'where2'], new CompositeExpression('AND', ['where1', 'where2']), '(where1) AND (where2)'], @@ -816,7 +816,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataOrWhere() { + public static function dataOrWhere(): array { return [ [['where1'], new CompositeExpression('OR', ['where1']), 'where1'], [['where1', 'where2'], new CompositeExpression('OR', ['where1', 'where2']), '(where1) OR (where2)'], @@ -848,7 +848,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataGroupBy() { + public static function dataGroupBy(): array { return [ [['column1'], ['`column1`'], '`column1`'], [['column1', 'column2'], ['`column1`', '`column2`'], '`column1`, `column2`'], @@ -880,7 +880,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataAddGroupBy() { + public static function dataAddGroupBy(): array { return [ [['column2'], ['`column1`', '`column2`'], '`column1`, `column2`'], [['column2', 'column3'], ['`column1`', '`column2`', '`column3`'], '`column1`, `column2`, `column3`'], @@ -913,7 +913,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataSetValue() { + public static function dataSetValue(): array { return [ ['column', 'value', ['`column`' => 'value'], '(`column`) VALUES(value)'], ]; @@ -967,7 +967,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataHaving() { + public static function dataHaving(): array { return [ [['condition1'], new CompositeExpression('AND', ['condition1']), 'HAVING condition1'], [['condition1', 'condition2'], new CompositeExpression('AND', ['condition1', 'condition2']), 'HAVING (condition1) AND (condition2)'], @@ -1008,7 +1008,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataAndHaving() { + public static function dataAndHaving(): array { return [ [['condition2'], new CompositeExpression('AND', ['condition1', 'condition2']), 'HAVING (condition1) AND (condition2)'], [['condition2', 'condition3'], new CompositeExpression('AND', ['condition1', 'condition2', 'condition3']), 'HAVING (condition1) AND (condition2) AND (condition3)'], @@ -1050,7 +1050,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataOrHaving() { + public static function dataOrHaving(): array { return [ [['condition2'], new CompositeExpression('OR', ['condition1', 'condition2']), 'HAVING (condition1) OR (condition2)'], [['condition2', 'condition3'], new CompositeExpression('OR', ['condition1', 'condition2', 'condition3']), 'HAVING (condition1) OR (condition2) OR (condition3)'], @@ -1092,7 +1092,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataOrderBy() { + public static function dataOrderBy(): array { return [ ['column', null, ['`column` ASC'], 'ORDER BY `column` ASC'], ['column', 'ASC', ['`column` ASC'], 'ORDER BY `column` ASC'], @@ -1122,7 +1122,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataAddOrderBy() { + public static function dataAddOrderBy(): array { return [ ['column2', null, null, ['`column1` ASC', '`column2` ASC'], 'ORDER BY `column1` ASC, `column2` ASC'], ['column2', null, 'ASC', ['`column1` ASC', '`column2` ASC'], 'ORDER BY `column1` ASC, `column2` ASC'], @@ -1197,7 +1197,7 @@ class QueryBuilderTest extends \Test\TestCase { } } - public function dataGetTableName() { + public function dataGetTableName(): array { $config = $this->createMock(SystemConfig::class); $logger = $this->createMock(LoggerInterface::class); $qb = new QueryBuilder(\OC::$server->getDatabaseConnection(), $config, $logger); @@ -1234,7 +1234,7 @@ class QueryBuilderTest extends \Test\TestCase { ); } - public function dataGetColumnName() { + public static function dataGetColumnName(): array { return [ ['column', '', '`column`'], ['column', 'a', '`a`.`column`'], diff --git a/tests/lib/DB/QueryBuilder/QuoteHelperTest.php b/tests/lib/DB/QueryBuilder/QuoteHelperTest.php index 3c2e33c28ea..eb09055033e 100644 --- a/tests/lib/DB/QueryBuilder/QuoteHelperTest.php +++ b/tests/lib/DB/QueryBuilder/QuoteHelperTest.php @@ -23,7 +23,7 @@ class QuoteHelperTest extends \Test\TestCase { $this->helper = new QuoteHelper(); } - public function dataQuoteColumnName() { + public static function dataQuoteColumnName(): array { return [ ['column', '`column`'], [new Literal('literal'), 'literal'], @@ -48,7 +48,7 @@ class QuoteHelperTest extends \Test\TestCase { ); } - public function dataQuoteColumnNames() { + public static function dataQuoteColumnNames(): array { return [ // Single case ['d.column', '`d`.`column`'], diff --git a/tests/lib/DateTimeFormatterTest.php b/tests/lib/DateTimeFormatterTest.php index 924cac9d399..cfab1643beb 100644 --- a/tests/lib/DateTimeFormatterTest.php +++ b/tests/lib/DateTimeFormatterTest.php @@ -36,23 +36,23 @@ class DateTimeFormatterTest extends TestCase { $this->formatter = new \OC\DateTimeFormatter(new \DateTimeZone('UTC'), \OCP\Util::getL10N('lib', 'en')); } - protected function getTimestampAgo($time, $seconds = 0, $minutes = 0, $hours = 0, $days = 0, $years = 0) { + protected static function getTimestampAgo($time, $seconds = 0, $minutes = 0, $hours = 0, $days = 0, $years = 0) { return $time - $seconds - $minutes * 60 - $hours * 3600 - $days * 24 * 3600 - $years * 365 * 24 * 3600; } - public function formatTimeSpanData() { + public static function formatTimeSpanData(): array { $time = 1416916800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo $deL10N = \OCP\Util::getL10N('lib', 'de'); return [ ['seconds ago', $time, $time], ['in a few seconds', $time + 5 , $time], - ['1 minute ago', $this->getTimestampAgo($time, 30, 1), $time], - ['15 minutes ago', $this->getTimestampAgo($time, 30, 15), $time], - ['in 15 minutes', $time, $this->getTimestampAgo($time, 30, 15)], - ['1 hour ago', $this->getTimestampAgo($time, 30, 15, 1), $time], - ['3 hours ago', $this->getTimestampAgo($time, 30, 15, 3), $time], - ['in 3 hours', $time, $this->getTimestampAgo($time, 30, 15, 3)], - ['4 days ago', $this->getTimestampAgo($time, 30, 15, 3, 4), $time], + ['1 minute ago', self::getTimestampAgo($time, 30, 1), $time], + ['15 minutes ago', self::getTimestampAgo($time, 30, 15), $time], + ['in 15 minutes', $time, self::getTimestampAgo($time, 30, 15)], + ['1 hour ago', self::getTimestampAgo($time, 30, 15, 1), $time], + ['3 hours ago', self::getTimestampAgo($time, 30, 15, 3), $time], + ['in 3 hours', $time, self::getTimestampAgo($time, 30, 15, 3)], + ['4 days ago', self::getTimestampAgo($time, 30, 15, 3, 4), $time], ['seconds ago', new \DateTime('Wed, 02 Oct 2013 23:59:58 +0000'), new \DateTime('Wed, 02 Oct 2013 23:59:59 +0000')], ['seconds ago', new \DateTime('Wed, 02 Oct 2013 23:59:00 +0000'), new \DateTime('Wed, 02 Oct 2013 23:59:59 +0000')], @@ -81,29 +81,29 @@ class DateTimeFormatterTest extends TestCase { $this->assertEquals((string)$expected, (string)$this->formatter->formatTimeSpan($timestamp, $compare, $locale)); } - public function formatDateSpanData() { + public static function formatDateSpanData(): array { $time = 1416916800; // Use a fixed timestamp so we don't switch days/years with the getTimestampAgo $deL10N = \OCP\Util::getL10N('lib', 'de'); return [ // Normal testing - ['today', $this->getTimestampAgo($time, 30, 15), $time], - ['yesterday', $this->getTimestampAgo($time, 0, 0, 0, 1), $time], - ['tomorrow', $time, $this->getTimestampAgo($time, 0, 0, 0, 1)], - ['4 days ago', $this->getTimestampAgo($time, 0, 0, 0, 4), $time], - ['in 4 days', $time, $this->getTimestampAgo($time, 0, 0, 0, 4)], - ['5 months ago', $this->getTimestampAgo($time, 0, 0, 0, 155), $time], - ['next month', $time, $this->getTimestampAgo($time, 0, 0, 0, 32)], - ['in 5 months', $time, $this->getTimestampAgo($time, 0, 0, 0, 155)], - ['2 years ago', $this->getTimestampAgo($time, 0, 0, 0, 0, 2), $time], - ['next year', $time, $this->getTimestampAgo($time, 0, 0, 0, 0, 1)], - ['in 2 years', $time, $this->getTimestampAgo($time, 0, 0, 0, 0, 2)], + ['today', self::getTimestampAgo($time, 30, 15), $time], + ['yesterday', self::getTimestampAgo($time, 0, 0, 0, 1), $time], + ['tomorrow', $time, self::getTimestampAgo($time, 0, 0, 0, 1)], + ['4 days ago', self::getTimestampAgo($time, 0, 0, 0, 4), $time], + ['in 4 days', $time, self::getTimestampAgo($time, 0, 0, 0, 4)], + ['5 months ago', self::getTimestampAgo($time, 0, 0, 0, 155), $time], + ['next month', $time, self::getTimestampAgo($time, 0, 0, 0, 32)], + ['in 5 months', $time, self::getTimestampAgo($time, 0, 0, 0, 155)], + ['2 years ago', self::getTimestampAgo($time, 0, 0, 0, 0, 2), $time], + ['next year', $time, self::getTimestampAgo($time, 0, 0, 0, 0, 1)], + ['in 2 years', $time, self::getTimestampAgo($time, 0, 0, 0, 0, 2)], // Test with compare timestamp - ['today', $this->getTimestampAgo($time, 0, 0, 0, 0, 1), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)], - ['yesterday', $this->getTimestampAgo($time, 30, 15, 3, 1, 1), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)], - ['4 days ago', $this->getTimestampAgo($time, 30, 15, 3, 4, 1), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)], - ['5 months ago', $this->getTimestampAgo($time, 30, 15, 3, 155, 1), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)], - ['2 years ago', $this->getTimestampAgo($time, 30, 15, 3, 35, 3), $this->getTimestampAgo($time, 0, 0, 0, 0, 1)], + ['today', self::getTimestampAgo($time, 0, 0, 0, 0, 1), self::getTimestampAgo($time, 0, 0, 0, 0, 1)], + ['yesterday', self::getTimestampAgo($time, 30, 15, 3, 1, 1), self::getTimestampAgo($time, 0, 0, 0, 0, 1)], + ['4 days ago', self::getTimestampAgo($time, 30, 15, 3, 4, 1), self::getTimestampAgo($time, 0, 0, 0, 0, 1)], + ['5 months ago', self::getTimestampAgo($time, 30, 15, 3, 155, 1), self::getTimestampAgo($time, 0, 0, 0, 0, 1)], + ['2 years ago', self::getTimestampAgo($time, 30, 15, 3, 35, 3), self::getTimestampAgo($time, 0, 0, 0, 0, 1)], // Test translations [$deL10N->t('today'), new \DateTime('Wed, 02 Oct 2013 12:00:00 +0000'), new \DateTime('Wed, 02 Oct 2013 23:59:59 +0000'), $deL10N], @@ -147,7 +147,7 @@ class DateTimeFormatterTest extends TestCase { $this->assertEquals((string)$expected, (string)$this->formatter->formatDateSpan($timestamp, $compare, $locale)); } - public function formatDateData() { + public static function formatDateData(): array { return [ [1102831200, 'December 12, 2004'], ]; @@ -160,7 +160,7 @@ class DateTimeFormatterTest extends TestCase { $this->assertEquals($expected, (string)$this->formatter->formatDate($timestamp)); } - public function formatDateTimeData() { + public static function formatDateTimeData(): array { return [ [1350129205, null, "October 13, 2012, 11:53:25\xE2\x80\xAFAM UTC"], [1350129205, new \DateTimeZone('Europe/Berlin'), "October 13, 2012, 1:53:25\xE2\x80\xAFPM GMT+2"], diff --git a/tests/lib/EmojiHelperTest.php b/tests/lib/EmojiHelperTest.php index 9ad56b32472..517d8655e53 100644 --- a/tests/lib/EmojiHelperTest.php +++ b/tests/lib/EmojiHelperTest.php @@ -38,10 +38,7 @@ class EmojiHelperTest extends TestCase { $this->assertEquals($expected, $this->helper->doesPlatformSupportEmoji()); } - /** - * @return array - */ - public function doesPlatformSupportEmojiDataProvider(): array { + public static function doesPlatformSupportEmojiDataProvider(): array { return [ [true, true], [false, false], @@ -60,7 +57,7 @@ class EmojiHelperTest extends TestCase { $this->assertEquals($expected, $actual); } - public function isValidSingleEmojiDataProvider(): array { + public static function isValidSingleEmojiDataProvider(): array { return [ ['📱📠', false], ['a', false], diff --git a/tests/lib/Encryption/EncryptionWrapperTest.php b/tests/lib/Encryption/EncryptionWrapperTest.php index 1ac7342a3d8..342a7214e44 100644 --- a/tests/lib/Encryption/EncryptionWrapperTest.php +++ b/tests/lib/Encryption/EncryptionWrapperTest.php @@ -9,7 +9,10 @@ namespace Test\Encryption; use OC\Encryption\EncryptionWrapper; use OC\Encryption\Manager; +use OC\Files\Storage\Wrapper\Encryption; use OC\Memcache\ArrayCache; +use OCA\Files_Trashbin\Storage; +use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IDisableEncryptionStorage; use OCP\Files\Storage\IStorage; use Psr\Log\LoggerInterface; @@ -55,7 +58,7 @@ class EncryptionWrapperTest extends TestCase { ]); } - $mount = $this->getMockBuilder('OCP\Files\Mount\IMountPoint') + $mount = $this->getMockBuilder(IMountPoint::class) ->disableOriginalConstructor() ->getMock(); @@ -63,16 +66,16 @@ class EncryptionWrapperTest extends TestCase { $this->assertEquals( $expectedWrapped, - $returnedStorage->instanceOfStorage('OC\Files\Storage\Wrapper\Encryption'), + $returnedStorage->instanceOfStorage(Encryption::class), 'Asserted that the storage is (not) wrapped with encryption' ); } - public function provideWrapStorage() { + public static function provideWrapStorage(): array { return [ // Wrap when not wrapped or not wrapped with storage [true, []], - [true, ['OCA\Files_Trashbin\Storage']], + [true, [Storage::class]], // Do not wrap shared storages [false, [IDisableEncryptionStorage::class]], diff --git a/tests/lib/Encryption/UpdateTest.php b/tests/lib/Encryption/UpdateTest.php index 9940549981f..4f3de2b495d 100644 --- a/tests/lib/Encryption/UpdateTest.php +++ b/tests/lib/Encryption/UpdateTest.php @@ -113,12 +113,7 @@ class UpdateTest extends TestCase { $updateMock->update($node); } - /** - * data provider for testUpdate() - * - * @return array - */ - public function dataTestUpdate() { + public static function dataTestUpdate(): array { return [ ['/user/files/foo', true, ['/user/files/foo/file1.txt', '/user/files/foo/file1.txt'], 2], ['/user/files/test.txt', false, [], 1], @@ -152,12 +147,7 @@ class UpdateTest extends TestCase { $updateMock->postRename($sourceNode, $targetNode); } - /** - * test data for testPostRename() - * - * @return array - */ - public function dataTestPostRename() { + public static function dataTestPostRename(): array { return [ ['/test.txt', '/testNew.txt'], ['/folder/test.txt', '/testNew.txt'], @@ -193,6 +183,8 @@ class UpdateTest extends TestCase { $this->logger, $this->uid ] - )->setMethods($methods)->getMock(); + ) + ->onlyMethods($methods) + ->getMock(); } } diff --git a/tests/lib/Encryption/UtilTest.php b/tests/lib/Encryption/UtilTest.php index 62ef809a867..68989c55fb0 100644 --- a/tests/lib/Encryption/UtilTest.php +++ b/tests/lib/Encryption/UtilTest.php @@ -20,7 +20,7 @@ class UtilTest extends TestCase { * * @see https://bugs.php.net/bug.php?id=21641 */ - protected int $headerSize = 8192; + protected static int $headerSize = 8192; /** @var \PHPUnit\Framework\MockObject\MockObject */ protected $view; @@ -61,7 +61,7 @@ class UtilTest extends TestCase { $this->assertEquals($expected, $id); } - public function providesHeadersForEncryptionModule() { + public static function providesHeadersForEncryptionModule(): array { return [ ['', []], ['', ['1']], @@ -80,11 +80,11 @@ class UtilTest extends TestCase { $this->assertEquals($expected, $result); } - public function providesHeaders() { + public static function providesHeaders(): array { return [ - [str_pad('HBEGIN:oc_encryption_module:0:HEND', $this->headerSize, '-', STR_PAD_RIGHT) + [str_pad('HBEGIN:oc_encryption_module:0:HEND', self::$headerSize, '-', STR_PAD_RIGHT) , [], '0'], - [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', $this->headerSize, '-', STR_PAD_RIGHT) + [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', self::$headerSize, '-', STR_PAD_RIGHT) , ['custom_header' => 'foo'], '0'], ]; } @@ -120,7 +120,7 @@ class UtilTest extends TestCase { ); } - public function providePathsForTestIsExcluded() { + public static function providePathsForTestIsExcluded(): array { return [ ['/files_encryption', '', true], ['files_encryption/foo.txt', '', true], @@ -152,7 +152,7 @@ class UtilTest extends TestCase { ); } - public function dataTestIsFile() { + public static function dataTestIsFile(): array { return [ ['/user/files/test.txt', true], ['/user/files', true], @@ -175,7 +175,7 @@ class UtilTest extends TestCase { $this->util->stripPartialFileExtension($path)); } - public function dataTestStripPartialFileExtension() { + public static function dataTestStripPartialFileExtension(): array { return [ ['/foo/test.txt', '/foo/test.txt'], ['/foo/test.txt.part', '/foo/test.txt'], @@ -196,17 +196,17 @@ class UtilTest extends TestCase { } } - public function dataTestParseRawHeader() { + public static function dataTestParseRawHeader(): array { return [ - [str_pad('HBEGIN:oc_encryption_module:0:HEND', $this->headerSize, '-', STR_PAD_RIGHT) + [str_pad('HBEGIN:oc_encryption_module:0:HEND', self::$headerSize, '-', STR_PAD_RIGHT) , [Util::HEADER_ENCRYPTION_MODULE_KEY => '0']], - [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', $this->headerSize, '-', STR_PAD_RIGHT) + [str_pad('HBEGIN:oc_encryption_module:0:custom_header:foo:HEND', self::$headerSize, '-', STR_PAD_RIGHT) , ['custom_header' => 'foo', Util::HEADER_ENCRYPTION_MODULE_KEY => '0']], - [str_pad('HelloWorld', $this->headerSize, '-', STR_PAD_RIGHT), []], + [str_pad('HelloWorld', self::$headerSize, '-', STR_PAD_RIGHT), []], ['', []], - [str_pad('HBEGIN:oc_encryption_module:0', $this->headerSize, '-', STR_PAD_RIGHT) + [str_pad('HBEGIN:oc_encryption_module:0', self::$headerSize, '-', STR_PAD_RIGHT) , []], - [str_pad('oc_encryption_module:0:HEND', $this->headerSize, '-', STR_PAD_RIGHT) + [str_pad('oc_encryption_module:0:HEND', self::$headerSize, '-', STR_PAD_RIGHT) , []], ]; } @@ -245,7 +245,7 @@ class UtilTest extends TestCase { ); } - public function dataTestGetFileKeyDir() { + public static function dataTestGetFileKeyDir(): array { return [ [false, '', '/user1/files_encryption/keys/foo/bar.txt/OC_DEFAULT_MODULE/'], [true, '', '/files_encryption/keys/foo/bar.txt/OC_DEFAULT_MODULE/'], diff --git a/tests/lib/ErrorHandlerTest.php b/tests/lib/ErrorHandlerTest.php index b45525e7962..00cf8e4c8db 100644 --- a/tests/lib/ErrorHandlerTest.php +++ b/tests/lib/ErrorHandlerTest.php @@ -16,10 +16,9 @@ use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; class ErrorHandlerTest extends TestCase { - /** @var MockObject */ - private LoggerInterface $logger; - + private LoggerInterface&MockObject $logger; private ErrorHandler $errorHandler; + private int $errorReporting; protected function setUp(): void { parent::setUp(); @@ -28,13 +27,20 @@ class ErrorHandlerTest extends TestCase { $this->errorHandler = new ErrorHandler( $this->logger ); + + $this->errorReporting = error_reporting(E_ALL); + } + + protected function tearDown(): void { + error_reporting($this->errorReporting); + parent::tearDown(); } /** * provide username, password combinations for testRemovePassword * @return array */ - public function passwordProvider() { + public static function passwordProvider(): array { return [ ['us:er', 'pass@word'], ['us:er', 'password'], diff --git a/tests/lib/Federation/CloudIdManagerTest.php b/tests/lib/Federation/CloudIdManagerTest.php index 7019cd202db..0bd0659b2f2 100644 --- a/tests/lib/Federation/CloudIdManagerTest.php +++ b/tests/lib/Federation/CloudIdManagerTest.php @@ -56,7 +56,7 @@ class CloudIdManagerTest extends TestCase { $this->overwriteService(ICloudIdManager::class, $this->cloudIdManager); } - public function dataGetDisplayNameFromContact(): array { + public static function dataGetDisplayNameFromContact(): array { return [ ['test1@example.tld', 'test', 'test'], ['test2@example.tld', null, null], @@ -84,7 +84,7 @@ class CloudIdManagerTest extends TestCase { $this->assertEquals($expected, $this->cloudIdManager->getDisplayNameFromContact($cloudId)); } - public function cloudIdProvider(): array { + public static function cloudIdProvider(): array { return [ ['test@example.com', 'test', 'example.com', 'test@example.com'], ['test@example.com/cloud', 'test', 'example.com/cloud', 'test@example.com/cloud'], @@ -122,7 +122,7 @@ class CloudIdManagerTest extends TestCase { $this->assertEquals($displayName . '@' . $noProtocolRemote, $cloudId->getDisplayId()); } - public function invalidCloudIdProvider(): array { + public static function invalidCloudIdProvider(): array { return [ ['example.com'], ['test:foo@example.com'], @@ -142,7 +142,7 @@ class CloudIdManagerTest extends TestCase { $this->cloudIdManager->resolveCloudId($cloudId); } - public function getCloudIdProvider(): array { + public static function getCloudIdProvider(): array { return [ ['test', 'example.com', 'test@example.com', null, 'https://example.com', 'https://example.com'], ['test', 'http://example.com', 'test@http://example.com', 'test@example.com'], diff --git a/tests/lib/Federation/CloudIdTest.php b/tests/lib/Federation/CloudIdTest.php index ca949d163c7..ec3cc15d6ff 100644 --- a/tests/lib/Federation/CloudIdTest.php +++ b/tests/lib/Federation/CloudIdTest.php @@ -28,7 +28,7 @@ class CloudIdTest extends TestCase { $this->overwriteService(ICloudIdManager::class, $this->cloudIdManager); } - public function dataGetDisplayCloudId(): array { + public static function dataGetDisplayCloudId(): array { return [ ['test@example.com', 'test', 'example.com', 'test@example.com'], ['test@http://example.com', 'test', 'http://example.com', 'test@example.com'], diff --git a/tests/lib/Files/Cache/CacheTest.php b/tests/lib/Files/Cache/CacheTest.php index 204f87d6a18..55b210a1e2d 100644 --- a/tests/lib/Files/Cache/CacheTest.php +++ b/tests/lib/Files/Cache/CacheTest.php @@ -49,6 +49,25 @@ class CacheTest extends \Test\TestCase { */ protected $cache2; + protected function setUp(): void { + parent::setUp(); + + $this->storage = new \OC\Files\Storage\Temporary([]); + $this->storage2 = new \OC\Files\Storage\Temporary([]); + $this->cache = new \OC\Files\Cache\Cache($this->storage); + $this->cache2 = new \OC\Files\Cache\Cache($this->storage2); + $this->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]); + $this->cache2->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]); + } + + protected function tearDown(): void { + if ($this->cache) { + $this->cache->clear(); + } + + parent::tearDown(); + } + public function testGetNumericId(): void { $this->assertNotNull($this->cache->getNumericStorageId()); } @@ -208,7 +227,7 @@ class CacheTest extends \Test\TestCase { } } - public function folderDataProvider() { + public static function folderDataProvider(): array { return [ ['folder'], // that was too easy, try something harder @@ -301,7 +320,7 @@ class CacheTest extends \Test\TestCase { $this->assertEquals(\OC\Files\Cache\Cache::COMPLETE, $this->cache->getStatus('foo')); } - public function putWithAllKindOfQuotesData() { + public static function putWithAllKindOfQuotesData(): array { return [ ['`backtick`'], ['´forward´'], @@ -437,7 +456,7 @@ class CacheTest extends \Test\TestCase { new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN_EQUAL, 'size', 100), 10, 0, [], $user))); } - public function movePathProvider() { + public static function movePathProvider(): array { return [ ['folder/foo', 'folder/foobar', ['1', '2']], ['folder/foo', 'foo', ['1', '2']], @@ -575,7 +594,7 @@ class CacheTest extends \Test\TestCase { * @var \OC\Files\Cache\Cache | \PHPUnit\Framework\MockObject\MockObject $cacheMock */ $cacheMock = $this->getMockBuilder(Cache::class) - ->setMethods(['normalize']) + ->onlyMethods(['normalize']) ->setConstructorArgs([$this->storage]) ->getMock(); @@ -646,7 +665,7 @@ class CacheTest extends \Test\TestCase { $this->assertEquals(1, count($this->cache->getFolderContents('folder'))); } - public function bogusPathNamesProvider() { + public static function bogusPathNamesProvider(): array { return [ ['/bogus.txt', 'bogus.txt'], ['//bogus.txt', 'bogus.txt'], @@ -691,7 +710,7 @@ class CacheTest extends \Test\TestCase { $this->assertNotEquals($fileId, $fileId2); } - public function escapingProvider() { + public static function escapingProvider(): array { return [ ['foo'], ['o%'], @@ -807,23 +826,4 @@ class CacheTest extends \Test\TestCase { $this->cache->remove('sub'); } - - protected function tearDown(): void { - if ($this->cache) { - $this->cache->clear(); - } - - parent::tearDown(); - } - - protected function setUp(): void { - parent::setUp(); - - $this->storage = new \OC\Files\Storage\Temporary([]); - $this->storage2 = new \OC\Files\Storage\Temporary([]); - $this->cache = new \OC\Files\Cache\Cache($this->storage); - $this->cache2 = new \OC\Files\Cache\Cache($this->storage2); - $this->cache->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]); - $this->cache2->insert('', ['size' => 0, 'mtime' => 0, 'mimetype' => ICacheEntry::DIRECTORY_MIMETYPE]); - } } diff --git a/tests/lib/Files/Cache/ScannerTest.php b/tests/lib/Files/Cache/ScannerTest.php index d78b7100d43..dc5ba5d3cdf 100644 --- a/tests/lib/Files/Cache/ScannerTest.php +++ b/tests/lib/Files/Cache/ScannerTest.php @@ -394,7 +394,7 @@ class ScannerTest extends TestCase { ); } - public function dataTestIsPartialFile() { + public static function dataTestIsPartialFile(): array { return [ ['foo.txt.part', true], ['/sub/folder/foo.txt.part', true], diff --git a/tests/lib/Files/Cache/SearchBuilderTest.php b/tests/lib/Files/Cache/SearchBuilderTest.php index 17285d44209..28af199639a 100644 --- a/tests/lib/Files/Cache/SearchBuilderTest.php +++ b/tests/lib/Files/Cache/SearchBuilderTest.php @@ -134,7 +134,7 @@ class SearchBuilderTest extends TestCase { return $rows; } - public function comparisonProvider() { + public static function comparisonProvider(): array { return [ [new SearchComparison(ISearchComparison::COMPARE_GREATER_THAN, 'mtime', 125), [1]], [new SearchComparison(ISearchComparison::COMPARE_LESS_THAN, 'mtime', 125), [0]], diff --git a/tests/lib/Files/Cache/UpdaterTest.php b/tests/lib/Files/Cache/UpdaterTest.php index ab46bdd4141..bc4b39a5dc4 100644 --- a/tests/lib/Files/Cache/UpdaterTest.php +++ b/tests/lib/Files/Cache/UpdaterTest.php @@ -305,7 +305,7 @@ class UpdaterTest extends \Test\TestCase { } } - public function changeExtensionProvider(): array { + public static function changeExtensionProvider(): array { return [ [new Temporary()], [new ObjectStoreStorage(['objectstore' => new StorageObjectStore(new Temporary())])] diff --git a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php index afb5c6a5d4d..9aa1ee5b723 100644 --- a/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php +++ b/tests/lib/Files/Cache/Wrapper/CachePermissionsMaskTest.php @@ -34,7 +34,7 @@ class CachePermissionsMaskTest extends CacheTest { return new \OC\Files\Cache\Wrapper\CachePermissionsMask($this->sourceCache, $mask); } - public function maskProvider() { + public static function maskProvider(): array { return [ [Constants::PERMISSION_ALL], [Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE], diff --git a/tests/lib/Files/Config/UserMountCacheTest.php b/tests/lib/Files/Config/UserMountCacheTest.php index 1efc56c1908..88b8b7767dd 100644 --- a/tests/lib/Files/Config/UserMountCacheTest.php +++ b/tests/lib/Files/Config/UserMountCacheTest.php @@ -9,6 +9,7 @@ namespace Test\Files\Config; use OC\DB\Exceptions\DbalException; use OC\DB\QueryBuilder\Literal; +use OC\Files\Cache\Cache; use OC\Files\Mount\MountPoint; use OC\Files\Storage\Storage; use OC\User\Manager; @@ -88,25 +89,19 @@ class UserMountCacheTest extends TestCase { private function getStorage($storageId, $rootInternalPath = '') { $rootId = $this->createCacheEntry($rootInternalPath, $storageId); - $storageCache = $this->getMockBuilder('\OC\Files\Cache\Storage') - ->disableOriginalConstructor() - ->getMock(); + $storageCache = $this->createMock(\OC\Files\Cache\Storage::class); $storageCache->expects($this->any()) ->method('getNumericId') ->willReturn($storageId); - $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') - ->disableOriginalConstructor() - ->getMock(); + $cache = $this->createMock(Cache::class); $cache->expects($this->any()) ->method('getId') ->willReturn($rootId); $cache->method('getNumericStorageId') ->willReturn($storageId); - $storage = $this->getMockBuilder('\OC\Files\Storage\Storage') - ->disableOriginalConstructor() - ->getMock(); + $storage = $this->createMock(Storage::class); $storage->expects($this->any()) ->method('getStorageCache') ->willReturn($storageCache); @@ -427,9 +422,9 @@ class UserMountCacheTest extends TestCase { $fileId = $this->createCacheEntry('/foo/bar', 2); - $mount1 = $this->getMockBuilder('\OC\Files\Mount\MountPoint') + $mount1 = $this->getMockBuilder(MountPoint::class) ->setConstructorArgs([$storage1, '/']) - ->setMethods(['getStorageRootId']) + ->onlyMethods(['getStorageRootId']) ->getMock(); $mount1->expects($this->any()) @@ -460,9 +455,9 @@ class UserMountCacheTest extends TestCase { $folderId = $this->createCacheEntry('/foo', 2); $fileId = $this->createCacheEntry('/bar/asd', 2); - $mount1 = $this->getMockBuilder('\OC\Files\Mount\MountPoint') + $mount1 = $this->getMockBuilder(MountPoint::class) ->setConstructorArgs([$storage1, '/foo/']) - ->setMethods(['getStorageRootId']) + ->onlyMethods(['getStorageRootId']) ->getMock(); $mount1->expects($this->any()) @@ -509,7 +504,7 @@ class UserMountCacheTest extends TestCase { $mount1 = $this->getMockBuilder(MountPoint::class) ->setConstructorArgs([$storage1, '/u1/']) - ->setMethods(['getStorageRootId', 'getNumericStorageId']) + ->onlyMethods(['getStorageRootId', 'getNumericStorageId']) ->getMock(); $mount1->expects($this->any()) diff --git a/tests/lib/Files/FilenameValidatorTest.php b/tests/lib/Files/FilenameValidatorTest.php index c5361e2c648..db7874b0bd5 100644 --- a/tests/lib/Files/FilenameValidatorTest.php +++ b/tests/lib/Files/FilenameValidatorTest.php @@ -122,7 +122,7 @@ class FilenameValidatorTest extends TestCase { $this->assertEquals($exception === null, $validator->isFilenameValid($filename)); } - public function dataValidateFilename(): array { + public static function dataValidateFilename(): array { return [ 'valid name' => [ 'a: b.txt', ['.htaccess'], [], [], [], null @@ -202,7 +202,7 @@ class FilenameValidatorTest extends TestCase { $validator->validateFilename($filename); } - public function data4ByteUnicode(): array { + public static function data4ByteUnicode(): array { return [ ['plane 1 𐪅'], ['emoji 😶🌫️'], @@ -218,7 +218,7 @@ class FilenameValidatorTest extends TestCase { $validator->validateFilename($filename); } - public function dataInvalidAsciiCharacters(): array { + public static function dataInvalidAsciiCharacters(): array { return [ [\chr(0)], [\chr(1)], @@ -271,7 +271,7 @@ class FilenameValidatorTest extends TestCase { $this->assertEquals($expected, $validator->isForbidden($filename)); } - public function dataIsForbidden(): array { + public static function dataIsForbidden(): array { return [ 'valid name' => [ 'a: b.txt', ['.htaccess'], false diff --git a/tests/lib/Files/FilesystemTest.php b/tests/lib/Files/FilesystemTest.php index a920dc662da..4a3543474a1 100644 --- a/tests/lib/Files/FilesystemTest.php +++ b/tests/lib/Files/FilesystemTest.php @@ -100,7 +100,7 @@ class FilesystemTest extends \Test\TestCase { $this->assertEquals('folder', $internalPath); } - public function normalizePathData() { + public static function normalizePathData(): array { return [ ['/', ''], ['/', '/'], @@ -201,7 +201,7 @@ class FilesystemTest extends \Test\TestCase { $this->assertEquals($expected, \OC\Files\Filesystem::normalizePath($path, $stripTrailingSlash)); } - public function normalizePathKeepUnicodeData() { + public static function normalizePathKeepUnicodeData(): array { $nfdName = 'ümlaut'; $nfcName = 'ümlaut'; return [ @@ -227,7 +227,7 @@ class FilesystemTest extends \Test\TestCase { $this->assertEquals('/' . $nfdName, \OC\Files\Filesystem::normalizePath($nfdName, true, false, true)); } - public function isValidPathData() { + public static function isValidPathData(): array { return [ ['/', true], ['/path', true], @@ -260,7 +260,7 @@ class FilesystemTest extends \Test\TestCase { $this->assertSame($expected, \OC\Files\Filesystem::isValidPath($path)); } - public function isFileBlacklistedData() { + public static function isFileBlacklistedData(): array { return [ ['/etc/foo/bar/foo.txt', false], ['\etc\foo/bar\foo.txt', false], diff --git a/tests/lib/Files/Node/FileTest.php b/tests/lib/Files/Node/FileTest.php index a67c9433663..74a23520344 100644 --- a/tests/lib/Files/Node/FileTest.php +++ b/tests/lib/Files/Node/FileTest.php @@ -7,6 +7,8 @@ namespace Test\Files\Node; +use OC\Files\Node\Root; + /** * Class FileTest * @@ -14,7 +16,7 @@ namespace Test\Files\Node; * * @package Test\Files\Node */ -class FileTest extends NodeTest { +class FileTest extends NodeTestCase { protected function createTestNode($root, $view, $path, array $data = [], $internalPath = '', $storage = null) { if ($data || $internalPath || $storage) { return new \OC\Files\Node\File($root, $view, $path, $this->getFileInfo($data, $internalPath, $storage)); @@ -37,7 +39,7 @@ class FileTest extends NodeTest { public function testGetContent(): void { /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); @@ -67,7 +69,7 @@ class FileTest extends NodeTest { $this->expectException(\OCP\Files\NotPermittedException::class); /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); @@ -86,7 +88,7 @@ class FileTest extends NodeTest { public function testPutContent(): void { /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); @@ -113,7 +115,7 @@ class FileTest extends NodeTest { $this->expectException(\OCP\Files\NotPermittedException::class); /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); @@ -128,7 +130,7 @@ class FileTest extends NodeTest { public function testGetMimeType(): void { /** @var \OC\Files\Node\Root|\PHPUnit\Framework\MockObject\MockObject $root */ - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); diff --git a/tests/lib/Files/Node/FolderTest.php b/tests/lib/Files/Node/FolderTest.php index e3edf202f8e..25f555e7068 100644 --- a/tests/lib/Files/Node/FolderTest.php +++ b/tests/lib/Files/Node/FolderTest.php @@ -40,7 +40,7 @@ use PHPUnit\Framework\MockObject\MockObject; * * @package Test\Files\Node */ -class FolderTest extends NodeTest { +class FolderTest extends NodeTestCase { protected function createTestNode($root, $view, $path, array $data = [], $internalPath = '', $storage = null) { $view->expects($this->any()) ->method('getRoot') @@ -337,7 +337,7 @@ class FolderTest extends NodeTest { $manager = $this->createMock(Manager::class); $view = $this->getRootViewMock(); $root = $this->getMockBuilder(Root::class) - ->setMethods(['getUser', 'getMountsIn', 'getMount']) + ->onlyMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); $root->expects($this->any()) @@ -499,7 +499,7 @@ class FolderTest extends NodeTest { $manager = $this->createMock(Manager::class); $view = $this->getRootViewMock(); $root = $this->getMockBuilder(Root::class) - ->setMethods(['getMountsIn', 'getMount']) + ->onlyMethods(['getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); $storage = $this->createMock(\OC\Files\Storage\Storage::class); @@ -548,7 +548,7 @@ class FolderTest extends NodeTest { $manager = $this->createMock(Manager::class); $view = $this->getRootViewMock(); $root = $this->getMockBuilder(Root::class) - ->setMethods(['getMountsIn', 'getMount']) + ->onlyMethods(['getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); $storage = $this->createMock(\OC\Files\Storage\Storage::class); @@ -593,7 +593,7 @@ class FolderTest extends NodeTest { $manager = $this->createMock(Manager::class); $view = $this->getRootViewMock(); $root = $this->getMockBuilder(Root::class) - ->setMethods(['getMountsIn', 'getMount']) + ->onlyMethods(['getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); $storage = $this->createMock(\OC\Files\Storage\Storage::class); @@ -637,7 +637,7 @@ class FolderTest extends NodeTest { $manager = $this->createMock(Manager::class); $view = $this->getRootViewMock(); $root = $this->getMockBuilder(Root::class) - ->setMethods(['getMountsIn', 'getMount']) + ->onlyMethods(['getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); $storage = $this->createMock(\OC\Files\Storage\Storage::class); @@ -681,7 +681,7 @@ class FolderTest extends NodeTest { $this->assertEquals('/bar/foo/asd/foo/qwerty', $result[1]->getPath()); } - public function uniqueNameProvider() { + public static function uniqueNameProvider(): array { return [ // input, existing, expected ['foo', [], 'foo'], @@ -698,7 +698,7 @@ class FolderTest extends NodeTest { $folderPath = '/bar/foo'; $view = $this->getRootViewMock(); $root = $this->getMockBuilder(Root::class) - ->setMethods(['getUser', 'getMountsIn', 'getMount']) + ->onlyMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); @@ -723,7 +723,7 @@ class FolderTest extends NodeTest { $view = $this->getRootViewMock(); /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */ $root = $this->getMockBuilder(Root::class) - ->setMethods(['getUser', 'getMountsIn', 'getMount']) + ->onlyMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */ @@ -792,7 +792,7 @@ class FolderTest extends NodeTest { $view = $this->getRootViewMock(); /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */ $root = $this->getMockBuilder(Root::class) - ->setMethods(['getUser', 'getMountsIn', 'getMount']) + ->onlyMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */ @@ -859,7 +859,7 @@ class FolderTest extends NodeTest { $view = $this->getRootViewMock(); /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\Node\Root $root */ $root = $this->getMockBuilder(Root::class) - ->setMethods(['getUser', 'getMountsIn', 'getMount']) + ->onlyMethods(['getUser', 'getMountsIn', 'getMount']) ->setConstructorArgs([$manager, $view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); /** @var \PHPUnit\Framework\MockObject\MockObject|\OC\Files\FileInfo $folderInfo */ @@ -910,7 +910,7 @@ class FolderTest extends NodeTest { $this->assertEquals([$id1], $ids); } - public function offsetLimitProvider() { + public static function offsetLimitProvider(): array { return [ [0, 10, ['/bar/foo/foo1', '/bar/foo/foo2', '/bar/foo/foo3', '/bar/foo/foo4', '/bar/foo/sub1/foo5', '/bar/foo/sub1/foo6', '/bar/foo/sub2/foo7', '/bar/foo/sub2/foo8'], []], [0, 5, ['/bar/foo/foo1', '/bar/foo/foo2', '/bar/foo/foo3', '/bar/foo/foo4', '/bar/foo/sub1/foo5'], []], diff --git a/tests/lib/Files/Node/HookConnectorTest.php b/tests/lib/Files/Node/HookConnectorTest.php index 1a3337b9ddc..b9e16299dd0 100644 --- a/tests/lib/Files/Node/HookConnectorTest.php +++ b/tests/lib/Files/Node/HookConnectorTest.php @@ -96,7 +96,7 @@ class HookConnectorTest extends TestCase { \OC_Util::tearDownFS(); } - public function viewToNodeProvider() { + public static function viewToNodeProvider(): array { return [ [function () { Filesystem::file_put_contents('test.txt', 'asd'); @@ -195,7 +195,7 @@ class HookConnectorTest extends TestCase { $this->assertEquals('/' . $this->userId . '/files/test.txt', $newDispatcherNode->getPath()); } - public function viewToNodeProviderCopyRename() { + public static function viewToNodeProviderCopyRename(): array { return [ [function () { Filesystem::file_put_contents('source', 'asd'); diff --git a/tests/lib/Files/Node/NodeTest.php b/tests/lib/Files/Node/NodeTestCase.php index db87aa925d3..a2b8a3ddffe 100644 --- a/tests/lib/Files/Node/NodeTest.php +++ b/tests/lib/Files/Node/NodeTestCase.php @@ -9,6 +9,7 @@ namespace Test\Files\Node; use OC\Files\FileInfo; use OC\Files\Mount\Manager; +use OC\Files\Node\Root; use OC\Files\View; use OC\Memcache\ArrayCache; use OCP\EventDispatcher\IEventDispatcher; @@ -27,7 +28,7 @@ use Psr\Log\LoggerInterface; * * @package Test\Files\Node */ -abstract class NodeTest extends \Test\TestCase { +abstract class NodeTestCase extends \Test\TestCase { /** @var \OC\User\User */ protected $user; /** @var \OC\Files\Mount\Manager */ @@ -71,7 +72,7 @@ abstract class NodeTest extends \Test\TestCase { ->willReturnCallback(function () { return new ArrayCache(); }); - $this->root = $this->getMockBuilder('\OC\Files\Node\Root') + $this->root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) ->getMock(); } @@ -592,7 +593,7 @@ abstract class NodeTest extends \Test\TestCase { $this->assertEquals('/bar/asd', $node->getPath()); } - public function moveOrCopyProvider() { + public static function moveOrCopyProvider(): array { return [ ['move', 'rename', 'preRename', 'postRename'], ['copy', 'copy', 'preCopy', 'postCopy'], @@ -608,9 +609,9 @@ abstract class NodeTest extends \Test\TestCase { */ public function testMoveCopyHooks($operationMethod, $viewMethod, $preHookName, $postHookName): void { /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject $root */ - $root = $this->getMockBuilder('\OC\Files\Node\Root') + $root = $this->getMockBuilder(Root::class) ->setConstructorArgs([$this->manager, $this->view, $this->user, $this->userMountCache, $this->logger, $this->userManager, $this->eventDispatcher, $this->cacheFactory]) - ->setMethods(['get']) + ->onlyMethods(['get']) ->getMock(); $this->view->expects($this->any()) diff --git a/tests/lib/Files/ObjectStore/AzureTest.php b/tests/lib/Files/ObjectStore/AzureTest.php index c82ed988434..1103b15ecd2 100644 --- a/tests/lib/Files/ObjectStore/AzureTest.php +++ b/tests/lib/Files/ObjectStore/AzureTest.php @@ -11,7 +11,7 @@ use OC\Files\ObjectStore\Azure; /** * @group PRIMARY-azure */ -class AzureTest extends ObjectStoreTest { +class AzureTest extends ObjectStoreTestCase { protected function getInstance() { $config = \OC::$server->getConfig()->getSystemValue('objectstore'); if (!is_array($config) || $config['class'] !== 'OC\\Files\\ObjectStore\\Azure') { diff --git a/tests/lib/Files/ObjectStore/LocalTest.php b/tests/lib/Files/ObjectStore/LocalTest.php index 99c5b61534f..3b561c01049 100644 --- a/tests/lib/Files/ObjectStore/LocalTest.php +++ b/tests/lib/Files/ObjectStore/LocalTest.php @@ -9,7 +9,7 @@ namespace Test\Files\ObjectStore; use OC\Files\ObjectStore\StorageObjectStore; use OC\Files\Storage\Temporary; -class LocalTest extends ObjectStoreTest { +class LocalTest extends ObjectStoreTestCase { /** * @return \OCP\Files\ObjectStore\IObjectStore */ diff --git a/tests/lib/Files/ObjectStore/MapperTest.php b/tests/lib/Files/ObjectStore/MapperTest.php index 15a2d497fc3..77416eae09a 100644 --- a/tests/lib/Files/ObjectStore/MapperTest.php +++ b/tests/lib/Files/ObjectStore/MapperTest.php @@ -29,7 +29,7 @@ class MapperTest extends \Test\TestCase { $this->mapper = new Mapper($this->user, $this->config); } - public function dataGetBucket() { + public static function dataGetBucket(): array { return [ ['user', 64, 0, '17'], ['USER', 64, 0, '0'], diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php index a0e18a5557b..a1befd4e79d 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreStoragesDifferentBucketTest.php @@ -9,12 +9,12 @@ namespace Test\Files\ObjectStore; use OC\Files\ObjectStore\StorageObjectStore; use OC\Files\Storage\Temporary; -use Test\Files\Storage\StoragesTest; +use Test\Files\Storage\StoragesTestCase; /** * @group DB */ -class ObjectStoreStoragesDifferentBucketTest extends StoragesTest { +class ObjectStoreStoragesDifferentBucketTest extends StoragesTestCase { /** * @var \OCP\Files\ObjectStore\IObjectStore */ diff --git a/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php b/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php index 19a1f4b7bc5..5505ee1dac1 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreStoragesSameBucketTest.php @@ -9,12 +9,12 @@ namespace Test\Files\ObjectStore; use OC\Files\ObjectStore\StorageObjectStore; use OC\Files\Storage\Temporary; -use Test\Files\Storage\StoragesTest; +use Test\Files\Storage\StoragesTestCase; /** * @group DB */ -class ObjectStoreStoragesSameBucketTest extends StoragesTest { +class ObjectStoreStoragesSameBucketTest extends StoragesTestCase { /** * @var \OCP\Files\ObjectStore\IObjectStore */ diff --git a/tests/lib/Files/ObjectStore/ObjectStoreTest.php b/tests/lib/Files/ObjectStore/ObjectStoreTestCase.php index 4a4f85dfb91..ecbfd9a37e6 100644 --- a/tests/lib/Files/ObjectStore/ObjectStoreTest.php +++ b/tests/lib/Files/ObjectStore/ObjectStoreTestCase.php @@ -9,10 +9,12 @@ namespace Test\Files\ObjectStore; use Test\TestCase; -abstract class ObjectStoreTest extends TestCase { +abstract class ObjectStoreTestCase extends TestCase { /** @var string[] */ private $cleanup = []; + private $instance = null; + /** * @return \OCP\Files\ObjectStore\IObjectStore */ @@ -22,13 +24,20 @@ abstract class ObjectStoreTest extends TestCase { $this->cleanup[] = $urn; } - public function tearDown(): void { - parent::tearDown(); + public function setUp(): void { + parent::setUp(); - $instance = $this->getInstance(); - foreach ($this->cleanup as $urn) { - $instance->deleteObject($urn); + $this->instance = $this->getInstance(); + } + + public function tearDown(): void { + if ($this->instance) { + foreach ($this->cleanup as $urn) { + $this->instance->deleteObject($urn); + } } + + parent::tearDown(); } protected function stringToStream($data) { diff --git a/tests/lib/Files/ObjectStore/S3Test.php b/tests/lib/Files/ObjectStore/S3Test.php index 1501f575f9a..76fc80c975f 100644 --- a/tests/lib/Files/ObjectStore/S3Test.php +++ b/tests/lib/Files/ObjectStore/S3Test.php @@ -44,7 +44,7 @@ class NonSeekableStream extends Wrapper { /** * @group PRIMARY-s3 */ -class S3Test extends ObjectStoreTest { +class S3Test extends ObjectStoreTestCase { public function setUp(): void { parent::setUp(); $s3 = $this->getInstance(); @@ -126,7 +126,7 @@ class S3Test extends ObjectStoreTest { } /** File size to upload in bytes */ - public function dataFileSizes() { + public static function dataFileSizes(): array { return [ [1000000], [2000000], [5242879], [5242880], [5242881], [10000000] ]; diff --git a/tests/lib/Files/ObjectStore/SwiftTest.php b/tests/lib/Files/ObjectStore/SwiftTest.php index 8a34d25e57b..9fb8c9bb68e 100644 --- a/tests/lib/Files/ObjectStore/SwiftTest.php +++ b/tests/lib/Files/ObjectStore/SwiftTest.php @@ -12,7 +12,7 @@ use OC\Files\ObjectStore\Swift; /** * @group PRIMARY-swift */ -class SwiftTest extends ObjectStoreTest { +class SwiftTest extends ObjectStoreTestCase { /** * @return \OCP\Files\ObjectStore\IObjectStore */ diff --git a/tests/lib/Files/PathVerificationTest.php b/tests/lib/Files/PathVerificationTest.php index fcbe0a6957f..d6dff445c0f 100644 --- a/tests/lib/Files/PathVerificationTest.php +++ b/tests/lib/Files/PathVerificationTest.php @@ -49,7 +49,7 @@ class PathVerificationTest extends \Test\TestCase { $this->view->verifyPath('', $fileName); } - public function providesEmptyFiles() { + public static function providesEmptyFiles(): array { return [ [''], [' '], @@ -66,7 +66,7 @@ class PathVerificationTest extends \Test\TestCase { $this->view->verifyPath('', $fileName); } - public function providesDotFiles() { + public static function providesDotFiles(): array { return [ ['.'], ['..'], @@ -95,7 +95,7 @@ class PathVerificationTest extends \Test\TestCase { $this->view->verifyPath('', $fileName); } - public function providesAstralPlane() { + public static function providesAstralPlane(): array { return [ // this is the monkey emoji - http://en.wikipedia.org/w/index.php?title=%F0%9F%90%B5&redirect=no ['🐵'], @@ -117,7 +117,7 @@ class PathVerificationTest extends \Test\TestCase { $this->addToAssertionCount(1); } - public function providesValidPosixPaths() { + public static function providesValidPosixPaths(): array { return [ ['simple'], ['simple.txt'], diff --git a/tests/lib/Files/Storage/Storage.php b/tests/lib/Files/Storage/Storage.php index 36d70965848..c6f051fb7e1 100644 --- a/tests/lib/Files/Storage/Storage.php +++ b/tests/lib/Files/Storage/Storage.php @@ -108,7 +108,7 @@ abstract class Storage extends \Test\TestCase { $this->assertEquals([], $content); } - public function fileNameProvider() { + public static function fileNameProvider(): array { return [ ['file.txt'], [' file.txt'], @@ -119,7 +119,7 @@ abstract class Storage extends \Test\TestCase { ]; } - public function directoryProvider() { + public static function directoryProvider(): array { return [ ['folder'], [' folder'], @@ -130,7 +130,7 @@ abstract class Storage extends \Test\TestCase { ]; } - public function loremFileProvider() { + public static function loremFileProvider(): array { $root = \OC::$SERVERROOT . '/tests/data/'; return [ // small file @@ -179,7 +179,7 @@ abstract class Storage extends \Test\TestCase { } - public function copyAndMoveProvider() { + public static function copyAndMoveProvider(): array { return [ ['/source.txt', '/target.txt'], ['/source.txt', '/target with space.txt'], @@ -414,7 +414,7 @@ abstract class Storage extends \Test\TestCase { $this->assertFalse($this->instance->file_exists('folder')); } - public function hashProvider() { + public static function hashProvider(): array { return [ ['Foobar', 'md5'], ['Foobar', 'sha1'], diff --git a/tests/lib/Files/Storage/StoragesTest.php b/tests/lib/Files/Storage/StoragesTestCase.php index 3f8198d331d..18fe78a93d1 100644 --- a/tests/lib/Files/Storage/StoragesTest.php +++ b/tests/lib/Files/Storage/StoragesTestCase.php @@ -9,7 +9,7 @@ namespace Test\Files\Storage; use Test\TestCase; -abstract class StoragesTest extends TestCase { +abstract class StoragesTestCase extends TestCase { /** * @var \OC\Files\Storage\Storage */ diff --git a/tests/lib/Files/Storage/Wrapper/EncodingTest.php b/tests/lib/Files/Storage/Wrapper/EncodingTest.php index d8b03a891c2..9d8a1e16145 100644 --- a/tests/lib/Files/Storage/Wrapper/EncodingTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncodingTest.php @@ -29,25 +29,25 @@ class EncodingTest extends \Test\Files\Storage\Storage { parent::tearDown(); } - public function directoryProvider() { + public static function directoryProvider(): array { $a = parent::directoryProvider(); $a[] = [self::NFC_NAME]; return $a; } - public function fileNameProvider() { + public static function fileNameProvider(): array { $a = parent::fileNameProvider(); $a[] = [self::NFD_NAME . '.txt']; return $a; } - public function copyAndMoveProvider() { + public static function copyAndMoveProvider(): array { $a = parent::copyAndMoveProvider(); $a[] = [self::NFD_NAME . '.txt', self::NFC_NAME . '-renamed.txt']; return $a; } - public function accessNameProvider() { + public static function accessNameProvider(): array { return [ [self::NFD_NAME], [self::NFC_NAME], @@ -110,7 +110,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertEquals('nfc', $this->instance->file_get_contents(self::NFC_NAME)); } - public function encodedDirectoriesProvider() { + public static function encodedDirectoriesProvider(): array { return [ [self::NFD_NAME, self::NFC_NAME], [self::NFD_NAME . '/' . self::NFD_NAME, self::NFC_NAME . '/' . self::NFC_NAME], @@ -150,7 +150,7 @@ class EncodingTest extends \Test\Files\Storage\Storage { $this->assertEquals('barbaric', $this->instance->file_get_contents('//' . self::NFC_NAME)); } - public function sourceAndTargetDirectoryProvider() { + public static function sourceAndTargetDirectoryProvider(): array { return [ [self::NFC_NAME . '1', self::NFC_NAME . '2'], [self::NFD_NAME . '1', self::NFC_NAME . '2'], diff --git a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php index e8ad557dae5..1c299fa989f 100644 --- a/tests/lib/Files/Storage/Wrapper/EncryptionTest.php +++ b/tests/lib/Files/Storage/Wrapper/EncryptionTest.php @@ -60,9 +60,9 @@ class EncryptionTest extends Storage { parent::setUp(); $mockModule = $this->buildMockModule(); - $this->encryptionManager = $this->getMockBuilder('\OC\Encryption\Manager') + $this->encryptionManager = $this->getMockBuilder(\OC\Encryption\Manager::class) ->disableOriginalConstructor() - ->setMethods(['getEncryptionModule', 'isEnabled']) + ->onlyMethods(['getEncryptionModule', 'isEnabled']) ->getMock(); $this->encryptionManager->expects($this->any()) ->method('getEncryptionModule') @@ -76,8 +76,8 @@ class EncryptionTest extends Storage { ->disableOriginalConstructor() ->getMock(); - $this->util = $this->getMockBuilder('\OC\Encryption\Util') - ->setMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension']) + $this->util = $this->getMockBuilder(Util::class) + ->onlyMethods(['getUidAndFilename', 'isFile', 'isExcluded', 'stripPartialFileExtension']) ->setConstructorArgs([new View(), new Manager( $this->config, $this->createMock(ICacheFactory::class), @@ -96,9 +96,9 @@ class EncryptionTest extends Storage { return $path; }); - $this->file = $this->getMockBuilder('\OC\Encryption\File') + $this->file = $this->getMockBuilder(File::class) ->disableOriginalConstructor() - ->setMethods(['getAccessList']) + ->onlyMethods(['getAccessList']) ->getMock(); $this->file->expects($this->any())->method('getAccessList')->willReturn([]); @@ -106,12 +106,11 @@ class EncryptionTest extends Storage { $this->sourceStorage = new Temporary([]); - $this->keyStore = $this->getMockBuilder('\OC\Encryption\Keys\Storage') - ->disableOriginalConstructor()->getMock(); + $this->keyStore = $this->createMock(\OC\Encryption\Keys\Storage::class); - $this->mount = $this->getMockBuilder('\OC\Files\Mount\MountPoint') + $this->mount = $this->getMockBuilder(MountPoint::class) ->disableOriginalConstructor() - ->setMethods(['getOption']) + ->onlyMethods(['getOption']) ->getMock(); $this->mount->expects($this->any())->method('getOption')->willReturnCallback(function ($option, $default) { if ($option === 'encrypt' && $default === true) { @@ -154,7 +153,7 @@ class EncryptionTest extends Storage { $this->arrayCache ] ) - ->setMethods(['getMetaData', 'getCache', 'getEncryptionModule']) + ->onlyMethods(['getMetaData', 'getCache', 'getEncryptionModule']) ->getMock(); $this->instance->expects($this->any()) @@ -175,7 +174,7 @@ class EncryptionTest extends Storage { protected function buildMockModule(): IEncryptionModule&MockObject { $this->encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') ->disableOriginalConstructor() - ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList']) + ->onlyMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList']) ->getMock(); $this->encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE'); @@ -235,7 +234,7 @@ class EncryptionTest extends Storage { $this->arrayCache, ] ) - ->setMethods(['getCache', 'verifyUnencryptedSize']) + ->onlyMethods(['getCache', 'verifyUnencryptedSize']) ->getMock(); if ($unencryptedSizeSet) { @@ -278,7 +277,7 @@ class EncryptionTest extends Storage { } } - public function dataTestGetMetaData() { + public static function dataTestGetMetaData(): array { return [ ['/test.txt', ['size' => 42, 'encrypted' => 2, 'encryptedVersion' => 2, 'fileid' => 1], true, true, 12, ['size' => 12, 'encrypted' => true, 'encryptedVersion' => 2]], ['/test.txt', null, true, true, 12, null], @@ -313,7 +312,7 @@ class EncryptionTest extends Storage { $this->arrayCache, ] ) - ->setMethods(['getCache', 'verifyUnencryptedSize']) + ->onlyMethods(['getCache', 'verifyUnencryptedSize']) ->getMock(); $this->instance->expects($this->any())->method('getCache')->willReturn($cache); @@ -357,7 +356,7 @@ class EncryptionTest extends Storage { $this->arrayCache, ] ) - ->setMethods(['fixUnencryptedSize']) + ->onlyMethods(['fixUnencryptedSize']) ->getMock(); $sourceStorage->expects($this->once())->method('filesize')->willReturn($encryptedSize); @@ -380,7 +379,7 @@ class EncryptionTest extends Storage { ); } - public function dataTestVerifyUnencryptedSize() { + public static function dataTestVerifyUnencryptedSize(): array { return [ [120, 80, false, 80], [120, 120, false, 80], @@ -435,7 +434,7 @@ class EncryptionTest extends Storage { * * @return array */ - public function dataTestCopyAndRename() { + public static function dataTestCopyAndRename(): array { return [ ['source', 'target', true, false, false], ['source', 'target', true, true, false], @@ -496,7 +495,7 @@ class EncryptionTest extends Storage { $encryptionStorage->rmdir($path); } - public function dataTestRmdir() { + public static function dataTestRmdir(): array { return [ ['/file.txt', true, true, true], ['/file.txt', false, true, true], @@ -531,7 +530,7 @@ class EncryptionTest extends Storage { ); } - public function dataTestCopyKeys() { + public static function dataTestCopyKeys(): array { return [ [true, false], [false, true], @@ -592,7 +591,7 @@ class EncryptionTest extends Storage { $this->arrayCache, ] ) - ->setMethods(['getCache', 'readFirstBlock']) + ->onlyMethods(['getCache', 'readFirstBlock']) ->getMock(); $instance->method('getCache')->willReturn($cache); @@ -618,7 +617,7 @@ class EncryptionTest extends Storage { $this->invokePrivate($instance, 'getHeader', [$path]); } - public function dataTestGetHeader() { + public static function dataTestGetHeader(): array { return [ ['/foo/bar.txt', false, '/foo/bar.txt'], ['/foo/bar.txt.part', false, '/foo/bar.txt'], @@ -635,7 +634,7 @@ class EncryptionTest extends Storage { * @dataProvider dataTestGetHeaderAddLegacyModule */ public function testGetHeaderAddLegacyModule($header, $isEncrypted, $strippedPathExists, $expected): void { - $sourceStorage = $this->getMockBuilder('\OC\Files\Storage\Storage') + $sourceStorage = $this->getMockBuilder(\OC\Files\Storage\Storage::class) ->disableOriginalConstructor()->getMock(); $sourceStorage->expects($this->once()) @@ -643,7 +642,7 @@ class EncryptionTest extends Storage { ->with('test.txt') ->willReturn($strippedPathExists); - $util = $this->getMockBuilder('\OC\Encryption\Util') + $util = $this->getMockBuilder(Util::class) ->onlyMethods(['stripPartialFileExtension', 'parseRawHeader']) ->setConstructorArgs([new View(), new Manager( $this->config, @@ -658,8 +657,7 @@ class EncryptionTest extends Storage { return $path; }); - $cache = $this->getMockBuilder('\OC\Files\Cache\Cache') - ->disableOriginalConstructor()->getMock(); + $cache = $this->createMock(Cache::class); $cache->expects($this->any()) ->method('get') ->willReturnCallback(function ($path) use ($isEncrypted) { @@ -685,7 +683,7 @@ class EncryptionTest extends Storage { $this->arrayCache, ] ) - ->setMethods(['readFirstBlock', 'getCache']) + ->onlyMethods(['readFirstBlock', 'getCache']) ->getMock(); $instance->method('readFirstBlock')->willReturn(''); @@ -701,7 +699,7 @@ class EncryptionTest extends Storage { } } - public function dataTestGetHeaderAddLegacyModule() { + public static function dataTestGetHeaderAddLegacyModule(): array { return [ [['cipher' => 'AES-128'], true, true, ['cipher' => 'AES-128', Util::HEADER_ENCRYPTION_MODULE_KEY => 'OC_DEFAULT_MODULE']], [[], true, false, []], @@ -710,7 +708,7 @@ class EncryptionTest extends Storage { ]; } - public function dataCopyBetweenStorage() { + public static function dataCopyBetweenStorage(): array { return [ [true, true, true], [true, false, false], @@ -859,7 +857,7 @@ class EncryptionTest extends Storage { $this->arrayCache ] ) - ->setMethods(['updateUnencryptedSize', 'getCache']) + ->onlyMethods(['updateUnencryptedSize', 'getCache']) ->getMock(); $targetStorage->expects($this->once())->method('copyFromStorage') @@ -901,7 +899,7 @@ class EncryptionTest extends Storage { $this->assertSame($copyResult, $result); } - public function dataTestCopyBetweenStorageVersions() { + public static function dataTestCopyBetweenStorageVersions(): array { return [ ['/files/foo.txt', '/files_versions/foo.txt.768743', true, true], ['/files/foo.txt', '/files_versions/foo.txt.768743', true, false], @@ -926,7 +924,7 @@ class EncryptionTest extends Storage { ); } - public function dataTestIsVersion() { + public static function dataTestIsVersion(): array { return [ ['files_versions/foo', true], ['/files_versions/foo', true], @@ -976,7 +974,7 @@ class EncryptionTest extends Storage { $arrayCache ] ) - ->setMethods(['getFullPath', 'getEncryptionModule']) + ->onlyMethods(['getFullPath', 'getEncryptionModule']) ->getMock(); if ($encryptionModule === true) { @@ -1018,7 +1016,7 @@ class EncryptionTest extends Storage { $this->assertSame($expected, $result); } - public function dataTestShouldEncrypt() { + public static function dataTestShouldEncrypt(): array { return [ [false, false, false, false], [true, false, false, false], diff --git a/tests/lib/Files/Storage/Wrapper/QuotaTest.php b/tests/lib/Files/Storage/Wrapper/QuotaTest.php index f07e6021e4e..aebae9b3c62 100644 --- a/tests/lib/Files/Storage/Wrapper/QuotaTest.php +++ b/tests/lib/Files/Storage/Wrapper/QuotaTest.php @@ -76,7 +76,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { public function testFreeSpaceWithUnknownDiskSpace(): void { $storage = $this->getMockBuilder(Local::class) - ->setMethods(['free_space']) + ->onlyMethods(['free_space']) ->setConstructorArgs([['datadir' => $this->tmpDir]]) ->getMock(); $storage->expects($this->any()) @@ -132,7 +132,7 @@ class QuotaTest extends \Test\Files\Storage\Storage { public function testReturnFalseWhenFopenFailed(): void { $failStorage = $this->getMockBuilder(Local::class) - ->setMethods(['fopen']) + ->onlyMethods(['fopen']) ->setConstructorArgs([['datadir' => $this->tmpDir]]) ->getMock(); $failStorage->expects($this->any()) diff --git a/tests/lib/Files/Stream/EncryptionTest.php b/tests/lib/Files/Stream/EncryptionTest.php index 36e72ea764a..c676358ad71 100644 --- a/tests/lib/Files/Stream/EncryptionTest.php +++ b/tests/lib/Files/Stream/EncryptionTest.php @@ -9,8 +9,12 @@ declare(strict_types=1); */ namespace Test\Files\Stream; +use OC\Encryption\File; +use OC\Encryption\Util; use OC\Files\Cache\CacheEntry; +use OC\Files\Storage\Storage; use OC\Files\Storage\Wrapper\Wrapper; +use OC\Files\Stream\Encryption; use OC\Files\View; use OC\Memcache\ArrayCache; use OCP\Encryption\IEncryptionModule; @@ -53,11 +57,11 @@ class EncryptionTest extends \Test\TestCase { ->getMock(); $file = $this->getMockBuilder('\OC\Encryption\File') ->disableOriginalConstructor() - ->setMethods(['getAccessList']) + ->onlyMethods(['getAccessList']) ->getMock(); $file->expects($this->any())->method('getAccessList')->willReturn([]); $util = $this->getMockBuilder('\OC\Encryption\Util') - ->setMethods(['getUidAndFilename']) + ->onlyMethods(['getUidAndFilename']) ->setConstructorArgs([new View(), new \OC\User\Manager( $config, $this->createMock(ICacheFactory::class), @@ -111,20 +115,17 @@ class EncryptionTest extends \Test\TestCase { $expectedReadOnly, ): void { // build mocks - $encryptionModuleMock = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') - ->disableOriginalConstructor()->getMock(); + $encryptionModuleMock = $this->createMock(IEncryptionModule::class); $encryptionModuleMock->expects($this->any())->method('needDetailedAccessList')->willReturn(!$isMasterKeyUsed); $encryptionModuleMock->expects($this->once()) ->method('getUnencryptedBlockSize')->willReturn(99); $encryptionModuleMock->expects($this->once()) ->method('begin')->willReturn([]); - $storageMock = $this->getMockBuilder('\OC\Files\Storage\Storage') - ->disableOriginalConstructor()->getMock(); + $storageMock = $this->createMock(Storage::class); $storageMock->expects($this->once())->method('file_exists')->willReturn($fileExists); - $fileMock = $this->getMockBuilder('\OC\Encryption\File') - ->disableOriginalConstructor()->getMock(); + $fileMock = $this->createMock(File::class); if ($isMasterKeyUsed) { $fileMock->expects($this->never())->method('getAccessList'); } else { @@ -134,18 +135,20 @@ class EncryptionTest extends \Test\TestCase { return []; }); } - $utilMock = $this->getMockBuilder('\OC\Encryption\Util') + $utilMock = $this->getMockBuilder(Util::class) ->disableOriginalConstructor()->getMock(); $utilMock->expects($this->any()) ->method('getHeaderSize') ->willReturn(8192); // get a instance of the stream wrapper - $streamWrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption') - ->setMethods(['loadContext', 'writeHeader', 'skipHeader'])->disableOriginalConstructor()->getMock(); + $streamWrapper = $this->getMockBuilder(Encryption::class) + ->onlyMethods(['loadContext', 'writeHeader', 'skipHeader']) + ->disableOriginalConstructor() + ->getMock(); // set internal properties of the stream wrapper - $stream = new \ReflectionClass('\OC\Files\Stream\Encryption'); + $stream = new \ReflectionClass(Encryption::class); $encryptionModule = $stream->getProperty('encryptionModule'); $encryptionModule->setAccessible(true); $encryptionModule->setValue($streamWrapper, $encryptionModuleMock); @@ -195,7 +198,7 @@ class EncryptionTest extends \Test\TestCase { $readOnly->setAccessible(false); } - public function dataProviderStreamOpen() { + public static function dataProviderStreamOpen(): array { return [ [false, 'r', '/foo/bar/test.txt', true, '/foo/bar/test.txt', null, null, true], [false, 'r', '/foo/bar/test.txt', false, '/foo/bar', null, null, true], @@ -266,7 +269,7 @@ class EncryptionTest extends \Test\TestCase { unlink($fileName); } - public function dataFilesProvider() { + public static function dataFilesProvider(): array { return [ ['lorem-big.txt'], ['block-aligned.txt'], @@ -315,9 +318,12 @@ class EncryptionTest extends \Test\TestCase { * @dataProvider dataFilesProvider */ public function testWriteToNonSeekableStorage($testFile): void { - $wrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption') - ->setMethods(['parentSeekStream'])->getMock(); - $wrapper->expects($this->any())->method('parentSeekStream')->willReturn(false); + $wrapper = $this->getMockBuilder(Encryption::class) + ->onlyMethods(['parentStreamSeek']) + ->getMock(); + $wrapper->expects($this->any()) + ->method('parentStreamSeek') + ->willReturn(false); $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile); // write it @@ -351,9 +357,9 @@ class EncryptionTest extends \Test\TestCase { } protected function buildMockModule(): IEncryptionModule&MockObject { - $encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule') + $encryptionModule = $this->getMockBuilder(IEncryptionModule::class) ->disableOriginalConstructor() - ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList']) + ->onlyMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList']) ->getMock(); $encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE'); diff --git a/tests/lib/Files/Stream/HashWrapperTest.php b/tests/lib/Files/Stream/HashWrapperTest.php index ee50fe3b13a..1e9bbd8f289 100644 --- a/tests/lib/Files/Stream/HashWrapperTest.php +++ b/tests/lib/Files/Stream/HashWrapperTest.php @@ -31,7 +31,7 @@ class HashWrapperTest extends TestCase { stream_get_contents($wrapper); } - public function hashProvider() { + public static function hashProvider(): array { return [ ['foo', 'md5', 'acbd18db4cc2f85cedef654fccc4a4d8'], ['foo', 'sha1', '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33'], diff --git a/tests/lib/Files/Utils/ScannerTest.php b/tests/lib/Files/Utils/ScannerTest.php index f66bb72e865..51089e5560c 100644 --- a/tests/lib/Files/Utils/ScannerTest.php +++ b/tests/lib/Files/Utils/ScannerTest.php @@ -138,10 +138,7 @@ class ScannerTest extends \Test\TestCase { $this->assertTrue($cache->inCache('folder/bar.txt')); } - /** - * @return array - */ - public function invalidPathProvider() { + public static function invalidPathProvider(): array { return [ [ '../', diff --git a/tests/lib/GlobalScale/ConfigTest.php b/tests/lib/GlobalScale/ConfigTest.php index aa001268ecd..b6c77c9ddf1 100644 --- a/tests/lib/GlobalScale/ConfigTest.php +++ b/tests/lib/GlobalScale/ConfigTest.php @@ -28,7 +28,7 @@ class ConfigTest extends TestCase { if (!empty($mockMethods)) { return $this->getMockBuilder(Config::class) ->setConstructorArgs([$this->config]) - ->setMethods($mockMethods) + ->onlyMethods($mockMethods) ->getMock(); } @@ -64,7 +64,7 @@ class ConfigTest extends TestCase { $this->assertSame($expected, $gsConfig->onlyInternalFederation()); } - public function dataTestOnlyInternalFederation() { + public static function dataTestOnlyInternalFederation(): array { return [ [true, 'global', false], [true, 'internal', true], diff --git a/tests/lib/Group/ManagerTest.php b/tests/lib/Group/ManagerTest.php index 0f8d7a5ecc3..e52e0733501 100644 --- a/tests/lib/Group/ManagerTest.php +++ b/tests/lib/Group/ManagerTest.php @@ -12,6 +12,11 @@ use OC\Group\Database; use OC\User\Manager; use OC\User\User; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Group\Backend\ABackend; +use OCP\Group\Backend\IAddToGroupBackend; +use OCP\Group\Backend\ICreateGroupBackend; +use OCP\Group\Backend\IGroupDetailsBackend; +use OCP\Group\Backend\IRemoveFromGroupBackend; use OCP\Group\Backend\ISearchableGroupBackend; use OCP\GroupInterface; use OCP\ICacheFactory; @@ -21,7 +26,8 @@ use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; -interface ISearchableGroupInterface extends ISearchableGroupBackend, GroupInterface { +abstract class TestBackend extends ABackend implements ISearchableGroupBackend, IAddToGroupBackend, ICreateGroupBackend, IGroupDetailsBackend, IRemoveFromGroupBackend, GroupInterface { + } class ManagerTest extends TestCase { @@ -74,9 +80,9 @@ class ManagerTest extends TestCase { } // need to declare it this way due to optional methods // thanks to the implementsActions logic - $backend = $this->getMockBuilder(ISearchableGroupInterface::class) + $backend = $this->getMockBuilder(TestBackend::class) ->disableOriginalConstructor() - ->setMethods([ + ->onlyMethods([ 'getGroupDetails', 'implementsActions', 'getUserGroups', @@ -283,9 +289,10 @@ class ManagerTest extends TestCase { ->with('1') ->willReturn(['group1']); $backend->expects($this->once()) - ->method('groupExists') - ->with('group1') - ->willReturn(true); + ->method('getGroupDetails') + ->willReturnMap([ + ['group1', ['displayName' => 'group1']], + ]); $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress); $manager->addBackend($backend); @@ -306,8 +313,11 @@ class ManagerTest extends TestCase { ->with('1') ->willReturn(['group1']); $backend1->expects($this->any()) - ->method('groupExists') - ->willReturn(true); + ->method('getGroupDetails') + ->willReturnMap([ + ['group1', ['displayName' => 'group1']], + ['group12', []], + ]); /** * @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend2 @@ -318,8 +328,11 @@ class ManagerTest extends TestCase { ->with('1') ->willReturn(['group12', 'group1']); $backend2->expects($this->any()) - ->method('groupExists') - ->willReturn(true); + ->method('getGroupDetails') + ->willReturnMap([ + ['group12', ['displayName' => 'group12']], + ['group1', ['displayName' => 'group1']], + ]); $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress); $manager->addBackend($backend1); @@ -335,7 +348,7 @@ class ManagerTest extends TestCase { public function testSearchMultipleBackendsLimitAndOffset(): void { /** - * @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend1 + * @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend1 */ $backend1 = $this->getTestBackend(); $backend1->expects($this->once()) @@ -343,11 +356,16 @@ class ManagerTest extends TestCase { ->with('1', 2, 1) ->willReturn(['group1']); $backend1->expects($this->any()) - ->method('groupExists') - ->willReturn(true); + ->method('getGroupDetails') + ->willReturnMap([ + [1, []], + [2, []], + ['group1', ['displayName' => 'group1']], + ['group12', []], + ]); /** - * @var \PHPUnit\Framework\MockObject\MockObject | \OC\Group\Backend $backend2 + * @var \PHPUnit\Framework\MockObject\MockObject|\OC\Group\Backend $backend2 */ $backend2 = $this->getTestBackend(); $backend2->expects($this->once()) @@ -355,8 +373,13 @@ class ManagerTest extends TestCase { ->with('1', 2, 1) ->willReturn(['group12']); $backend2->expects($this->any()) - ->method('groupExists') - ->willReturn(true); + ->method('getGroupDetails') + ->willReturnMap([ + [1, []], + [2, []], + ['group1', []], + ['group12', ['displayName' => 'group12']], + ]); $manager = new \OC\Group\Manager($this->userManager, $this->dispatcher, $this->logger, $this->cache, $this->remoteIpAddress); $manager->addBackend($backend1); diff --git a/tests/lib/HelperStorageTest.php b/tests/lib/HelperStorageTest.php index 455bd288351..e4e877ab2a8 100644 --- a/tests/lib/HelperStorageTest.php +++ b/tests/lib/HelperStorageTest.php @@ -71,13 +71,13 @@ class HelperStorageTest extends \Test\TestCase { */ private function getStorageMock($freeSpace = 12) { $this->storageMock = $this->getMockBuilder(Temporary::class) - ->setMethods(['free_space']) + ->onlyMethods(['free_space']) ->setConstructorArgs([[]]) ->getMock(); $this->storageMock->expects($this->once()) ->method('free_space') - ->willReturn(12); + ->willReturn($freeSpace); return $this->storageMock; } diff --git a/tests/lib/ImageTest.php b/tests/lib/ImageTest.php index 5de5435335a..494f616ac9c 100644 --- a/tests/lib/ImageTest.php +++ b/tests/lib/ImageTest.php @@ -271,7 +271,7 @@ class ImageTest extends \Test\TestCase { $this->assertEquals(15, $img->height()); } - public static function sampleProvider() { + public static function sampleProvider(): array { return [ ['testimage.png', [200, 100], [100, 100]], ['testimage.jpg', [840, 840], [840, 525]], @@ -294,7 +294,7 @@ class ImageTest extends \Test\TestCase { $this->assertEquals($expected[1], $img->height()); } - public static function sampleFilenamesProvider() { + public static function sampleFilenamesProvider(): array { return [ ['testimage.png'], ['testimage.jpg'], @@ -328,7 +328,7 @@ class ImageTest extends \Test\TestCase { ); } - public static function largeSampleProvider() { + public static function largeSampleProvider(): array { return [ ['testimage.png', [200, 100], [100, 100]], ['testimage.jpg', [840, 840], [840, 525]], @@ -351,7 +351,7 @@ class ImageTest extends \Test\TestCase { $this->assertEquals($expected[1], $img->height()); } - public function convertDataProvider() { + public static function convertDataProvider(): array { return [ [ 'image/gif'], [ 'image/jpeg'], diff --git a/tests/lib/InfoXmlTest.php b/tests/lib/InfoXmlTest.php index e579a4b4efd..ffc367d4471 100644 --- a/tests/lib/InfoXmlTest.php +++ b/tests/lib/InfoXmlTest.php @@ -23,7 +23,7 @@ class InfoXmlTest extends TestCase { $this->appManager = Server::get(IAppManager::class); } - public function dataApps() { + public static function dataApps(): array { return [ ['admin_audit'], ['comments'], diff --git a/tests/lib/InitialStateServiceTest.php b/tests/lib/InitialStateServiceTest.php index f58d54cb26b..5e0f7c7b55e 100644 --- a/tests/lib/InitialStateServiceTest.php +++ b/tests/lib/InitialStateServiceTest.php @@ -36,7 +36,7 @@ class InitialStateServiceTest extends TestCase { ); } - public function staticData(): array { + public static function staticData(): array { return [ ['string'], [23], diff --git a/tests/lib/InstallerTest.php b/tests/lib/InstallerTest.php index d27ca6e2159..9e77cb6a4fc 100644 --- a/tests/lib/InstallerTest.php +++ b/tests/lib/InstallerTest.php @@ -111,7 +111,7 @@ class InstallerTest extends TestCase { $installer->removeApp(self::$appid); } - public function updateArrayProvider() { + public static function updateArrayProvider(): array { return [ // Update available [ diff --git a/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php b/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php index 14cc8851178..1d0b3e4f24d 100644 --- a/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php +++ b/tests/lib/IntegrityCheck/Iterator/ExcludeFileByNameFilterIteratorTest.php @@ -17,11 +17,11 @@ class ExcludeFileByNameFilterIteratorTest extends TestCase { parent::setUp(); $this->filter = $this->getMockBuilder(ExcludeFileByNameFilterIterator::class) ->disableOriginalConstructor() - ->setMethods(['current']) + ->onlyMethods(['current']) ->getMock(); } - public function fileNameProvider(): array { + public static function fileNameProvider(): array { return [ ['a file', true], ['Thumbs.db', false], @@ -42,7 +42,7 @@ class ExcludeFileByNameFilterIteratorTest extends TestCase { public function testAcceptForFiles($fileName, $expectedResult): void { $iteratorMock = $this->getMockBuilder(\RecursiveDirectoryIterator::class) ->disableOriginalConstructor() - ->setMethods(['getFilename', 'isDir']) + ->onlyMethods(['getFilename', 'isDir']) ->getMock(); $iteratorMock->method('getFilename') @@ -64,7 +64,7 @@ class ExcludeFileByNameFilterIteratorTest extends TestCase { public function testAcceptForDirs($fileName, $expectedResult): void { $iteratorMock = $this->getMockBuilder(\RecursiveDirectoryIterator::class) ->disableOriginalConstructor() - ->setMethods(['getFilename', 'isDir']) + ->onlyMethods(['getFilename', 'isDir']) ->getMock(); $iteratorMock->method('getFilename') diff --git a/tests/lib/L10N/L10nTest.php b/tests/lib/L10N/L10nTest.php index 32b81cf06a7..a95a1241f4b 100644 --- a/tests/lib/L10N/L10nTest.php +++ b/tests/lib/L10N/L10nTest.php @@ -96,7 +96,7 @@ class L10nTest extends TestCase { $this->assertEquals('5 Dateien', (string)$l->n('%n file', '%n files', 5)); } - public function dataPlaceholders(): array { + public static function dataPlaceholders(): array { return [ ['Ordered placeholders one %s two %s', 'Placeholder one 1 two 2'], ['Reordered placeholders one %s two %s', 'Placeholder two 2 one 1'], @@ -117,7 +117,7 @@ class L10nTest extends TestCase { $this->assertEquals($expected, $l->t($string, ['1', '2'])); } - public function localizationData() { + public static function localizationData(): array { return [ // timestamp as string ["February 13, 2009, 11:31:30\xE2\x80\xAFPM UTC", 'en', 'en_US', 'datetime', '1234567890'], @@ -161,7 +161,7 @@ class L10nTest extends TestCase { $this->assertSame($expectedDate, $l->l($type, $value)); } - public function firstDayData() { + public static function firstDayData(): array { return [ [1, 'de', 'de_DE'], [0, 'en', 'en_US'], @@ -179,7 +179,7 @@ class L10nTest extends TestCase { $this->assertSame($expected, $l->l('firstday', 'firstday')); } - public function jsDateData() { + public static function jsDateData(): array { return [ ['dd.MM.yy', 'de', 'de_DE'], ['M/d/yy', 'en', 'en_US'], @@ -224,10 +224,7 @@ class L10nTest extends TestCase { ); } - /** - * @return array - */ - public function findLanguageFromLocaleData(): array { + public static function findLanguageFromLocaleData(): array { return [ 'en_US' => ['en_US', 'en'], 'en_UK' => ['en_UK', 'en'], diff --git a/tests/lib/L10N/LanguageIteratorTest.php b/tests/lib/L10N/LanguageIteratorTest.php index 79998c36354..e328941e35d 100644 --- a/tests/lib/L10N/LanguageIteratorTest.php +++ b/tests/lib/L10N/LanguageIteratorTest.php @@ -28,7 +28,7 @@ class LanguageIteratorTest extends TestCase { $this->iterator = new LanguageIterator($this->user, $this->config); } - public function languageSettingsProvider() { + public static function languageSettingsProvider(): array { return [ // all language settings set [ 'de_DE', 'es_CU', 'zh_TW', ['de_DE', 'de', 'es_CU', 'es', 'zh_TW', 'zh', 'en']], diff --git a/tests/lib/LargeFileHelperGetFileSizeTest.php b/tests/lib/LargeFileHelperGetFileSizeTest.php index 247886fee6a..7f6604bdb35 100644 --- a/tests/lib/LargeFileHelperGetFileSizeTest.php +++ b/tests/lib/LargeFileHelperGetFileSizeTest.php @@ -26,7 +26,7 @@ class LargeFileHelperGetFileSizeTest extends TestCase { $this->helper = new \OC\LargeFileHelper(); } - public function dataFileNameProvider() { + public static function dataFileNameProvider(): array { $path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR; return [ diff --git a/tests/lib/LegacyHelperTest.php b/tests/lib/LegacyHelperTest.php index ea359d4e50c..15af5ca06e8 100644 --- a/tests/lib/LegacyHelperTest.php +++ b/tests/lib/LegacyHelperTest.php @@ -31,7 +31,7 @@ class LegacyHelperTest extends \Test\TestCase { $this->assertEquals($expected, $result); } - public function humanFileSizeProvider() { + public static function humanFileSizeProvider(): array { return [ ['0 B', 0], ['1 KB', 1024], @@ -51,7 +51,7 @@ class LegacyHelperTest extends \Test\TestCase { $this->assertEquals($expected, $result); } - public function providesComputerFileSize() { + public static function providesComputerFileSize(): array { return [ [0.0, '0 B'], [1024.0, '1 KB'], @@ -110,95 +110,87 @@ class LegacyHelperTest extends \Test\TestCase { $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(2)) ->method('file_exists') - ->withConsecutive( + ->willReturnMap([ // Conflict on filename.ext - ['dir/filename.ext'], - ['dir/filename (2).ext'], - ) - ->will($this->onConsecutiveCalls(true, false)); + ['dir/filename.ext', true], + ['dir/filename (2).ext', false], + ]); $this->assertEquals('dir/filename (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(3)) ->method('file_exists') - ->withConsecutive( - ['dir/filename.ext'], - ['dir/filename (2).ext'], - ['dir/filename (3).ext'], - ) - ->will($this->onConsecutiveCalls(true, true, false)); + ->willReturnMap([ + // Conflict on filename.ext + ['dir/filename.ext', true], + ['dir/filename (2).ext', true], + ['dir/filename (3).ext', false], + ]); $this->assertEquals('dir/filename (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename.ext', $viewMock)); $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(2)) ->method('file_exists') - ->withConsecutive( - ['dir/filename (1).ext'], - ['dir/filename (2).ext'], - ) - ->will($this->onConsecutiveCalls(true, false)); + ->willReturnMap([ + ['dir/filename (1).ext', true], + ['dir/filename (2).ext', false], + ]); $this->assertEquals('dir/filename (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (1).ext', $viewMock)); $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(2)) ->method('file_exists') - ->withConsecutive( - ['dir/filename (2).ext'], - ['dir/filename (3).ext'], - ) - ->will($this->onConsecutiveCalls(true, false)); + ->willReturnMap([ + ['dir/filename (2).ext', true], + ['dir/filename (3).ext', false], + ]); $this->assertEquals('dir/filename (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (2).ext', $viewMock)); $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(3)) ->method('file_exists') - ->withConsecutive( - ['dir/filename (2).ext'], - ['dir/filename (3).ext'], - ['dir/filename (4).ext'], - ) - ->will($this->onConsecutiveCalls(true, true, false)); + ->willReturnMap([ + ['dir/filename (2).ext', true], + ['dir/filename (3).ext', true], + ['dir/filename (4).ext', false], + ]); $this->assertEquals('dir/filename (4).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename (2).ext', $viewMock)); $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(2)) ->method('file_exists') - ->withConsecutive( - ['dir/filename(1).ext'], - ['dir/filename(2).ext'], - ) - ->will($this->onConsecutiveCalls(true, false)); + ->willReturnMap([ + ['dir/filename(1).ext', true], + ['dir/filename(2).ext', false], + ]); $this->assertEquals('dir/filename(2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1).ext', $viewMock)); $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(2)) ->method('file_exists') - ->withConsecutive( - ['dir/filename(1) (1).ext'], - ['dir/filename(1) (2).ext'], - ) - ->will($this->onConsecutiveCalls(true, false)); + ->willReturnMap([ + ['dir/filename(1) (1).ext', true], + ['dir/filename(1) (2).ext', false], + ]); $this->assertEquals('dir/filename(1) (2).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (1).ext', $viewMock)); $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(3)) ->method('file_exists') - ->withConsecutive( - ['dir/filename(1) (1).ext'], - ['dir/filename(1) (2).ext'], - ['dir/filename(1) (3).ext'], - ) - ->will($this->onConsecutiveCalls(true, true, false)); + ->willReturnMap([ + ['dir/filename(1) (1).ext', true], + ['dir/filename(1) (2).ext', true], + ['dir/filename(1) (3).ext', false], + ]); $this->assertEquals('dir/filename(1) (3).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (1).ext', $viewMock)); $viewMock = $this->createMock(View::class); $viewMock->expects($this->exactly(2)) ->method('file_exists') - ->withConsecutive( - ['dir/filename(1) (2) (3).ext'], - ['dir/filename(1) (2) (4).ext'], - ) - ->will($this->onConsecutiveCalls(true, false)); + ->willReturnMap([ + ['dir/filename(1) (2) (3).ext', true], + ['dir/filename(1) (2) (4).ext', false], + ]); $this->assertEquals('dir/filename(1) (2) (4).ext', OC_Helper::buildNotExistingFileNameForView('dir', 'filename(1) (2) (3).ext', $viewMock)); } @@ -227,7 +219,7 @@ class LegacyHelperTest extends \Test\TestCase { } - public function streamCopyDataProvider() { + public static function streamCopyDataProvider(): array { return [ [0, false, false, false], [0, false, \OC::$SERVERROOT . '/tests/data/lorem.txt', false], @@ -260,17 +252,4 @@ class LegacyHelperTest extends \Test\TestCase { \OC_Helper::rmdirr($baseDir); $this->assertFalse(file_exists($baseDir)); } - - /** - * Allows us to test private methods/properties - * - * @param $object - * @param $methodName - * @param array $parameters - * @return mixed - * @deprecated Please extend \Test\TestCase and use self::invokePrivate() then - */ - public static function invokePrivate($object, $methodName, array $parameters = []) { - return parent::invokePrivate($object, $methodName, $parameters); - } } diff --git a/tests/lib/Log/PsrLoggerAdapterTest.php b/tests/lib/Log/PsrLoggerAdapterTest.php index cc9ddea378a..9a159ba537d 100644 --- a/tests/lib/Log/PsrLoggerAdapterTest.php +++ b/tests/lib/Log/PsrLoggerAdapterTest.php @@ -45,7 +45,7 @@ class PsrLoggerAdapterTest extends TestCase { $this->assertEquals($expectedLevel, PsrLoggerAdapter::logLevelToInt($level)); } - public function dataPsrLoggingLevels(): array { + public static function dataPsrLoggingLevels(): array { return [ [LogLevel::ALERT, ILogger::ERROR], [LogLevel::CRITICAL, ILogger::ERROR], @@ -69,7 +69,7 @@ class PsrLoggerAdapterTest extends TestCase { $this->loggerAdapter->log($level, 'valid message'); } - public function dataInvalidLoggingLevel(): array { + public static function dataInvalidLoggingLevel(): array { return [ // invalid string ['this is not a level'], diff --git a/tests/lib/LoggerTest.php b/tests/lib/LoggerTest.php index c7c60e892aa..5c8345b392b 100644 --- a/tests/lib/LoggerTest.php +++ b/tests/lib/LoggerTest.php @@ -72,7 +72,7 @@ class LoggerTest extends TestCase implements IWriter { $this->assertEquals($expected, $this->getLogs()); } - public function dataMatchesCondition(): array { + public static function dataMatchesCondition(): array { return [ [ 'user0', @@ -181,7 +181,7 @@ class LoggerTest extends TestCase implements IWriter { $this->logs[] = $level . ' ' . $textMessage; } - public function userAndPasswordData(): array { + public static function userAndPasswordData(): array { return [ ['mySpecialUsername', 'MySuperSecretPassword'], ['my-user', '324324()#ä234'], diff --git a/tests/lib/Mail/MailerTest.php b/tests/lib/Mail/MailerTest.php index 02a2605fc77..76a06e58c65 100644 --- a/tests/lib/Mail/MailerTest.php +++ b/tests/lib/Mail/MailerTest.php @@ -66,7 +66,7 @@ class MailerTest extends TestCase { /** * @return array */ - public function sendmailModeProvider(): array { + public static function sendmailModeProvider(): array { return [ 'smtp' => ['smtp', ' -bs'], 'pipe' => ['pipe', ' -t -i'], @@ -170,7 +170,7 @@ class MailerTest extends TestCase { ['mail_smtpport', 25, 25], ]); $this->mailer = $this->getMockBuilder(Mailer::class) - ->setMethods(['getInstance']) + ->onlyMethods(['getInstance']) ->setConstructorArgs( [ $this->config, @@ -227,7 +227,7 @@ class MailerTest extends TestCase { /** * @return array */ - public function mailAddressProvider() { + public static function mailAddressProvider(): array { return [ ['lukas@owncloud.com', true, false], ['lukas@localhost', true, false], diff --git a/tests/lib/Mail/MessageTest.php b/tests/lib/Mail/MessageTest.php index 260d3aaff76..79a12f3c355 100644 --- a/tests/lib/Mail/MessageTest.php +++ b/tests/lib/Mail/MessageTest.php @@ -27,7 +27,7 @@ class MessageTest extends TestCase { /** * @return array */ - public function mailAddressProvider() { + public static function mailAddressProvider(): array { return [ [ ['lukas@owncloud.com' => 'Lukas Reschke'], @@ -65,8 +65,7 @@ class MessageTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->symfonyEmail = $this->getMockBuilder(Email::class) - ->disableOriginalConstructor()->getMock(); + $this->symfonyEmail = $this->createMock(Email::class); $this->message = new Message($this->symfonyEmail, false); } diff --git a/tests/lib/Memcache/FactoryTest.php b/tests/lib/Memcache/FactoryTest.php index fa0d80c5153..cbf908e0cc6 100644 --- a/tests/lib/Memcache/FactoryTest.php +++ b/tests/lib/Memcache/FactoryTest.php @@ -56,7 +56,7 @@ class FactoryTest extends \Test\TestCase { public const UNAVAILABLE1 = '\\Test\\Memcache\\Test_Factory_Unavailable_Cache1'; public const UNAVAILABLE2 = '\\Test\\Memcache\\Test_Factory_Unavailable_Cache2'; - public function cacheAvailabilityProvider() { + public static function cacheAvailabilityProvider(): array { return [ [ // local and distributed available @@ -86,7 +86,7 @@ class FactoryTest extends \Test\TestCase { ]; } - public function cacheUnavailableProvider() { + public static function cacheUnavailableProvider(): array { return [ [ // local available, distributed unavailable diff --git a/tests/lib/MemoryInfoTest.php b/tests/lib/MemoryInfoTest.php index 2477de2d799..a81a5ebcaeb 100644 --- a/tests/lib/MemoryInfoTest.php +++ b/tests/lib/MemoryInfoTest.php @@ -37,12 +37,7 @@ class MemoryInfoTest extends TestCase { ini_set('memory_limit', $this->iniSettingBeforeTest); } - /** - * Provides test data. - * - * @return array - */ - public function getMemoryLimitTestData(): array { + public static function getMemoryLimitTestData(): array { return [ 'unlimited' => ['-1', -1,], '524288000 bytes' => ['524288000', 524288000,], @@ -65,12 +60,7 @@ class MemoryInfoTest extends TestCase { self::assertEquals($expected, $memoryInfo->getMemoryLimit()); } - /** - * Provides sufficient memory limit test data. - * - * @return array - */ - public function getSufficientMemoryTestData(): array { + public static function getSufficientMemoryTestData(): array { return [ 'unlimited' => [-1, true,], '512M' => [512 * 1024 * 1024, true,], @@ -85,12 +75,11 @@ class MemoryInfoTest extends TestCase { * @param int $memoryLimit The memory limit * @param bool $expected If the memory limit is sufficient. * @dataProvider getSufficientMemoryTestData - * @return void */ public function testIsMemoryLimitSufficient(int $memoryLimit, bool $expected): void { /* @var MemoryInfo|MockObject $memoryInfo */ $memoryInfo = $this->getMockBuilder(MemoryInfo::class) - ->setMethods(['getMemoryLimit',]) + ->onlyMethods(['getMemoryLimit',]) ->getMock(); $memoryInfo diff --git a/tests/lib/Migration/BackgroundRepairTest.php b/tests/lib/Migration/BackgroundRepairTest.php index 25ea6088072..b85bd4262e0 100644 --- a/tests/lib/Migration/BackgroundRepairTest.php +++ b/tests/lib/Migration/BackgroundRepairTest.php @@ -54,22 +54,15 @@ class BackgroundRepairTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->jobList = $this->getMockBuilder(JobList::class) - ->disableOriginalConstructor() - ->getMock(); - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->jobList = $this->createMock(JobList::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->dispatcher = $this->createMock(IEventDispatcher::class); $this->time = $this->createMock(ITimeFactory::class); $this->time->method('getTime') ->willReturn(999999); $this->appManager = $this->createMock(IAppManager::class); $this->repair = new Repair($this->dispatcher, $this->logger); - $this->job = $this->getMockBuilder(BackgroundRepair::class) - ->setConstructorArgs([$this->repair, $this->time, $this->logger, $this->jobList, $this->appManager]) - ->setMethods(['loadApp']) - ->getMock(); + $this->job = new BackgroundRepair($this->repair, $this->time, $this->logger, $this->jobList, $this->appManager); } public function testNoArguments(): void { diff --git a/tests/lib/NaturalSortTest.php b/tests/lib/NaturalSortTest.php index 3a07c5ceb66..833e2f5e3be 100644 --- a/tests/lib/NaturalSortTest.php +++ b/tests/lib/NaturalSortTest.php @@ -35,7 +35,7 @@ class NaturalSortTest extends \Test\TestCase { * Must provide the same result as in core/js/tests/specs/coreSpec.js * @return array test cases */ - public function naturalSortDataProvider() { + public static function naturalSortDataProvider(): array { return [ // different casing [ @@ -189,7 +189,7 @@ class NaturalSortTest extends \Test\TestCase { * Must provide the same result as in core/js/tests/specs/coreSpec.js * @return array test cases */ - public function defaultCollatorDataProvider() { + public static function defaultCollatorDataProvider(): array { return [ // different casing [ diff --git a/tests/lib/NavigationManagerTest.php b/tests/lib/NavigationManagerTest.php index 48cfa972f2b..986d2183a14 100644 --- a/tests/lib/NavigationManagerTest.php +++ b/tests/lib/NavigationManagerTest.php @@ -68,10 +68,10 @@ class NavigationManagerTest extends TestCase { $this->navigationManager->clear(false); } - public function addArrayData() { + public static function addArrayData(): array { return [ [ - 'entry id' => [ + 'entry' => [ 'id' => 'entry id', 'name' => 'link text', 'order' => 1, @@ -81,7 +81,7 @@ class NavigationManagerTest extends TestCase { 'classes' => '', 'unread' => 0 ], - 'entry id2' => [ + 'expectedEntry' => [ 'id' => 'entry id', 'name' => 'link text', 'order' => 1, @@ -94,7 +94,7 @@ class NavigationManagerTest extends TestCase { ] ], [ - 'entry id' => [ + 'entry' => [ 'id' => 'entry id', 'name' => 'link text', 'order' => 1, @@ -103,7 +103,7 @@ class NavigationManagerTest extends TestCase { 'active' => true, 'unread' => 0, ], - 'entry id2' => [ + 'expectedEntry' => [ 'id' => 'entry id', 'name' => 'link text', 'order' => 1, @@ -272,7 +272,7 @@ class NavigationManagerTest extends TestCase { $this->assertEquals($expected, $entries); } - public function providesNavigationConfig() { + public static function providesNavigationConfig(): array { $apps = [ 'core_apps' => [ 'id' => 'core_apps', diff --git a/tests/lib/Net/HostnameClassifierTest.php b/tests/lib/Net/HostnameClassifierTest.php index 766246ed8ad..5d80da01e46 100644 --- a/tests/lib/Net/HostnameClassifierTest.php +++ b/tests/lib/Net/HostnameClassifierTest.php @@ -21,7 +21,7 @@ class HostnameClassifierTest extends TestCase { $this->classifier = new HostnameClassifier(); } - public function localHostnamesData():array { + public static function localHostnamesData(): array { return [ ['localhost'], ['localHost'], @@ -41,7 +41,7 @@ class HostnameClassifierTest extends TestCase { self::assertTrue($isLocal); } - public function publicHostnamesData(): array { + public static function publicHostnamesData(): array { return [ ['example.com'], ['example.net'], diff --git a/tests/lib/Net/IpAddressClassifierTest.php b/tests/lib/Net/IpAddressClassifierTest.php index 803be00f740..be0b7e52fe0 100644 --- a/tests/lib/Net/IpAddressClassifierTest.php +++ b/tests/lib/Net/IpAddressClassifierTest.php @@ -21,7 +21,7 @@ class IpAddressClassifierTest extends TestCase { $this->classifier = new IpAddressClassifier(); } - public function publicIpAddressData(): array { + public static function publicIpAddressData(): array { return [ ['8.8.8.8'], ['8.8.4.4'], @@ -39,7 +39,7 @@ class IpAddressClassifierTest extends TestCase { self::assertFalse($isLocal); } - public function localIpAddressData(): array { + public static function localIpAddressData(): array { return [ ['192.168.0.1'], ['fe80::200:5aee:feaa:20a2'], diff --git a/tests/lib/Notification/ActionTest.php b/tests/lib/Notification/ActionTest.php index 3ae4b1db7e7..241e08048a0 100644 --- a/tests/lib/Notification/ActionTest.php +++ b/tests/lib/Notification/ActionTest.php @@ -20,7 +20,7 @@ class ActionTest extends TestCase { $this->action = new Action(); } - public function dataSetLabel() { + public static function dataSetLabel(): array { return [ ['test1'], [str_repeat('a', 1)], @@ -38,7 +38,7 @@ class ActionTest extends TestCase { $this->assertSame($label, $this->action->getLabel()); } - public function dataSetLabelInvalid() { + public static function dataSetLabelInvalid(): array { return [ [''], [str_repeat('a', 33)], @@ -56,7 +56,7 @@ class ActionTest extends TestCase { $this->action->setLabel($label); } - public function dataSetParsedLabel() { + public static function dataSetParsedLabel(): array { return [ ['test1'], [str_repeat('a', 1)], @@ -74,7 +74,7 @@ class ActionTest extends TestCase { $this->assertSame($label, $this->action->getParsedLabel()); } - public function dataSetParsedLabelInvalid() { + public static function dataSetParsedLabelInvalid(): array { return [ [''], ]; @@ -91,7 +91,7 @@ class ActionTest extends TestCase { $this->action->setParsedLabel($label); } - public function dataSetLink() { + public static function dataSetLink(): array { return [ ['test1', 'GET'], ['test2', 'POST'], @@ -112,7 +112,7 @@ class ActionTest extends TestCase { $this->assertSame($type, $this->action->getRequestType()); } - public function dataSetLinkInvalid() { + public static function dataSetLinkInvalid(): array { return [ // Invalid link ['', 'GET'], @@ -135,7 +135,7 @@ class ActionTest extends TestCase { $this->action->setLink($link, $type); } - public function dataSetPrimary() { + public static function dataSetPrimary(): array { return [ [true], [false], diff --git a/tests/lib/Notification/ManagerTest.php b/tests/lib/Notification/ManagerTest.php index 2a85316d7c4..418d642317e 100644 --- a/tests/lib/Notification/ManagerTest.php +++ b/tests/lib/Notification/ManagerTest.php @@ -153,7 +153,7 @@ class ManagerTest extends TestCase { $this->coordinator, $this->richTextFormatter, ]) - ->setMethods(['getApps']) + ->onlyMethods(['getApps']) ->getMock(); $manager->expects($this->once()) @@ -185,7 +185,7 @@ class ManagerTest extends TestCase { $this->coordinator, $this->richTextFormatter, ]) - ->setMethods(['getApps']) + ->onlyMethods(['getApps']) ->getMock(); $manager->expects($this->never()) @@ -210,7 +210,7 @@ class ManagerTest extends TestCase { $this->coordinator, $this->richTextFormatter, ]) - ->setMethods(['getApps']) + ->onlyMethods(['getApps']) ->getMock(); $manager->expects($this->once()) @@ -236,7 +236,7 @@ class ManagerTest extends TestCase { $this->coordinator, $this->richTextFormatter, ]) - ->setMethods(['getApps']) + ->onlyMethods(['getApps']) ->getMock(); $manager->expects($this->once()) @@ -246,7 +246,7 @@ class ManagerTest extends TestCase { $manager->getCount($notification); } - public function dataIsFairUseOfFreePushService(): array { + public static function dataIsFairUseOfFreePushService(): array { return [ [true, 999, true], [true, 1000, true], diff --git a/tests/lib/Notification/NotificationTest.php b/tests/lib/Notification/NotificationTest.php index 957d74233be..93b1746be3c 100644 --- a/tests/lib/Notification/NotificationTest.php +++ b/tests/lib/Notification/NotificationTest.php @@ -30,7 +30,7 @@ class NotificationTest extends TestCase { $this->notification = new Notification($this->validator, $this->richTextFormatter); } - protected function dataValidString($maxLength) { + protected static function dataValidString($maxLength): array { $dataSets = [ ['test1'], ['1564'], @@ -42,7 +42,7 @@ class NotificationTest extends TestCase { return $dataSets; } - protected function dataInvalidString($maxLength) { + protected static function dataInvalidString($maxLength): array { $dataSets = [ [''] ]; @@ -52,8 +52,8 @@ class NotificationTest extends TestCase { return $dataSets; } - public function dataSetApp() { - return $this->dataValidString(32); + public static function dataSetApp(): array { + return self::dataValidString(32); } /** @@ -66,8 +66,8 @@ class NotificationTest extends TestCase { $this->assertSame($app, $this->notification->getApp()); } - public function dataSetAppInvalid() { - return $this->dataInvalidString(32); + public static function dataSetAppInvalid(): array { + return self::dataInvalidString(32); } /** @@ -82,8 +82,8 @@ class NotificationTest extends TestCase { } - public function dataSetUser() { - return $this->dataValidString(64); + public static function dataSetUser(): array { + return self::dataValidString(64); } /** @@ -96,8 +96,8 @@ class NotificationTest extends TestCase { $this->assertSame($user, $this->notification->getUser()); } - public function dataSetUserInvalid() { - return $this->dataInvalidString(64); + public static function dataSetUserInvalid(): array { + return self::dataInvalidString(64); } /** @@ -111,7 +111,7 @@ class NotificationTest extends TestCase { $this->notification->setUser($user); } - public function dataSetDateTime() { + public static function dataSetDateTime(): array { $past = new \DateTime(); $past->sub(new \DateInterval('P1Y')); $current = new \DateTime(); @@ -135,7 +135,7 @@ class NotificationTest extends TestCase { $this->assertSame($dateTime, $this->notification->getDateTime()); } - public function dataSetDateTimeZero() { + public static function dataSetDateTimeZero(): array { $nineTeenSeventy = new \DateTime(); $nineTeenSeventy->setTimestamp(0); return [ @@ -155,7 +155,7 @@ class NotificationTest extends TestCase { $this->notification->setDateTime($dateTime); } - public function dataSetObject() { + public static function dataSetObject(): array { return [ ['a', '21'], [str_repeat('a', 64), '42'], @@ -175,11 +175,11 @@ class NotificationTest extends TestCase { $this->assertSame($id, $this->notification->getObjectId()); } - public function dataSetObjectTypeInvalid() { - return $this->dataInvalidString(64); + public static function dataSetObjectTypeInvalid(): array { + return self::dataInvalidString(64); } - public function dataSetObjectIdInvalid() { + public static function dataSetObjectIdInvalid(): array { return [ [''], [str_repeat('a', 64 + 1)], @@ -198,7 +198,7 @@ class NotificationTest extends TestCase { $this->notification->setObject('object', $id); } - public function dataSetSubject() { + public static function dataSetSubject(): array { return [ ['a', []], [str_repeat('a', 64), [str_repeat('a', 160)]], @@ -219,8 +219,8 @@ class NotificationTest extends TestCase { $this->assertSame($parameters, $this->notification->getSubjectParameters()); } - public function dataSetSubjectInvalidSubject() { - return $this->dataInvalidString(64); + public static function dataSetSubjectInvalidSubject(): array { + return self::dataInvalidString(64); } /** @@ -234,8 +234,8 @@ class NotificationTest extends TestCase { $this->notification->setSubject($subject, []); } - public function dataSetParsedSubject() { - return $this->dataValidString(false); + public static function dataSetParsedSubject(): array { + return self::dataValidString(false); } /** @@ -248,8 +248,8 @@ class NotificationTest extends TestCase { $this->assertSame($subject, $this->notification->getParsedSubject()); } - public function dataSetParsedSubjectInvalid() { - return $this->dataInvalidString(false); + public static function dataSetParsedSubjectInvalid(): array { + return self::dataInvalidString(false); } /** @@ -263,7 +263,7 @@ class NotificationTest extends TestCase { $this->notification->setParsedSubject($subject); } - public function dataSetMessage() { + public static function dataSetMessage(): array { return [ ['a', []], [str_repeat('a', 64), [str_repeat('a', 160)]], @@ -284,8 +284,8 @@ class NotificationTest extends TestCase { $this->assertSame($parameters, $this->notification->getMessageParameters()); } - public function dataSetMessageInvalidMessage() { - return $this->dataInvalidString(64); + public static function dataSetMessageInvalidMessage(): array { + return self::dataInvalidString(64); } /** @@ -299,8 +299,8 @@ class NotificationTest extends TestCase { $this->notification->setMessage($message, []); } - public function dataSetParsedMessage() { - return $this->dataValidString(false); + public static function dataSetParsedMessage(): array { + return self::dataValidString(false); } /** @@ -313,8 +313,8 @@ class NotificationTest extends TestCase { $this->assertSame($message, $this->notification->getParsedMessage()); } - public function dataSetParsedMessageInvalid() { - return $this->dataInvalidString(false); + public static function dataSetParsedMessageInvalid(): array { + return self::dataInvalidString(false); } /** @@ -328,8 +328,8 @@ class NotificationTest extends TestCase { $this->notification->setParsedMessage($message); } - public function dataSetLink() { - return $this->dataValidString(4000); + public static function dataSetLink(): array { + return self::dataValidString(4000); } /** @@ -342,8 +342,8 @@ class NotificationTest extends TestCase { $this->assertSame($link, $this->notification->getLink()); } - public function dataSetLinkInvalid() { - return $this->dataInvalidString(4000); + public static function dataSetLinkInvalid(): array { + return self::dataInvalidString(4000); } /** @@ -357,8 +357,8 @@ class NotificationTest extends TestCase { $this->notification->setLink($link); } - public function dataSetIcon() { - return $this->dataValidString(4000); + public static function dataSetIcon(): array { + return self::dataValidString(4000); } /** @@ -371,8 +371,8 @@ class NotificationTest extends TestCase { $this->assertSame($icon, $this->notification->getIcon()); } - public function dataSetIconInvalid() { - return $this->dataInvalidString(4000); + public static function dataSetIconInvalid(): array { + return self::dataInvalidString(4000); } /** @@ -508,7 +508,7 @@ class NotificationTest extends TestCase { $this->assertEquals([$action2, $action1, $action1], $this->notification->getParsedActions()); } - public function dataIsValid() { + public static function dataIsValid(): array { return [ [false, '', false], [true, '', false], @@ -527,7 +527,7 @@ class NotificationTest extends TestCase { public function testIsValid($isValidCommon, $subject, $expected): void { /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ $notification = $this->getMockBuilder(Notification::class) - ->setMethods([ + ->onlyMethods([ 'isValidCommon', 'getSubject', 'getParsedSubject', @@ -560,7 +560,7 @@ class NotificationTest extends TestCase { public function testIsParsedValid($isValidCommon, $subject, $expected): void { /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ $notification = $this->getMockBuilder(Notification::class) - ->setMethods([ + ->onlyMethods([ 'isValidCommon', 'getParsedSubject', 'getSubject', @@ -583,7 +583,7 @@ class NotificationTest extends TestCase { $this->assertEquals($expected, $notification->isValidParsed()); } - public function dataIsValidCommon() { + public static function dataIsValidCommon(): array { return [ ['', '', 0, '', '', false], ['app', '', 0, '', '', false], @@ -607,7 +607,7 @@ class NotificationTest extends TestCase { public function testIsValidCommon($app, $user, $timestamp, $objectType, $objectId, $expected): void { /** @var \OCP\Notification\INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ $notification = $this->getMockBuilder(Notification::class) - ->setMethods([ + ->onlyMethods([ 'getApp', 'getUser', 'getDateTime', diff --git a/tests/lib/OCS/ApiHelperTest.php b/tests/lib/OCS/ApiHelperTest.php index fdbc1f4c538..93de6b22af7 100644 --- a/tests/lib/OCS/ApiHelperTest.php +++ b/tests/lib/OCS/ApiHelperTest.php @@ -14,10 +14,7 @@ use OC\OCS\ApiHelper; use OCP\IRequest; class ApiHelperTest extends \Test\TestCase { - /** - * @return array - */ - public function versionDataScriptNameProvider(): array { + public static function versionDataScriptNameProvider(): array { return [ // Valid script name [ diff --git a/tests/lib/OCS/DiscoveryServiceTest.php b/tests/lib/OCS/DiscoveryServiceTest.php index 3db3163e11d..2fce12ee3c0 100644 --- a/tests/lib/OCS/DiscoveryServiceTest.php +++ b/tests/lib/OCS/DiscoveryServiceTest.php @@ -45,7 +45,7 @@ class DiscoveryServiceTest extends TestCase { $this->assertSame($expected, $result); } - public function dataTestIsSafeUrl() { + public static function dataTestIsSafeUrl(): array { return [ ['api/ocs/v1.php/foo', true], ['/api/ocs/v1.php/foo', true], @@ -69,7 +69,7 @@ class DiscoveryServiceTest extends TestCase { $this->assertSame($expected, $result); } - public function dataTestGetEndpoints() { + public static function dataTestGetEndpoints(): array { return [ [['services' => ['myService' => ['endpoints' => []]]], 'myService', []], [['services' => ['myService' => ['endpoints' => ['foo' => '/bar']]]], 'myService', ['foo' => '/bar']], diff --git a/tests/lib/Preview/GeneratorTest.php b/tests/lib/Preview/GeneratorTest.php index 607127a6495..84ffe6662c7 100644 --- a/tests/lib/Preview/GeneratorTest.php +++ b/tests/lib/Preview/GeneratorTest.php @@ -343,7 +343,7 @@ class GeneratorTest extends \Test\TestCase { return $image; } - public function dataSize() { + public static function dataSize(): array { return [ [1024, 2048, 512, 512, false, IPreview::MODE_FILL, 256, 512], [1024, 2048, 512, 512, false, IPreview::MODE_COVER, 512, 1024], diff --git a/tests/lib/Preview/SVGTest.php b/tests/lib/Preview/SVGTest.php index 6a0e93e5f79..14730bc8034 100644 --- a/tests/lib/Preview/SVGTest.php +++ b/tests/lib/Preview/SVGTest.php @@ -30,7 +30,7 @@ class SVGTest extends Provider { } } - public function dataGetThumbnailSVGHref(): array { + public static function dataGetThumbnailSVGHref(): array { return [ ['href'], [' href'], diff --git a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php index 810fa1fe4e8..88fc24b40ad 100644 --- a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php +++ b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php @@ -30,7 +30,7 @@ class ClearGeneratedAvatarCacheTest extends \Test\TestCase { $this->repair = new ClearGeneratedAvatarCache($this->config, $this->avatarManager, $this->jobList); } - public function shouldRunDataProvider() { + public static function shouldRunDataProvider(): array { return [ ['11.0.0.0', true], ['15.0.0.3', true], diff --git a/tests/lib/Repair/RepairInvalidSharesTest.php b/tests/lib/Repair/RepairInvalidSharesTest.php index dfcdce3801a..7c49d74e2ef 100644 --- a/tests/lib/Repair/RepairInvalidSharesTest.php +++ b/tests/lib/Repair/RepairInvalidSharesTest.php @@ -122,7 +122,7 @@ class RepairInvalidSharesTest extends TestCase { $result->closeCursor(); } - public function fileSharePermissionsProvider() { + public static function fileSharePermissionsProvider(): array { return [ // unchanged for folder [ diff --git a/tests/lib/RichObjectStrings/DefinitionsTest.php b/tests/lib/RichObjectStrings/DefinitionsTest.php index 9299a556972..cc964aff50f 100644 --- a/tests/lib/RichObjectStrings/DefinitionsTest.php +++ b/tests/lib/RichObjectStrings/DefinitionsTest.php @@ -10,7 +10,7 @@ use OCP\RichObjectStrings\Definitions; use Test\TestCase; class DefinitionsTest extends TestCase { - public function dataGetDefinition() { + public static function dataGetDefinition() { $definitions = new Definitions(); $testsuite = []; foreach ($definitions->definitions as $type => $definition) { @@ -19,7 +19,7 @@ class DefinitionsTest extends TestCase { return $testsuite; } - + public function testGetDefinitionNotExisting(): void { $this->expectException(\OCP\RichObjectStrings\InvalidObjectExeption::class); $this->expectExceptionMessage('Object type is undefined'); diff --git a/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php b/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php index 82bffb74e01..ac679238617 100644 --- a/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php +++ b/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php @@ -36,7 +36,7 @@ class MemoryCacheBackendTest extends TestCase { $this->cacheFactory ->expects($this->once()) ->method('createDistributed') - ->with('OC\Security\Bruteforce\Backend\MemoryCacheBackend') + ->with(MemoryCacheBackend::class) ->willReturn($this->cache); $this->backend = new MemoryCacheBackend( @@ -55,7 +55,7 @@ class MemoryCacheBackendTest extends TestCase { $this->assertSame(0, $this->backend->getAttempts('10.10.10.10/32', 0)); } - public function dataGetAttempts(): array { + public static function dataGetAttempts(): array { return [ [0, null, null, 4], [100, null, null, 2], diff --git a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php index f8386124626..fcc776ade8e 100644 --- a/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php +++ b/tests/lib/Security/CSRF/TokenStorage/SessionStorageTest.php @@ -28,7 +28,7 @@ class SessionStorageTest extends \Test\TestCase { /** * @return array */ - public function getTokenDataProvider() { + public static function getTokenDataProvider(): array { return [ [ '', diff --git a/tests/lib/Security/CertificateManagerTest.php b/tests/lib/Security/CertificateManagerTest.php index 1c168228b6a..a0cb133ec3b 100644 --- a/tests/lib/Security/CertificateManagerTest.php +++ b/tests/lib/Security/CertificateManagerTest.php @@ -100,10 +100,7 @@ class CertificateManagerTest extends \Test\TestCase { $this->certificateManager->addCertificate('InvalidCertificate', 'invalidCertificate'); } - /** - * @return array - */ - public function dangerousFileProvider() { + public static function dangerousFileProvider(): array { return [ ['.htaccess'], ['../../foo.txt'], @@ -153,7 +150,7 @@ class CertificateManagerTest extends \Test\TestCase { /** @var CertificateManager | \PHPUnit\Framework\MockObject\MockObject $certificateManager */ $certificateManager = $this->getMockBuilder('OC\Security\CertificateManager') ->setConstructorArgs([$view, $config, $this->createMock(LoggerInterface::class), $this->random]) - ->setMethods(['getFilemtimeOfCaBundle', 'getCertificateBundle']) + ->onlyMethods(['getFilemtimeOfCaBundle', 'getCertificateBundle']) ->getMock(); $certificateManager->expects($this->any())->method('getFilemtimeOfCaBundle') @@ -181,7 +178,7 @@ class CertificateManagerTest extends \Test\TestCase { ); } - public function dataTestNeedRebundling() { + public static function dataTestNeedRebundling(): array { return [ //values: CaBundleMtime, targetBundleMtime, targetBundleExists, expected diff --git a/tests/lib/Security/CredentialsManagerTest.php b/tests/lib/Security/CredentialsManagerTest.php index ce60a2f62a2..d5e7a114667 100644 --- a/tests/lib/Security/CredentialsManagerTest.php +++ b/tests/lib/Security/CredentialsManagerTest.php @@ -50,7 +50,7 @@ class CredentialsManagerTest extends \Test\TestCase { $this->assertSame($secretsRev, $received); } - public function credentialsProvider(): array { + public static function credentialsProvider(): array { return [ [ 'alice', diff --git a/tests/lib/Security/CryptoTest.php b/tests/lib/Security/CryptoTest.php index 79140b34456..64042d0c5a9 100644 --- a/tests/lib/Security/CryptoTest.php +++ b/tests/lib/Security/CryptoTest.php @@ -13,7 +13,7 @@ namespace Test\Security; use OC\Security\Crypto; class CryptoTest extends \Test\TestCase { - public function defaultEncryptionProvider() { + public static function defaultEncryptionProvider(): array { return [ ['Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt.'], [''], diff --git a/tests/lib/Security/HasherTest.php b/tests/lib/Security/HasherTest.php index 41cad7f323f..11b63e8ec88 100644 --- a/tests/lib/Security/HasherTest.php +++ b/tests/lib/Security/HasherTest.php @@ -17,10 +17,7 @@ use OCP\IConfig; * Class HasherTest */ class HasherTest extends \Test\TestCase { - /** - * @return array - */ - public function versionHashProvider() { + public static function versionHashProvider(): array { return [ ['asf32äà$$a.|3', null], ['asf32äà$$a.|3|5', null], @@ -30,7 +27,7 @@ class HasherTest extends \Test\TestCase { ]; } - public function hashProviders70_71(): array { + public static function hashProviders70_71(): array { return [ // Valid SHA1 strings ['password', '5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8', true], @@ -66,7 +63,7 @@ class HasherTest extends \Test\TestCase { ]; } - public function hashProviders72(): array { + public static function hashProviders72(): array { return [ // Valid ARGON2 hashes ['password', '2|$argon2i$v=19$m=1024,t=2,p=2$T3JGcEkxVFNOVktNSjZUcg$4/hyLtSejxNgAuzSFFV/HLM3qRQKBwEtKw61qPN4zWA', true], @@ -83,7 +80,7 @@ class HasherTest extends \Test\TestCase { ]; } - public function hashProviders73(): array { + public static function hashProviders73(): array { return [ // Valid ARGON2ID hashes ['password', '2|$argon2id$v=19$m=65536,t=4,p=1$TEtIMnhUczliQzI0Y01WeA$BpMUDrApy25iagIogUAnlc0rNTPJmGs8lOEeVHujJ9Q', true], diff --git a/tests/lib/Security/Ip/BruteforceAllowListTest.php b/tests/lib/Security/Ip/BruteforceAllowListTest.php index f7ef9e3df72..efdb7c4034c 100644 --- a/tests/lib/Security/Ip/BruteforceAllowListTest.php +++ b/tests/lib/Security/Ip/BruteforceAllowListTest.php @@ -42,7 +42,7 @@ class BruteforceAllowListTest extends TestCase { ); } - public function dataIsBypassListed(): array { + public static function dataIsBypassListed(): array { return [ [ '10.10.10.10', diff --git a/tests/lib/Security/Ip/RemoteAddressTest.php b/tests/lib/Security/Ip/RemoteAddressTest.php index d1f621796fe..63c1b452294 100644 --- a/tests/lib/Security/Ip/RemoteAddressTest.php +++ b/tests/lib/Security/Ip/RemoteAddressTest.php @@ -44,7 +44,7 @@ class RemoteAddressTest extends \Test\TestCase { /** * @return array<string, mixed, bool> */ - public function dataProvider(): array { + public static function dataProvider(): array { return [ // No IP (ie. CLI) ['', ['192.168.1.2/24'], true], diff --git a/tests/lib/Security/Normalizer/IpAddressTest.php b/tests/lib/Security/Normalizer/IpAddressTest.php index 33a8b4d28f1..29067596c98 100644 --- a/tests/lib/Security/Normalizer/IpAddressTest.php +++ b/tests/lib/Security/Normalizer/IpAddressTest.php @@ -13,7 +13,7 @@ use OC\Security\Normalizer\IpAddress; use Test\TestCase; class IpAddressTest extends TestCase { - public function subnetDataProvider() { + public static function subnetDataProvider(): array { return [ [ '64.233.191.254', diff --git a/tests/lib/Security/RemoteHostValidatorIntegrationTest.php b/tests/lib/Security/RemoteHostValidatorIntegrationTest.php index 6cddb8b4ce9..3d319e828ff 100644 --- a/tests/lib/Security/RemoteHostValidatorIntegrationTest.php +++ b/tests/lib/Security/RemoteHostValidatorIntegrationTest.php @@ -37,7 +37,7 @@ class RemoteHostValidatorIntegrationTest extends TestCase { ); } - public function localHostsData(): array { + public static function localHostsData(): array { return [ ['[::1]'], ['[::]'], @@ -101,7 +101,7 @@ class RemoteHostValidatorIntegrationTest extends TestCase { self::assertTrue($isValid); } - public function externalAddressesData():array { + public static function externalAddressesData():array { return [ ['8.8.8.8'], ['8.8.4.4'], diff --git a/tests/lib/Security/RemoteHostValidatorTest.php b/tests/lib/Security/RemoteHostValidatorTest.php index c698ebbc3c6..46c969d28c1 100644 --- a/tests/lib/Security/RemoteHostValidatorTest.php +++ b/tests/lib/Security/RemoteHostValidatorTest.php @@ -44,7 +44,7 @@ class RemoteHostValidatorTest extends TestCase { ); } - public function dataValid(): array { + public static function dataValid(): array { return [ ['nextcloud.com', true], ['com.one-.nextcloud-one.com', false], diff --git a/tests/lib/Security/SecureRandomTest.php b/tests/lib/Security/SecureRandomTest.php index 8000917579b..98eb0e45df3 100644 --- a/tests/lib/Security/SecureRandomTest.php +++ b/tests/lib/Security/SecureRandomTest.php @@ -13,7 +13,7 @@ namespace Test\Security; use OC\Security\SecureRandom; class SecureRandomTest extends \Test\TestCase { - public function stringGenerationProvider() { + public static function stringGenerationProvider(): array { return [ [1, 1], [128, 128], @@ -24,7 +24,7 @@ class SecureRandomTest extends \Test\TestCase { ]; } - public static function charCombinations() { + public static function charCombinations(): array { return [ ['CHAR_LOWER', '[a-z]'], ['CHAR_UPPER', '[A-Z]'], @@ -76,7 +76,7 @@ class SecureRandomTest extends \Test\TestCase { $this->assertSame(1, $matchesRegex); } - public static function invalidLengths() { + public static function invalidLengths(): array { return [ [0], [-1], diff --git a/tests/lib/Security/TrustedDomainHelperTest.php b/tests/lib/Security/TrustedDomainHelperTest.php index 656b7a77206..1b9ba20a906 100644 --- a/tests/lib/Security/TrustedDomainHelperTest.php +++ b/tests/lib/Security/TrustedDomainHelperTest.php @@ -63,7 +63,7 @@ class TrustedDomainHelperTest extends \Test\TestCase { /** * @return array */ - public function trustedDomainDataProvider() { + public static function trustedDomainDataProvider(): array { $trustedHostTestList = [ 'host.one.test', 'host.two.test', diff --git a/tests/lib/ServerTest.php b/tests/lib/ServerTest.php index eb9b1dab9f5..371bc572b15 100644 --- a/tests/lib/ServerTest.php +++ b/tests/lib/ServerTest.php @@ -28,7 +28,7 @@ class ServerTest extends \Test\TestCase { $this->server = new \OC\Server('', $config); } - public function dataTestQuery() { + public static function dataTestQuery(): array { return [ ['\OCP\Activity\IManager', '\OC\Activity\Manager'], ['\OCP\IConfig', '\OC\AllConfig'], diff --git a/tests/lib/SetupTest.php b/tests/lib/SetupTest.php index b5e1b7000c3..f82060dcfa2 100644 --- a/tests/lib/SetupTest.php +++ b/tests/lib/SetupTest.php @@ -42,7 +42,7 @@ class SetupTest extends \Test\TestCase { $this->random = $this->createMock(ISecureRandom::class); $this->installer = $this->createMock(Installer::class); $this->setupClass = $this->getMockBuilder(Setup::class) - ->setMethods(['class_exists', 'is_callable', 'getAvailableDbDriversForPdo']) + ->onlyMethods(['class_exists', 'is_callable', 'getAvailableDbDriversForPdo']) ->setConstructorArgs([$this->config, $this->iniWrapper, $this->l10nFactory, $this->defaults, $this->logger, $this->random, $this->installer]) ->getMock(); } @@ -151,7 +151,7 @@ class SetupTest extends \Test\TestCase { $this->assertSame($webRoot, $expected); } - public function findWebRootProvider(): array { + public static function findWebRootProvider(): array { return [ 'https://www.example.com/nextcloud/' => ['https://www.example.com/nextcloud/', '/nextcloud'], 'https://www.example.com/nextcloud' => ['https://www.example.com/nextcloud', '/nextcloud'], diff --git a/tests/lib/Share/HelperTest.php b/tests/lib/Share/HelperTest.php index c923bb0480a..c56350358eb 100644 --- a/tests/lib/Share/HelperTest.php +++ b/tests/lib/Share/HelperTest.php @@ -12,7 +12,7 @@ namespace Test\Share; * Class Helper */ class HelperTest extends \Test\TestCase { - public function expireDateProvider() { + public static function expireDateProvider(): array { return [ // no default expire date, we take the users expire date [['defaultExpireDateSet' => false], 2000000000, 2000010000, 2000010000], @@ -54,7 +54,7 @@ class HelperTest extends \Test\TestCase { ); } - public function dataTestCompareServerAddresses() { + public static function dataTestCompareServerAddresses(): array { return [ ['user1', 'http://server1', 'user1', 'http://server1', true], ['user1', 'https://server1', 'user1', 'http://server1', true], diff --git a/tests/lib/Share/ShareTest.php b/tests/lib/Share/ShareTest.php index 60891e10ca2..944d0738eb1 100644 --- a/tests/lib/Share/ShareTest.php +++ b/tests/lib/Share/ShareTest.php @@ -132,7 +132,7 @@ class ShareTest extends \Test\TestCase { $this->assertSame($expectedResult, $result); } - public function urls() { + public static function urls(): array { return [ ['http://owncloud.org', 'owncloud.org'], ['https://owncloud.org', 'owncloud.org'], @@ -161,7 +161,7 @@ class ShareTest extends \Test\TestCase { } } - public function dataProviderTestGroupItems() { + public static function dataProviderTestGroupItems(): array { return [ // one array with one share [ diff --git a/tests/lib/Share20/DefaultShareProviderTest.php b/tests/lib/Share20/DefaultShareProviderTest.php index 75a70d558c1..39560795921 100644 --- a/tests/lib/Share20/DefaultShareProviderTest.php +++ b/tests/lib/Share20/DefaultShareProviderTest.php @@ -472,7 +472,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->logger, $this->shareManager, ]) - ->setMethods(['getShareById']) + ->onlyMethods(['getShareById']) ->getMock(); $provider->delete($share); @@ -569,7 +569,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->logger, $this->shareManager, ]) - ->setMethods(['getShareById']) + ->onlyMethods(['getShareById']) ->getMock(); $provider->delete($share); @@ -968,7 +968,7 @@ class DefaultShareProviderTest extends \Test\TestCase { return $qb->getLastInsertId(); } - public function storageAndFileNameProvider() { + public static function storageAndFileNameProvider(): array { return [ // regular file on regular storage ['home::shareOwner', 'files/test.txt', 'files/test2.txt'], @@ -1281,7 +1281,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertEquals(IShare::TYPE_GROUP, $share->getShareType()); } - public function shareTypesProvider() { + public static function shareTypesProvider(): array { return [ [IShare::TYPE_USER, false], [IShare::TYPE_GROUP, false], @@ -2276,7 +2276,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertSame('/ultraNewTarget', $share->getTarget()); } - public function dataDeleteUser() { + public static function dataDeleteUser(): array { return [ [IShare::TYPE_USER, 'a', 'b', 'c', 'a', true], [IShare::TYPE_USER, 'a', 'b', 'c', 'b', false], @@ -2334,7 +2334,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertCount($rowDeleted ? 0 : 1, $data); } - public function dataDeleteUserGroup() { + public static function dataDeleteUserGroup(): array { return [ ['a', 'b', 'c', 'a', true, true], ['a', 'b', 'c', 'b', false, false], @@ -2403,7 +2403,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertCount($groupShareDeleted ? 0 : 1, $data); } - public function dataGroupDeleted() { + public static function dataGroupDeleted(): array { return [ [ [ @@ -2497,7 +2497,7 @@ class DefaultShareProviderTest extends \Test\TestCase { $this->assertCount($shouldBeDeleted ? 0 : count($ids), $data); } - public function dataUserDeletedFromGroup() { + public static function dataUserDeletedFromGroup(): array { return [ ['group1', 'user1', true], ['group1', 'user2', false], diff --git a/tests/lib/Share20/LegacyHooksTest.php b/tests/lib/Share20/LegacyHooksTest.php index 0761eed592b..4a3d3a4310b 100644 --- a/tests/lib/Share20/LegacyHooksTest.php +++ b/tests/lib/Share20/LegacyHooksTest.php @@ -23,6 +23,19 @@ use OCP\Share\IShare; use Psr\Log\LoggerInterface; use Test\TestCase; +class Dummy { + public function postShare() { + } + public function preShare() { + } + public function postFromSelf() { + } + public function post() { + } + public function pre() { + } +} + class LegacyHooksTest extends TestCase { /** @var LegacyHooks */ private $hooks; @@ -60,7 +73,7 @@ class LegacyHooksTest extends TestCase { ->setTarget('myTarget') ->setNodeCacheEntry($info); - $hookListner = $this->getMockBuilder('Dummy')->setMethods(['pre'])->getMock(); + $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['pre'])->getMock(); \OCP\Util::connectHook('OCP\Share', 'pre_unshare', $hookListner, 'pre'); $hookListnerExpectsPre = [ @@ -101,7 +114,7 @@ class LegacyHooksTest extends TestCase { ->setTarget('myTarget') ->setNodeCacheEntry($info); - $hookListner = $this->getMockBuilder('Dummy')->setMethods(['post'])->getMock(); + $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['post'])->getMock(); \OCP\Util::connectHook('OCP\Share', 'post_unshare', $hookListner, 'post'); $hookListnerExpectsPost = [ @@ -155,7 +168,7 @@ class LegacyHooksTest extends TestCase { ->setTarget('myTarget') ->setNodeCacheEntry($info); - $hookListner = $this->getMockBuilder('Dummy')->setMethods(['postFromSelf'])->getMock(); + $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['postFromSelf'])->getMock(); \OCP\Util::connectHook('OCP\Share', 'post_unshareFromSelf', $hookListner, 'postFromSelf'); $hookListnerExpectsPostFromSelf = [ @@ -212,7 +225,7 @@ class LegacyHooksTest extends TestCase { ->setToken('token'); - $hookListner = $this->getMockBuilder('Dummy')->setMethods(['preShare'])->getMock(); + $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['preShare'])->getMock(); \OCP\Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare'); $run = true; @@ -260,7 +273,7 @@ class LegacyHooksTest extends TestCase { ->setToken('token'); - $hookListner = $this->getMockBuilder('Dummy')->setMethods(['preShare'])->getMock(); + $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['preShare'])->getMock(); \OCP\Util::connectHook('OCP\Share', 'pre_shared', $hookListner, 'preShare'); $run = true; @@ -316,7 +329,7 @@ class LegacyHooksTest extends TestCase { ->setToken('token'); - $hookListner = $this->getMockBuilder('Dummy')->setMethods(['postShare'])->getMock(); + $hookListner = $this->getMockBuilder(Dummy::class)->onlyMethods(['postShare'])->getMock(); \OCP\Util::connectHook('OCP\Share', 'post_shared', $hookListner, 'postShare'); $expected = [ diff --git a/tests/lib/Share20/ShareHelperTest.php b/tests/lib/Share20/ShareHelperTest.php index 8aaa8350ea9..9027704bb32 100644 --- a/tests/lib/Share20/ShareHelperTest.php +++ b/tests/lib/Share20/ShareHelperTest.php @@ -27,7 +27,7 @@ class ShareHelperTest extends TestCase { $this->helper = new ShareHelper($this->manager); } - public function dataGetPathsForAccessList() { + public static function dataGetPathsForAccessList(): array { return [ [[], [], false, [], [], false, [ 'users' => [], @@ -64,7 +64,7 @@ class ShareHelperTest extends TestCase { /** @var ShareHelper|\PHPUnit\Framework\MockObject\MockObject $helper */ $helper = $this->getMockBuilder(ShareHelper::class) ->setConstructorArgs([$this->manager]) - ->setMethods(['getPathsForUsers', 'getPathsForRemotes']) + ->onlyMethods(['getPathsForUsers', 'getPathsForRemotes']) ->getMock(); $helper->expects($resolveUsers ? $this->once() : $this->never()) @@ -80,7 +80,7 @@ class ShareHelperTest extends TestCase { $this->assertSame($expected, $helper->getPathsForAccessList($node)); } - public function dataGetPathsForUsers() { + public static function dataGetPathsForUsers(): array { return [ [[], [23 => 'TwentyThree', 42 => 'FortyTwo'], []], [ @@ -133,7 +133,7 @@ class ShareHelperTest extends TestCase { $this->assertEquals($expected, self::invokePrivate($this->helper, 'getPathsForUsers', [$lastNode, $users])); } - public function dataGetPathsForRemotes() { + public static function dataGetPathsForRemotes(): array { return [ [[], [23 => 'TwentyThree', 42 => 'FortyTwo'], []], [ @@ -190,7 +190,7 @@ class ShareHelperTest extends TestCase { $this->assertEquals($expected, self::invokePrivate($this->helper, 'getPathsForRemotes', [$lastNode, $remotes])); } - public function dataGetMountedPath() { + public static function dataGetMountedPath(): array { return [ ['/admin/files/foobar', '/foobar'], ['/admin/files/foo/bar', '/foo/bar'], diff --git a/tests/lib/Support/Subscription/RegistryTest.php b/tests/lib/Support/Subscription/RegistryTest.php index b3a0f8e603e..08a216294d6 100644 --- a/tests/lib/Support/Subscription/RegistryTest.php +++ b/tests/lib/Support/Subscription/RegistryTest.php @@ -157,7 +157,7 @@ class RegistryTest extends TestCase { $this->assertSame(false, $this->registry->delegateIsHardUserLimitReached($this->notificationManager)); } - public function dataForUserLimitCheck() { + public static function dataForUserLimitCheck(): array { return [ // $userLimit, $userCount, $disabledUsers, $expectedResult [35, 15, 2, false], diff --git a/tests/lib/SystemTag/SystemTagManagerTest.php b/tests/lib/SystemTag/SystemTagManagerTest.php index 94103c52cb1..4627ebbf546 100644 --- a/tests/lib/SystemTag/SystemTagManagerTest.php +++ b/tests/lib/SystemTag/SystemTagManagerTest.php @@ -66,7 +66,7 @@ class SystemTagManagerTest extends TestCase { $query->delete(SystemTagManager::TAG_TABLE)->execute(); } - public static function getAllTagsDataProvider() { + public static function getAllTagsDataProvider(): array { return [ [ // no tags at all @@ -113,7 +113,7 @@ class SystemTagManagerTest extends TestCase { } } - public static function getAllTagsFilteredDataProvider() { + public static function getAllTagsFilteredDataProvider(): array { return [ [ [ @@ -226,7 +226,7 @@ class SystemTagManagerTest extends TestCase { } } - public static function oneTagMultipleFlagsProvider() { + public static function oneTagMultipleFlagsProvider(): array { return [ ['one', false, false], ['one', true, false], @@ -299,7 +299,7 @@ class SystemTagManagerTest extends TestCase { $this->tagManager->getTagsByIds([$tag1->getId() . 'suffix']); } - public static function updateTagProvider() { + public static function updateTagProvider(): array { return [ [ // update name @@ -424,7 +424,7 @@ class SystemTagManagerTest extends TestCase { ], $tagIdMapping); } - public static function visibilityCheckProvider() { + public static function visibilityCheckProvider(): array { return [ [false, false, false, false], [true, false, false, true], @@ -451,7 +451,7 @@ class SystemTagManagerTest extends TestCase { $this->assertEquals($expectedResult, $this->tagManager->canUserSeeTag($tag1, $user)); } - public static function assignabilityCheckProvider() { + public static function assignabilityCheckProvider(): array { return [ // no groups [false, false, false, false], @@ -529,7 +529,7 @@ class SystemTagManagerTest extends TestCase { $this->assertEquals([], $this->tagManager->getTagGroups($tag1)); } - private function allowedToCreateProvider(): array { + public static function allowedToCreateProvider(): array { return [ [true, null, true], [true, null, false], @@ -570,7 +570,7 @@ class SystemTagManagerTest extends TestCase { \OC::$CLI = $oldCli; } - private function disallowedToCreateProvider(): array { + public static function disallowedToCreateProvider(): array { return [ [false], [null], diff --git a/tests/lib/Updater/ReleaseMetadataTest.php b/tests/lib/Updater/ReleaseMetadataTest.php index 72c6da5064d..335425b7672 100644 --- a/tests/lib/Updater/ReleaseMetadataTest.php +++ b/tests/lib/Updater/ReleaseMetadataTest.php @@ -17,9 +17,7 @@ class ReleaseMetadataTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->clientService = $this->getMockBuilder(IClientService::class) - ->disableOriginalConstructor() - ->getMock(); + $this->clientService = $this->createMock(IClientService::class); } public function testDownloadMetadata(): void { @@ -39,7 +37,7 @@ class ReleaseMetadataTest extends \Test\TestCase { $releaseMetadata = new ReleaseMetadata($this->clientService); - $this->assertSame($this->resultRequestArray(), $releaseMetadata->downloadMetadata('ouila')); + $this->assertSame(self::resultRequestArray(), $releaseMetadata->downloadMetadata('ouila')); } /** @@ -72,7 +70,7 @@ class ReleaseMetadataTest extends \Test\TestCase { /** * @return array */ - public function getMetadataUrlProvider(): array { + public static function getMetadataUrlProvider(): array { return [ [ '30.0.0', @@ -89,11 +87,11 @@ class ReleaseMetadataTest extends \Test\TestCase { ]; } - private function resultRequest(): string { - return json_encode($this->resultRequestArray()); + private static function resultRequest(): string { + return json_encode(self::resultRequestArray()); } - private function resultRequestArray(): array { + private static function resultRequestArray(): array { return [ 'migrations' => [ 'core' => [], diff --git a/tests/lib/Updater/VersionCheckTest.php b/tests/lib/Updater/VersionCheckTest.php index 51d1625ea4d..4ee75c767a2 100644 --- a/tests/lib/Updater/VersionCheckTest.php +++ b/tests/lib/Updater/VersionCheckTest.php @@ -45,7 +45,7 @@ class VersionCheckTest extends \Test\TestCase { ->willReturn(false); $this->logger = $this->createMock(LoggerInterface::class); $this->updater = $this->getMockBuilder(VersionCheck::class) - ->setMethods(['getUrlContent']) + ->onlyMethods(['getUrlContent']) ->setConstructorArgs([ $this->serverVersion, $clientService, diff --git a/tests/lib/UpdaterTest.php b/tests/lib/UpdaterTest.php index 81babee7029..291aaf807e5 100644 --- a/tests/lib/UpdaterTest.php +++ b/tests/lib/UpdaterTest.php @@ -54,7 +54,7 @@ class UpdaterTest extends TestCase { /** * @return array */ - public function versionCompatibilityTestData() { + public static function versionCompatibilityTestData(): array { return [ // Upgrade with invalid version ['9.1.1.13', '11.0.2.25', ['nextcloud' => ['11.0' => true]], false], diff --git a/tests/lib/UrlGeneratorTest.php b/tests/lib/UrlGeneratorTest.php index ed7b797d809..7006c3948f6 100644 --- a/tests/lib/UrlGeneratorTest.php +++ b/tests/lib/UrlGeneratorTest.php @@ -107,14 +107,14 @@ class UrlGeneratorTest extends \Test\TestCase { $this->assertEquals($expected, $result); } - public static function provideRoutes() { + public static function provideRoutes(): array { return [ ['core.Preview.getPreview', 'http://localhost/nextcloud/index.php/core/preview.png'], ['cloud_federation_api.requesthandlercontroller.addShare', 'http://localhost/nextcloud/index.php/ocm/shares'], ]; } - public static function provideDocRootAppUrlParts() { + public static function provideDocRootAppUrlParts(): array { return [ ['files_external', 'ajax/oauth2.php', [], '/index.php/apps/files_external/ajax/oauth2.php'], ['files_external', 'ajax/oauth2.php', ['trut' => 'trat', 'dut' => 'dat'], '/index.php/apps/files_external/ajax/oauth2.php?trut=trat&dut=dat'], @@ -122,7 +122,7 @@ class UrlGeneratorTest extends \Test\TestCase { ]; } - public static function provideSubDirAppUrlParts() { + public static function provideSubDirAppUrlParts(): array { return [ ['files_external', 'ajax/oauth2.php', [], '/nextcloud/index.php/apps/files_external/ajax/oauth2.php'], ['files_external', 'ajax/oauth2.php', ['trut' => 'trat', 'dut' => 'dat'], '/nextcloud/index.php/apps/files_external/ajax/oauth2.php?trut=trat&dut=dat'], @@ -154,7 +154,7 @@ class UrlGeneratorTest extends \Test\TestCase { $this->assertEquals($expectedResult, $result); } - public function provideDocRootURLs() { + public static function provideDocRootURLs(): array { return [ ['index.php', 'http://localhost/index.php'], ['/index.php', 'http://localhost/index.php'], @@ -163,7 +163,7 @@ class UrlGeneratorTest extends \Test\TestCase { ]; } - public function provideSubDirURLs() { + public static function provideSubDirURLs(): array { return [ ['', 'http://localhost/nextcloud/'], ['/', 'http://localhost/nextcloud/'], @@ -213,7 +213,7 @@ class UrlGeneratorTest extends \Test\TestCase { $this->assertEquals($expected, $result); } - public function provideOCSRoutes(): array { + public static function provideOCSRoutes(): array { return [ ['core.OCS.getCapabilities', false, 'http://localhost/nextcloud/ocs/v2.php/cloud/capabilities'], ['core.OCS.getCapabilities', true, 'http://localhost/nextcloud/ocs/v2.php/cloud/capabilities'], @@ -268,7 +268,7 @@ class UrlGeneratorTest extends \Test\TestCase { $this->assertSame('http://localhost' . \OC::$WEBROOT . '/apps/dashboard/', $this->urlGenerator->linkToDefaultPageUrl()); } - public function imagePathProvider(): array { + public static function imagePathProvider(): array { return [ ['core', 'favicon-mask.svg', \OC::$WEBROOT . '/core/img/favicon-mask.svg'], ['files', 'folder.svg', \OC::$WEBROOT . '/apps/files/img/folder.svg'], diff --git a/tests/lib/User/SessionTest.php b/tests/lib/User/SessionTest.php index 7ed02571460..a10a0e87b81 100644 --- a/tests/lib/User/SessionTest.php +++ b/tests/lib/User/SessionTest.php @@ -96,7 +96,7 @@ class SessionTest extends \Test\TestCase { $this->logger, $this->dispatcher ]) - ->setMethods([ + ->onlyMethods([ 'setMagicInCookie', ]) ->getMock(); @@ -104,7 +104,7 @@ class SessionTest extends \Test\TestCase { \OC_User::setIncognitoMode(false); } - public function isLoggedInData() { + public static function isLoggedInData(): array { return [ [true], [false], @@ -121,7 +121,7 @@ class SessionTest extends \Test\TestCase { $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods([ + ->onlyMethods([ 'getUser' ]) ->getMock(); @@ -177,7 +177,7 @@ class SessionTest extends \Test\TestCase { //keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -205,7 +205,7 @@ class SessionTest extends \Test\TestCase { $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods([ + ->onlyMethods([ 'prepareUserLogin' ]) ->getMock(); @@ -244,7 +244,7 @@ class SessionTest extends \Test\TestCase { //keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -278,7 +278,7 @@ class SessionTest extends \Test\TestCase { //keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -322,7 +322,7 @@ class SessionTest extends \Test\TestCase { // Keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -360,7 +360,7 @@ class SessionTest extends \Test\TestCase { // Keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -424,7 +424,7 @@ class SessionTest extends \Test\TestCase { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -460,7 +460,7 @@ class SessionTest extends \Test\TestCase { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -486,7 +486,7 @@ class SessionTest extends \Test\TestCase { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $userSession->expects($this->once()) @@ -528,7 +528,7 @@ class SessionTest extends \Test\TestCase { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods(['login', 'isTwoFactorEnforced']) + ->onlyMethods(['login', 'isTwoFactorEnforced']) ->getMock(); $this->tokenProvider->expects($this->once()) @@ -657,7 +657,7 @@ class SessionTest extends \Test\TestCase { //keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -667,7 +667,7 @@ class SessionTest extends \Test\TestCase { ->getMock(); $userSession = $this->getMockBuilder(Session::class) //override, otherwise tests will fail because of setcookie() - ->setMethods(['setMagicInCookie', 'setLoginName']) + ->onlyMethods(['setMagicInCookie', 'setLoginName']) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) ->getMock(); @@ -747,7 +747,7 @@ class SessionTest extends \Test\TestCase { //keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -757,7 +757,7 @@ class SessionTest extends \Test\TestCase { ->getMock(); $userSession = $this->getMockBuilder(Session::class) //override, otherwise tests will fail because of setcookie() - ->setMethods(['setMagicInCookie']) + ->onlyMethods(['setMagicInCookie']) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) ->getMock(); @@ -812,7 +812,7 @@ class SessionTest extends \Test\TestCase { //keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -822,7 +822,7 @@ class SessionTest extends \Test\TestCase { ->getMock(); $userSession = $this->getMockBuilder(Session::class) //override, otherwise tests will fail because of setcookie() - ->setMethods(['setMagicInCookie']) + ->onlyMethods(['setMagicInCookie']) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) ->getMock(); @@ -865,7 +865,7 @@ class SessionTest extends \Test\TestCase { //keep following methods intact in order to ensure hooks are working $mockedManagerMethods = array_diff($managerMethods, ['__construct', 'emit', 'listen']); $manager = $this->getMockBuilder(Manager::class) - ->setMethods($mockedManagerMethods) + ->onlyMethods($mockedManagerMethods) ->setConstructorArgs([ $this->config, $this->createMock(ICacheFactory::class), @@ -875,7 +875,7 @@ class SessionTest extends \Test\TestCase { ->getMock(); $userSession = $this->getMockBuilder(Session::class) //override, otherwise tests will fail because of setcookie() - ->setMethods(['setMagicInCookie']) + ->onlyMethods(['setMagicInCookie']) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) ->getMock(); $token = 'goodToken'; @@ -925,7 +925,7 @@ class SessionTest extends \Test\TestCase { $session->set('user_id', 'foo'); $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods([ + ->onlyMethods([ 'validateSession' ]) ->getMock(); @@ -1155,7 +1155,7 @@ class SessionTest extends \Test\TestCase { $this->logger, $this->dispatcher ]) - ->setMethods([ + ->onlyMethods([ 'logClientIn', 'getUser', ]) @@ -1207,7 +1207,7 @@ class SessionTest extends \Test\TestCase { $this->logger, $this->dispatcher ]) - ->setMethods([ + ->onlyMethods([ 'logClientIn', ]) ->getMock(); @@ -1235,7 +1235,7 @@ class SessionTest extends \Test\TestCase { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $userSession->expects($this->once()) @@ -1281,7 +1281,7 @@ class SessionTest extends \Test\TestCase { /** @var Session $userSession */ $userSession = $this->getMockBuilder(Session::class) ->setConstructorArgs([$manager, $session, $this->timeFactory, $this->tokenProvider, $this->config, $this->random, $this->lockdownManager, $this->logger, $this->dispatcher]) - ->setMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser']) + ->onlyMethods(['isTokenPassword', 'login', 'supportsCookies', 'createSessionToken', 'getUser']) ->getMock(); $userSession->expects($this->once()) diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php index 44d28481ed5..694c1e757cb 100644 --- a/tests/lib/User/UserTest.php +++ b/tests/lib/User/UserTest.php @@ -496,7 +496,7 @@ class UserTest extends TestCase { $this->assertEquals(2, $hooksCalled); } - public function dataDeleteHooks() { + public static function dataDeleteHooks(): array { return [ [true, 2], [false, 1], @@ -632,7 +632,7 @@ class UserTest extends TestCase { ->onlyMethods(['getHome']) ->setConstructorArgs(['foo', $backend, $this->dispatcher, null, $config]) ->getMock(); - + $user->expects(self::atLeastOnce()) ->method('getHome') ->willReturn('/home/path'); @@ -650,7 +650,7 @@ class UserTest extends TestCase { $this->restoreService(\OCP\Comments\ICommentsManager::class); } - public function dataGetCloudId(): array { + public static function dataGetCloudId(): array { return [ ['https://localhost:8888/nextcloud', 'foo@localhost:8888/nextcloud'], ['http://localhost:8888/nextcloud', 'foo@http://localhost:8888/nextcloud'], @@ -964,7 +964,7 @@ class UserTest extends TestCase { null, $config, ]) - ->setMethods(['isEnabled', 'triggerChange']) + ->onlyMethods(['isEnabled', 'triggerChange']) ->getMock(); $user->expects($this->once()) @@ -998,7 +998,7 @@ class UserTest extends TestCase { null, $config, ]) - ->setMethods(['isEnabled', 'triggerChange']) + ->onlyMethods(['isEnabled', 'triggerChange']) ->getMock(); $user->expects($this->once()) |