Merge pull request #52851 from nextcloud/ci/noid/update-phpunit10

test: Prepare tests/ and some apps/*/tests/ for PHPUnit10
feat/add_log_scan_command
Joas Schilling 5 months ago committed by GitHub
commit c62fa55007
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 40
      apps/comments/tests/Unit/Activity/ListenerTest.php
  2. 19
      apps/comments/tests/Unit/AppInfo/ApplicationTest.php
  3. 9
      apps/comments/tests/Unit/Collaboration/CommentersSorterTest.php
  4. 30
      apps/comments/tests/Unit/Controller/NotificationsTest.php
  5. 49
      apps/comments/tests/Unit/EventHandlerTest.php
  6. 82
      apps/comments/tests/Unit/Notification/ListenerTest.php
  7. 37
      apps/comments/tests/Unit/Notification/NotifierTest.php
  8. 8
      apps/contactsinteraction/tests/Db/RecentContactMapperTest.php
  9. 8
      apps/dashboard/tests/DashboardServiceTest.php
  10. 2
      apps/files_external/tests/Storage/FtpTest.php
  11. 2
      apps/files_external/tests/Storage/SmbTest.php
  12. 12
      apps/twofactor_backupcodes/tests/Db/BackupCodeMapperTest.php
  13. 13
      apps/twofactor_backupcodes/tests/Service/BackupCodeStorageTest.php
  14. 21
      apps/twofactor_backupcodes/tests/Unit/Activity/ProviderTest.php
  15. 24
      apps/twofactor_backupcodes/tests/Unit/BackgroundJob/CheckBackupCodeTest.php
  16. 25
      apps/twofactor_backupcodes/tests/Unit/BackgroundJob/RememberBackupCodesJobTest.php
  17. 27
      apps/twofactor_backupcodes/tests/Unit/Controller/SettingsControllerTest.php
  18. 11
      apps/twofactor_backupcodes/tests/Unit/Listener/ActivityPublisherTest.php
  19. 9
      apps/twofactor_backupcodes/tests/Unit/Listener/ClearNotificationsTest.php
  20. 5
      apps/twofactor_backupcodes/tests/Unit/Listener/ProviderDisabledTest.php
  21. 5
      apps/twofactor_backupcodes/tests/Unit/Listener/ProviderEnabledTest.php
  22. 13
      apps/twofactor_backupcodes/tests/Unit/Listener/RegistryUpdaterTest.php
  23. 9
      apps/twofactor_backupcodes/tests/Unit/Migration/CheckBackupCodeTest.php
  24. 19
      apps/twofactor_backupcodes/tests/Unit/Notification/NotifierTest.php
  25. 21
      apps/twofactor_backupcodes/tests/Unit/Service/BackupCodeStorageTest.php
  26. 6
      apps/updatenotification/tests/BackgroundJob/ResetTokenTest.php
  27. 54
      apps/updatenotification/tests/BackgroundJob/UpdateAvailableNotificationsTest.php
  28. 14
      apps/updatenotification/tests/Controller/AdminControllerTest.php
  29. 10
      apps/updatenotification/tests/Notification/NotifierTest.php
  30. 6
      apps/updatenotification/tests/Settings/AdminTest.php
  31. 13
      apps/user_status/tests/Unit/BackgroundJob/ClearOldStatusesBackgroundJobTest.php
  32. 13
      apps/user_status/tests/Unit/CapabilitiesTest.php
  33. 9
      apps/user_status/tests/Unit/Connector/UserStatusProviderTest.php
  34. 12
      apps/user_status/tests/Unit/Controller/PredefinedStatusControllerTest.php
  35. 9
      apps/user_status/tests/Unit/Controller/StatusesControllerTest.php
  36. 68
      apps/user_status/tests/Unit/Controller/UserStatusControllerTest.php
  37. 33
      apps/user_status/tests/Unit/Dashboard/UserStatusWidgetTest.php
  38. 16
      apps/user_status/tests/Unit/Db/UserStatusMapperTest.php
  39. 9
      apps/user_status/tests/Unit/Listener/UserDeletedListenerTest.php
  40. 37
      apps/user_status/tests/Unit/Listener/UserLiveStatusListenerTest.php
  41. 33
      apps/user_status/tests/Unit/Service/PredefinedStatusServiceTest.php
  42. 86
      apps/user_status/tests/Unit/Service/StatusServiceTest.php
  43. 2
      apps/webhook_listeners/tests/Db/WebhookListenerMapperTest.php
  44. 38
      apps/workflowengine/tests/Check/AbstractStringCheckTest.php
  45. 43
      apps/workflowengine/tests/Check/RequestRemoteAddressTest.php
  46. 46
      apps/workflowengine/tests/Check/RequestTimeTest.php
  47. 26
      apps/workflowengine/tests/Check/RequestUserAgentTest.php
  48. 1
      lib/private/Support/CrashReport/Registry.php
  49. 23
      tests/lib/Accounts/AccountManagerTest.php
  50. 2
      tests/lib/Accounts/AccountPropertyTest.php
  51. 12
      tests/lib/Accounts/HooksTest.php
  52. 6
      tests/lib/Activity/ManagerTest.php
  53. 2
      tests/lib/AllConfigTest.php
  54. 4
      tests/lib/App/AppManagerTest.php
  55. 2
      tests/lib/App/AppStore/Fetcher/AppDiscoverFetcherTest.php
  56. 2
      tests/lib/App/AppStore/Fetcher/AppFetcherTest.php
  57. 6
      tests/lib/App/AppStore/Version/VersionParserTest.php
  58. 2
      tests/lib/App/CompareVersionTest.php
  59. 12
      tests/lib/App/DependencyAnalyzerTest.php
  60. 2
      tests/lib/App/InfoParserTest.php
  61. 2
      tests/lib/App/PlatformRepositoryTest.php
  62. 30
      tests/lib/AppConfigTest.php
  63. 2
      tests/lib/AppFramework/AppTest.php
  64. 2
      tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php
  65. 10
      tests/lib/AppFramework/Controller/AuthPublicShareControllerTest.php
  66. 2
      tests/lib/AppFramework/Controller/ControllerTest.php
  67. 2
      tests/lib/AppFramework/Controller/PublicShareControllerTest.php
  68. 2
      tests/lib/AppFramework/Db/EntityTest.php
  69. 95
      tests/lib/AppFramework/Db/QBMapperTest.php
  70. 2
      tests/lib/AppFramework/DependencyInjection/DIContainerTest.php
  71. 40
      tests/lib/AppFramework/Http/DispatcherTest.php
  72. 2
      tests/lib/AppFramework/Http/DownloadResponseTest.php
  73. 5
      tests/lib/AppFramework/Http/JSONResponseTest.php
  74. 17
      tests/lib/AppFramework/Middleware/MiddlewareDispatcherTest.php
  75. 7
      tests/lib/AppFramework/Middleware/MiddlewareTest.php
  76. 2
      tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php
  77. 120
      tests/lib/AppFramework/Middleware/OCSMiddlewareTest.php
  78. 2
      tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php
  79. 41
      tests/lib/AppFramework/Middleware/Security/BruteForceMiddlewareTest.php
  80. 16
      tests/lib/AppFramework/Middleware/Security/CORSMiddlewareTest.php
  81. 2
      tests/lib/AppFramework/Middleware/Security/PasswordConfirmationMiddlewareTest.php
  82. 2
      tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php
  83. 20
      tests/lib/AppFramework/Middleware/Security/SecurityMiddlewareTest.php
  84. 2
      tests/lib/AppFramework/OCS/V2ResponseTest.php
  85. 53
      tests/lib/AppFramework/Routing/RoutingTest.php
  86. 16
      tests/lib/AppFramework/Services/AppConfigTest.php
  87. 2
      tests/lib/AppFramework/Utility/SimpleContainerTest.php
  88. 6
      tests/lib/AppTest.php
  89. 6
      tests/lib/Archive/ZIPTest.php
  90. 15
      tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php
  91. 5
      tests/lib/Authentication/Login/ALoginTestCommand.php
  92. 2
      tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php
  93. 2
      tests/lib/Authentication/Login/CompleteLoginCommandTest.php
  94. 2
      tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php
  95. 2
      tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php
  96. 2
      tests/lib/Authentication/Login/LoggedInCheckCommandTest.php
  97. 2
      tests/lib/Authentication/Login/PreLoginHookCommandTest.php
  98. 2
      tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php
  99. 2
      tests/lib/Authentication/Login/TwoFactorCommandTest.php
  100. 2
      tests/lib/Authentication/Login/UidLoginCommandTest.php
  101. Some files were not shown because too many files have changed in this diff Show More

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later * SPDX-License-Identifier: AGPL-3.0-or-later
@ -20,30 +23,17 @@ use OCP\Files\Node;
use OCP\IUser; use OCP\IUser;
use OCP\IUserSession; use OCP\IUserSession;
use OCP\Share\IShareHelper; use OCP\Share\IShareHelper;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class ListenerTest extends TestCase { class ListenerTest extends TestCase {
protected IManager&MockObject $activityManager;
/** @var Listener */ protected IUserSession&MockObject $session;
protected $listener; protected IAppManager&MockObject $appManager;
protected IMountProviderCollection&MockObject $mountProviderCollection;
/** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ protected IRootFolder&MockObject $rootFolder;
protected $activityManager; protected IShareHelper&MockObject $shareHelper;
protected Listener $listener;
/** @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 function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -76,7 +66,7 @@ class ListenerTest extends TestCase {
->method('getObjectType') ->method('getObjectType')
->willReturn('files'); ->willReturn('files');
/** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ /** @var CommentsEvent|MockObject $event */
$event = $this->createMock(CommentsEvent::class); $event = $this->createMock(CommentsEvent::class);
$event->expects($this->any()) $event->expects($this->any())
->method('getComment') ->method('getComment')
@ -85,13 +75,13 @@ class ListenerTest extends TestCase {
->method('getEvent') ->method('getEvent')
->willReturn(CommentsEvent::EVENT_ADD); ->willReturn(CommentsEvent::EVENT_ADD);
/** @var IUser|\PHPUnit\Framework\MockObject\MockObject $ownerUser */ /** @var IUser|MockObject $ownerUser */
$ownerUser = $this->createMock(IUser::class); $ownerUser = $this->createMock(IUser::class);
$ownerUser->expects($this->any()) $ownerUser->expects($this->any())
->method('getUID') ->method('getUID')
->willReturn('937393'); ->willReturn('937393');
/** @var \PHPUnit\Framework\MockObject\MockObject $mount */ /** @var MockObject $mount */
$mount = $this->createMock(ICachedMountFileInfo::class); $mount = $this->createMock(ICachedMountFileInfo::class);
$mount->expects($this->any()) $mount->expects($this->any())
->method('getUser') ->method('getUser')
@ -133,7 +123,7 @@ class ListenerTest extends TestCase {
->method('getUser') ->method('getUser')
->willReturn($ownerUser); ->willReturn($ownerUser);
/** @var \PHPUnit\Framework\MockObject\MockObject $activity */ /** @var MockObject $activity */
$activity = $this->createMock(IEvent::class); $activity = $this->createMock(IEvent::class);
$activity->expects($this->exactly(count($al['users']))) $activity->expects($this->exactly(count($al['users'])))
->method('setAffectedUser'); ->method('setAffectedUser');

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@ -7,7 +9,12 @@
*/ */
namespace OCA\Comments\Tests\Unit\AppInfo; 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\AppInfo\Application;
use OCA\Comments\Controller\NotificationsController;
use OCA\Comments\Notification\Notifier; use OCA\Comments\Notification\Notifier;
use OCP\IUserManager; use OCP\IUserManager;
use OCP\IUserSession; use OCP\IUserSession;
@ -38,12 +45,12 @@ class ApplicationTest extends TestCase {
$c = $app->getContainer(); $c = $app->getContainer();
$services = [ $services = [
'OCA\Comments\Controller\NotificationsController', NotificationsController::class,
'OCA\Comments\Activity\Filter', Filter::class,
'OCA\Comments\Activity\Listener', Listener::class,
'OCA\Comments\Activity\Provider', Provider::class,
'OCA\Comments\Activity\Setting', Setting::class,
'OCA\Comments\Notification\Listener', \OCA\Comments\Notification\Listener::class,
Notifier::class, Notifier::class,
]; ];

@ -8,13 +8,12 @@ namespace OCA\Comments\Tests\Unit\Collaboration;
use OCA\Comments\Collaboration\CommentersSorter; use OCA\Comments\Collaboration\CommentersSorter;
use OCP\Comments\IComment; use OCP\Comments\IComment;
use OCP\Comments\ICommentsManager; use OCP\Comments\ICommentsManager;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class CommentersSorterTest extends TestCase { class CommentersSorterTest extends TestCase {
/** @var ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ protected ICommentsManager&MockObject $commentsManager;
protected $commentsManager; protected CommentersSorter $sorter;
/** @var CommentersSorter */
protected $sorter;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -55,7 +54,7 @@ class CommentersSorterTest extends TestCase {
$this->assertEquals($data['expected'], $workArray); $this->assertEquals($data['expected'], $workArray);
} }
public function sortDataProvider() { public static function sortDataProvider(): array {
return [[ return [[
[ [
#1 – sort properly and otherwise keep existing order #1 – sort properly and otherwise keep existing order

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
@ -22,26 +24,16 @@ use OCP\IUser;
use OCP\IUserSession; use OCP\IUserSession;
use OCP\Notification\IManager; use OCP\Notification\IManager;
use OCP\Notification\INotification; use OCP\Notification\INotification;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class NotificationsTest extends TestCase { class NotificationsTest extends TestCase {
/** @var NotificationsController */ protected ICommentsManager&MockObject $commentsManager;
protected $notificationsController; protected IRootFolder&MockObject $rootFolder;
protected IUserSession&MockObject $session;
/** @var ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ protected IManager&MockObject $notificationManager;
protected $commentsManager; protected IURLGenerator&MockObject $urlGenerator;
protected NotificationsController $notificationsController;
/** @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 function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -81,10 +73,6 @@ class NotificationsTest extends TestCase {
$this->urlGenerator->expects($this->exactly(2)) $this->urlGenerator->expects($this->exactly(2))
->method('linkToRoute') ->method('linkToRoute')
->withConsecutive(
['comments.Notifications.view', ['id' => '42']],
['core.login.showLoginForm', ['redirect_url' => 'link-to-comment']]
)
->willReturnMap([ ->willReturnMap([
['comments.Notifications.view', ['id' => '42'], 'link-to-comment'], ['comments.Notifications.view', ['id' => '42'], 'link-to-comment'],
['core.login.showLoginForm', ['redirect_url' => 'link-to-comment'], 'link-to-login'], ['core.login.showLoginForm', ['redirect_url' => 'link-to-comment'], 'link-to-login'],

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later * 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 OCA\Comments\Notification\Listener as NotificationListener;
use OCP\Comments\CommentsEvent; use OCP\Comments\CommentsEvent;
use OCP\Comments\IComment; use OCP\Comments\IComment;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class EventHandlerTest extends TestCase { class EventHandlerTest extends TestCase {
/** @var CommentsEventListener */ protected ActivityListener&MockObject $activityListener;
protected $eventHandler; protected NotificationListener&MockObject $notificationListener;
protected CommentsEventListener $eventHandler;
/** @var ActivityListener|\PHPUnit\Framework\MockObject\MockObject */
protected $activityListener;
/** @var NotificationListener|\PHPUnit\Framework\MockObject\MockObject */
protected $notificationListener;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
$this->activityListener = $this->getMockBuilder(ActivityListener::class) $this->activityListener = $this->createMock(ActivityListener::class);
->disableOriginalConstructor() $this->notificationListener = $this->createMock(NotificationListener::class);
->getMock();
$this->notificationListener = $this->getMockBuilder(NotificationListener::class)
->disableOriginalConstructor()
->getMock();
$this->eventHandler = new CommentsEventListener($this->activityListener, $this->notificationListener); $this->eventHandler = new CommentsEventListener($this->activityListener, $this->notificationListener);
} }
public function testNotFiles(): void { public function testNotFiles(): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ /** @var IComment|MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock(); $comment = $this->createMock(IComment::class);
$comment->expects($this->once()) $comment->expects($this->once())
->method('getObjectType') ->method('getObjectType')
->willReturn('smiles'); ->willReturn('smiles');
/** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ /** @var CommentsEvent|MockObject $event */
$event = $this->getMockBuilder(CommentsEvent::class) $event = $this->createMock(CommentsEvent::class);
->disableOriginalConstructor()
->getMock();
$event->expects($this->once()) $event->expects($this->once())
->method('getComment') ->method('getComment')
->willReturn($comment); ->willReturn($comment);
@ -56,7 +48,7 @@ class EventHandlerTest extends TestCase {
$this->eventHandler->handle($event); $this->eventHandler->handle($event);
} }
public function handledProvider() { public static function handledProvider(): array {
return [ return [
[CommentsEvent::EVENT_DELETE], [CommentsEvent::EVENT_DELETE],
[CommentsEvent::EVENT_UPDATE], [CommentsEvent::EVENT_UPDATE],
@ -67,19 +59,16 @@ class EventHandlerTest extends TestCase {
/** /**
* @dataProvider handledProvider * @dataProvider handledProvider
* @param string $eventType
*/ */
public function testHandled($eventType): void { public function testHandled(string $eventType): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ /** @var IComment|MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock(); $comment = $this->createMock(IComment::class);
$comment->expects($this->once()) $comment->expects($this->once())
->method('getObjectType') ->method('getObjectType')
->willReturn('files'); ->willReturn('files');
/** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ /** @var CommentsEvent|MockObject $event */
$event = $this->getMockBuilder(CommentsEvent::class) $event = $this->createMock(CommentsEvent::class);
->disableOriginalConstructor()
->getMock();
$event->expects($this->atLeastOnce()) $event->expects($this->atLeastOnce())
->method('getComment') ->method('getComment')
->willReturn($comment); ->willReturn($comment);

@ -14,25 +14,19 @@ use OCP\IURLGenerator;
use OCP\IUserManager; use OCP\IUserManager;
use OCP\Notification\IManager; use OCP\Notification\IManager;
use OCP\Notification\INotification; use OCP\Notification\INotification;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class ListenerTest extends TestCase { class ListenerTest extends TestCase {
/** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ protected IManager&MockObject $notificationManager;
protected $notificationManager; protected IUserManager&MockObject $userManager;
protected IURLGenerator&MockObject $urlGenerator;
/** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ protected Listener $listener;
protected $userManager;
/** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */
protected $urlGenerator;
/** @var Listener */
protected $listener;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
$this->notificationManager = $this->createMock(\OCP\Notification\IManager::class); $this->notificationManager = $this->createMock(IManager::class);
$this->userManager = $this->createMock(IUserManager::class); $this->userManager = $this->createMock(IUserManager::class);
$this->listener = new Listener( $this->listener = new Listener(
@ -41,7 +35,7 @@ class ListenerTest extends TestCase {
); );
} }
public function eventProvider() { public static function eventProvider(): array {
return [ return [
[CommentsEvent::EVENT_ADD, 'notify'], [CommentsEvent::EVENT_ADD, 'notify'],
[CommentsEvent::EVENT_UPDATE, 'notify'], [CommentsEvent::EVENT_UPDATE, 'notify'],
@ -56,8 +50,8 @@ class ListenerTest extends TestCase {
* @param string $notificationMethod * @param string $notificationMethod
*/ */
public function testEvaluate($eventType, $notificationMethod): void { public function testEvaluate($eventType, $notificationMethod): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ /** @var IComment|MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock(); $comment = $this->createMock(IComment::class);
$comment->expects($this->any()) $comment->expects($this->any())
->method('getObjectType') ->method('getObjectType')
->willReturn('files'); ->willReturn('files');
@ -78,10 +72,8 @@ class ListenerTest extends TestCase {
->method('getId') ->method('getId')
->willReturn('1234'); ->willReturn('1234');
/** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ /** @var CommentsEvent|MockObject $event */
$event = $this->getMockBuilder(CommentsEvent::class) $event = $this->createMock(CommentsEvent::class);
->disableOriginalConstructor()
->getMock();
$event->expects($this->once()) $event->expects($this->once())
->method('getComment') ->method('getComment')
->willReturn($comment); ->willReturn($comment);
@ -89,8 +81,8 @@ class ListenerTest extends TestCase {
->method(('getEvent')) ->method(('getEvent'))
->willReturn($eventType); ->willReturn($eventType);
/** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ /** @var INotification|MockObject $notification */
$notification = $this->getMockBuilder(INotification::class)->getMock(); $notification = $this->createMock(INotification::class);
$notification->expects($this->any()) $notification->expects($this->any())
->method($this->anything()) ->method($this->anything())
->willReturn($notification); ->willReturn($notification);
@ -106,26 +98,24 @@ class ListenerTest extends TestCase {
$this->userManager->expects($this->exactly(6)) $this->userManager->expects($this->exactly(6))
->method('userExists') ->method('userExists')
->withConsecutive( ->willReturnMap([
['foobar'], ['foobar', true],
['barfoo'], ['barfoo', true],
['foo@bar.com'], ['foo@bar.com', true],
['bar@foo.org@foobar.io'], ['bar@foo.org@foobar.io', true],
['23452-4333-54353-2342'], ['23452-4333-54353-2342', true],
['yolo'] ['yolo', true]
) ]);
->willReturn(true);
$this->listener->evaluate($event); $this->listener->evaluate($event);
} }
/** /**
* @dataProvider eventProvider * @dataProvider eventProvider
* @param string $eventType
*/ */
public function testEvaluateNoMentions($eventType): void { public function testEvaluateNoMentions(string $eventType): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ /** @var IComment|MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock(); $comment = $this->createMock(IComment::class);
$comment->expects($this->any()) $comment->expects($this->any())
->method('getObjectType') ->method('getObjectType')
->willReturn('files'); ->willReturn('files');
@ -136,10 +126,8 @@ class ListenerTest extends TestCase {
->method('getMentions') ->method('getMentions')
->willReturn([]); ->willReturn([]);
/** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ /** @var CommentsEvent|MockObject $event */
$event = $this->getMockBuilder(CommentsEvent::class) $event = $this->createMock(CommentsEvent::class);
->disableOriginalConstructor()
->getMock();
$event->expects($this->once()) $event->expects($this->once())
->method('getComment') ->method('getComment')
->willReturn($comment); ->willReturn($comment);
@ -161,8 +149,8 @@ class ListenerTest extends TestCase {
} }
public function testEvaluateUserDoesNotExist(): void { public function testEvaluateUserDoesNotExist(): void {
/** @var IComment|\PHPUnit\Framework\MockObject\MockObject $comment */ /** @var IComment|MockObject $comment */
$comment = $this->getMockBuilder(IComment::class)->getMock(); $comment = $this->createMock(IComment::class);
$comment->expects($this->any()) $comment->expects($this->any())
->method('getObjectType') ->method('getObjectType')
->willReturn('files'); ->willReturn('files');
@ -176,10 +164,8 @@ class ListenerTest extends TestCase {
->method('getId') ->method('getId')
->willReturn('1234'); ->willReturn('1234');
/** @var CommentsEvent|\PHPUnit\Framework\MockObject\MockObject $event */ /** @var CommentsEvent|MockObject $event */
$event = $this->getMockBuilder(CommentsEvent::class) $event = $this->createMock(CommentsEvent::class);
->disableOriginalConstructor()
->getMock();
$event->expects($this->once()) $event->expects($this->once())
->method('getComment') ->method('getComment')
->willReturn($comment); ->willReturn($comment);
@ -187,8 +173,8 @@ class ListenerTest extends TestCase {
->method(('getEvent')) ->method(('getEvent'))
->willReturn(CommentsEvent::EVENT_ADD); ->willReturn(CommentsEvent::EVENT_ADD);
/** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ /** @var INotification|MockObject $notification */
$notification = $this->getMockBuilder(INotification::class)->getMock(); $notification = $this->createMock(INotification::class);
$notification->expects($this->any()) $notification->expects($this->any())
->method($this->anything()) ->method($this->anything())
->willReturn($notification); ->willReturn($notification);
@ -203,9 +189,7 @@ class ListenerTest extends TestCase {
$this->userManager->expects($this->once()) $this->userManager->expects($this->once())
->method('userExists') ->method('userExists')
->withConsecutive( ->with('foobar')
['foobar']
)
->willReturn(false); ->willReturn(false);
$this->listener->evaluate($event); $this->listener->evaluate($event);

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later * SPDX-License-Identifier: AGPL-3.0-or-later
@ -23,26 +26,16 @@ use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class NotifierTest extends TestCase { class NotifierTest extends TestCase {
/** @var Notifier */ protected IFactory&MockObject $l10nFactory;
protected $notifier; protected IL10N&MockObject $l;
/** @var IFactory|MockObject */ protected IRootFolder&MockObject $folder;
protected $l10nFactory; protected ICommentsManager&MockObject $commentsManager;
/** @var IL10N|MockObject */ protected IURLGenerator&MockObject $url;
protected $l; protected IUserManager&MockObject $userManager;
/** @var IRootFolder|MockObject */ protected INotification&MockObject $notification;
protected $folder; protected IComment&MockObject $comment;
/** @var ICommentsManager|MockObject */ protected Notifier $notifier;
protected $commentsManager; protected string $lc = 'tlh_KX';
/** @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 function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -75,9 +68,8 @@ class NotifierTest extends TestCase {
public function testPrepareSuccess(): void { public function testPrepareSuccess(): void {
$fileName = 'Gre\'thor.odp'; $fileName = 'Gre\'thor.odp';
$displayName = 'Huraga'; $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 = $this->createMock(Node::class);
$node $node
->expects($this->atLeastOnce()) ->expects($this->atLeastOnce())
@ -192,7 +184,6 @@ class NotifierTest extends TestCase {
public function testPrepareSuccessDeletedUser(): void { public function testPrepareSuccessDeletedUser(): void {
$fileName = 'Gre\'thor.odp'; $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 */ /** @var Node|MockObject $node */
$node = $this->createMock(Node::class); $node = $this->createMock(Node::class);

@ -21,12 +21,8 @@ use Test\TestCase;
* @group DB * @group DB
*/ */
class RecentContactMapperTest extends TestCase { class RecentContactMapperTest extends TestCase {
private RecentContactMapper $recentContactMapper;
/** @var RecentContactMapper */ private ITimeFactory $time;
private $recentContactMapper;
/** @var ITimeFactory */
private $time;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -40,7 +40,7 @@ class DashboardServiceTest extends TestCase {
); );
} }
public function testGetBirthdate() { public function testGetBirthdate(): void {
$user = $this->createMock(IUser::class); $user = $this->createMock(IUser::class);
$this->userManager->method('get') $this->userManager->method('get')
->willReturn($user); ->willReturn($user);
@ -61,7 +61,7 @@ class DashboardServiceTest extends TestCase {
$this->assertEquals('2024-12-10T00:00:00.000Z', $birthdate); $this->assertEquals('2024-12-10T00:00:00.000Z', $birthdate);
} }
public function testGetBirthdatePropertyDoesNotExist() { public function testGetBirthdatePropertyDoesNotExist(): void {
$user = $this->createMock(IUser::class); $user = $this->createMock(IUser::class);
$this->userManager->method('get') $this->userManager->method('get')
->willReturn($user); ->willReturn($user);
@ -75,7 +75,7 @@ class DashboardServiceTest extends TestCase {
$this->assertEquals('', $birthdate); $this->assertEquals('', $birthdate);
} }
public function testGetBirthdateUserNotFound() { public function testGetBirthdateUserNotFound(): void {
$this->userManager->method('get') $this->userManager->method('get')
->willReturn(null); ->willReturn(null);
@ -84,7 +84,7 @@ class DashboardServiceTest extends TestCase {
$this->assertEquals('', $birthdate); $this->assertEquals('', $birthdate);
} }
public function testGetBirthdateNoUserId() { public function testGetBirthdateNoUserId(): void {
$service = new DashboardService( $service = new DashboardService(
$this->config, $this->config,
null, null,

@ -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 * 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 array_filter(parent::directoryProvider(), function ($item) {
return substr($item[0], -1) !== ' '; return substr($item[0], -1) !== ' ';
}); });

@ -49,7 +49,7 @@ class SmbTest extends \Test\Files\Storage\Storage {
parent::tearDown(); parent::tearDown();
} }
public function directoryProvider() { public static function directoryProvider(): array {
// doesn't support leading/trailing spaces // doesn't support leading/trailing spaces
return [['folder']]; return [['folder']];
} }

@ -19,15 +19,9 @@ use Test\TestCase;
* @group DB * @group DB
*/ */
class BackupCodeMapperTest extends TestCase { class BackupCodeMapperTest extends TestCase {
private IDBConnection $db;
/** @var IDBConnection */ private BackupCodeMapper $mapper;
private $db; private string $testUID = 'test123456';
/** @var BackupCodeMapper */
private $mapper;
/** @var string */
private $testUID = 'test123456';
private function resetDB() { private function resetDB() {
$qb = $this->db->getQueryBuilder(); $qb = $this->db->getQueryBuilder();

@ -13,21 +13,16 @@ use OCP\IUser;
use OCP\Notification\IManager; use OCP\Notification\IManager;
use OCP\Notification\INotification; use OCP\Notification\INotification;
use OCP\Server; use OCP\Server;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
/** /**
* @group DB * @group DB
*/ */
class BackupCodeStorageTest extends TestCase { class BackupCodeStorageTest extends TestCase {
private IManager&MockObject $notificationManager;
/** @var BackupCodeStorage */ private string $testUID = 'test123456789';
private $storage; private BackupCodeStorage $storage;
/** @var string */
private $testUID = 'test123456789';
/** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
private $notificationManager;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -15,21 +15,14 @@ use OCP\Activity\IManager;
use OCP\IL10N; use OCP\IL10N;
use OCP\IURLGenerator; use OCP\IURLGenerator;
use OCP\L10N\IFactory; use OCP\L10N\IFactory;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class ProviderTest extends TestCase { class ProviderTest extends TestCase {
private IFactory&MockObject $l10n;
/** @var IFactory|\PHPUnit\Framework\MockObject\MockObject */ private IURLGenerator&MockObject $urlGenerator;
private $l10n; private IManager&MockObject $activityManager;
private Provider $provider;
/** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */
private $urlGenerator;
/** @var IManager|\PHPUnit\Framework\MockObject\MockObject */
private $activityManager;
/** @var Provider */
private $provider;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -52,7 +45,7 @@ class ProviderTest extends TestCase {
$this->provider->parse($lang, $event); $this->provider->parse($lang, $event);
} }
public function subjectData() { public static function subjectData(): array {
return [ return [
['codes_generated'], ['codes_generated'],
]; ];
@ -61,7 +54,7 @@ class ProviderTest extends TestCase {
/** /**
* @dataProvider subjectData * @dataProvider subjectData
*/ */
public function testParse($subject): void { public function testParse(string $subject): void {
$lang = 'ru'; $lang = 'ru';
$event = $this->createMock(IEvent::class); $event = $this->createMock(IEvent::class);
$l = $this->createMock(IL10N::class); $l = $this->createMock(IL10N::class);

@ -20,24 +20,12 @@ use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class CheckBackupCodeTest extends TestCase { class CheckBackupCodeTest extends TestCase {
private IUserManager&MockObject $userManager;
/** @var IUserManager|MockObject */ private IJobList&MockObject $jobList;
private $userManager; private IRegistry&MockObject $registry;
private Manager&MockObject $manager;
/** @var IJobList|MockObject */ private IUser&MockObject $user;
private $jobList; private CheckBackupCodes $checkBackupCodes;
/** @var IRegistry|MockObject */
private $registry;
/** @var Manager|MockObject */
private $manager;
/** @var IUser|MockObject */
private $user;
/** @var CheckBackupCodes */
private $checkBackupCodes;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -17,27 +17,16 @@ use OCP\IUserManager;
use OCP\Notification\IManager; use OCP\Notification\IManager;
use OCP\Notification\INotification; use OCP\Notification\INotification;
use OCP\Server; use OCP\Server;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class RememberBackupCodesJobTest extends TestCase { class RememberBackupCodesJobTest extends TestCase {
private IRegistry&MockObject $registry;
/** @var IRegistry|\PHPUnit\Framework\MockObject\MockObject */ private IUserManager&MockObject $userManager;
private $registry; private ITimeFactory&MockObject $time;
private IManager&MockObject $notificationManager;
/** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ private IJobList&MockObject $jobList;
private $userManager; private RememberBackupCodesJob $job;
/** @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;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -14,36 +14,27 @@ use OCP\AppFramework\Http\JSONResponse;
use OCP\IRequest; use OCP\IRequest;
use OCP\IUser; use OCP\IUser;
use OCP\IUserSession; use OCP\IUserSession;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class SettingsControllerTest extends TestCase { class SettingsControllerTest extends TestCase {
private IRequest&MockObject $request;
/** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ private BackupCodeStorage&MockObject $storage;
private $request; private IUserSession&MockObject $userSession;
private SettingsController $controller;
/** @var BackupCodeStorage|\PHPUnit\Framework\MockObject\MockObject */
private $storage;
/** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */
private $userSession;
/** @var SettingsController */
private $controller;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
$this->request = $this->getMockBuilder(IRequest::class)->getMock(); $this->request = $this->createMock(IRequest::class);
$this->storage = $this->getMockBuilder(BackupCodeStorage::class) $this->storage = $this->createMock(BackupCodeStorage::class);
->disableOriginalConstructor() $this->userSession = $this->createMock(IUserSession::class);
->getMock();
$this->userSession = $this->getMockBuilder(IUserSession::class)->getMock();
$this->controller = new SettingsController('twofactor_backupcodes', $this->request, $this->storage, $this->userSession); $this->controller = new SettingsController('twofactor_backupcodes', $this->request, $this->storage, $this->userSession);
} }
public function testCreateCodes(): void { public function testCreateCodes(): void {
$user = $this->getMockBuilder(IUser::class)->getMock(); $user = $this->createMock(IUser::class);
$codes = ['a', 'b']; $codes = ['a', 'b'];
$this->userSession->expects($this->once()) $this->userSession->expects($this->once())

@ -19,14 +19,9 @@ use Psr\Log\LoggerInterface;
use Test\TestCase; use Test\TestCase;
class ActivityPublisherTest extends TestCase { class ActivityPublisherTest extends TestCase {
/** @var IManager|MockObject */ private IManager&MockObject $activityManager;
private $activityManager; private LoggerInterface&MockObject $logger;
private ActivityPublisher $listener;
/** @var LoggerInterface */
private $logger;
/** @var ActivityPublisher */
private $listener;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -15,15 +15,12 @@ use OCP\IUser;
use OCP\Notification\IManager; use OCP\Notification\IManager;
use OCP\Notification\INotification; use OCP\Notification\INotification;
use OCP\Server; use OCP\Server;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class ClearNotificationsTest extends TestCase { class ClearNotificationsTest extends TestCase {
private IManager&MockObject $notificationManager;
/** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ private ClearNotifications $listener;
private $notificationManager;
/** @var ClearNotifications */
private $listener;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -15,11 +15,12 @@ use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserUnregistered;
use OCP\BackgroundJob\IJobList; use OCP\BackgroundJob\IJobList;
use OCP\EventDispatcher\Event; use OCP\EventDispatcher\Event;
use OCP\IUser; use OCP\IUser;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class ProviderDisabledTest extends TestCase { class ProviderDisabledTest extends TestCase {
private IRegistry $registy; private IRegistry&MockObject $registy;
private IJobList $jobList; private IJobList&MockObject $jobList;
private ProviderDisabled $listener; private ProviderDisabled $listener;
protected function setUp(): void { protected function setUp(): void {

@ -15,11 +15,12 @@ use OCP\Authentication\TwoFactorAuth\TwoFactorProviderForUserRegistered;
use OCP\BackgroundJob\IJobList; use OCP\BackgroundJob\IJobList;
use OCP\EventDispatcher\Event; use OCP\EventDispatcher\Event;
use OCP\IUser; use OCP\IUser;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class ProviderEnabledTest extends TestCase { class ProviderEnabledTest extends TestCase {
private IRegistry $registy; private IRegistry&MockObject $registy;
private IJobList $jobList; private IJobList&MockObject $jobList;
private ProviderEnabled $listener; private ProviderEnabled $listener;
protected function setUp(): void { protected function setUp(): void {

@ -14,18 +14,13 @@ use OCA\TwoFactorBackupCodes\Provider\BackupCodesProvider;
use OCP\Authentication\TwoFactorAuth\IRegistry; use OCP\Authentication\TwoFactorAuth\IRegistry;
use OCP\EventDispatcher\Event; use OCP\EventDispatcher\Event;
use OCP\IUser; use OCP\IUser;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class RegistryUpdaterTest extends TestCase { class RegistryUpdaterTest extends TestCase {
private IRegistry&MockObject $registry;
/** @var IRegistry */ private BackupCodesProvider&MockObject $provider;
private $registry; private RegistryUpdater $listener;
/** @var BackupCodesProvider */
private $provider;
/** @var RegistryUpdater */
private $listener;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -11,15 +11,12 @@ namespace OCA\TwoFactorBackupCodes\Tests\Unit\Migration;
use OCA\TwoFactorBackupCodes\Migration\CheckBackupCodes; use OCA\TwoFactorBackupCodes\Migration\CheckBackupCodes;
use OCP\BackgroundJob\IJobList; use OCP\BackgroundJob\IJobList;
use OCP\Migration\IOutput; use OCP\Migration\IOutput;
use PHPunit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class CheckBackupCodeTest extends TestCase { class CheckBackupCodeTest extends TestCase {
private IJobList&MockObject $jobList;
/** @var IJobList|\PHPunit\Framework\MockObject\MockObject */ private CheckBackupCodes $checkBackupsCodes;
private $jobList;
/** @var CheckBackupCodes */
private $checkBackupsCodes;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -17,15 +17,10 @@ use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class NotifierTest extends TestCase { class NotifierTest extends TestCase {
/** @var Notifier */ protected IFactory&MockObject $factory;
protected $notifier; protected IURLGenerator&MockObject $url;
protected IL10N&MockObject $l;
/** @var IFactory|MockObject */ protected Notifier $notifier;
protected $factory;
/** @var IURLGenerator|MockObject */
protected $url;
/** @var IL10N|MockObject */
protected $l;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -52,7 +47,7 @@ class NotifierTest extends TestCase {
public function testPrepareWrongApp(): void { public function testPrepareWrongApp(): void {
$this->expectException(\InvalidArgumentException::class); $this->expectException(\InvalidArgumentException::class);
/** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ /** @var INotification|MockObject $notification */
$notification = $this->createMock(INotification::class); $notification = $this->createMock(INotification::class);
$notification->expects($this->once()) $notification->expects($this->once())
->method('getApp') ->method('getApp')
@ -67,7 +62,7 @@ class NotifierTest extends TestCase {
public function testPrepareWrongSubject(): void { public function testPrepareWrongSubject(): void {
$this->expectException(\InvalidArgumentException::class); $this->expectException(\InvalidArgumentException::class);
/** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ /** @var INotification|MockObject $notification */
$notification = $this->createMock(INotification::class); $notification = $this->createMock(INotification::class);
$notification->expects($this->once()) $notification->expects($this->once())
->method('getApp') ->method('getApp')
@ -80,7 +75,7 @@ class NotifierTest extends TestCase {
} }
public function testPrepare(): void { public function testPrepare(): void {
/** @var INotification|\PHPUnit\Framework\MockObject\MockObject $notification */ /** @var INotification&MockObject $notification */
$notification = $this->createMock(INotification::class); $notification = $this->createMock(INotification::class);
$notification->expects($this->once()) $notification->expects($this->once())

@ -16,24 +16,15 @@ use OCP\EventDispatcher\IEventDispatcher;
use OCP\IUser; use OCP\IUser;
use OCP\Security\IHasher; use OCP\Security\IHasher;
use OCP\Security\ISecureRandom; use OCP\Security\ISecureRandom;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class BackupCodeStorageTest extends TestCase { class BackupCodeStorageTest extends TestCase {
private BackupCodeMapper&MockObject $mapper;
/** @var BackupCodeMapper|\PHPUnit\Framework\MockObject\MockObject */ private ISecureRandom&MockObject $random;
private $mapper; private IHasher&MockObject $hasher;
private IEventDispatcher&MockObject $eventDispatcher;
/** @var ISecureRandom|\PHPUnit\Framework\MockObject\MockObject */ private BackupCodeStorage $storage;
private $random;
/** @var IHasher|\PHPUnit\Framework\MockObject\MockObject */
private $hasher;
/** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */
private $eventDispatcher;
/** @var BackupCodeStorage */
private $storage;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -16,9 +16,9 @@ use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class ResetTokenTest extends TestCase { class ResetTokenTest extends TestCase {
private IConfig|MockObject $config; private IConfig&MockObject $config;
private IAppConfig|MockObject $appConfig; private IAppConfig&MockObject $appConfig;
private ITimeFactory|MockObject $timeFactory; private ITimeFactory&MockObject $timeFactory;
private BackgroundJobResetToken $resetTokenBackgroundJob; private BackgroundJobResetToken $resetTokenBackgroundJob;
protected function setUp(): void { protected function setUp(): void {

@ -26,14 +26,14 @@ use Test\TestCase;
class UpdateAvailableNotificationsTest extends TestCase { class UpdateAvailableNotificationsTest extends TestCase {
private ServerVersion&MockObject $serverVersion; private ServerVersion&MockObject $serverVersion;
private IConfig|MockObject $config; private IConfig&MockObject $config;
private IManager|MockObject $notificationManager; private IManager&MockObject $notificationManager;
private IGroupManager|MockObject $groupManager; private IGroupManager&MockObject $groupManager;
private IAppManager|MockObject $appManager; private IAppManager&MockObject $appManager;
private IAppConfig|MockObject $appConfig; private IAppConfig&MockObject $appConfig;
private ITimeFactory|MockObject $timeFactory; private ITimeFactory&MockObject $timeFactory;
private Installer|MockObject $installer; private Installer&MockObject $installer;
private VersionCheck|MockObject $versionCheck; private VersionCheck&MockObject $versionCheck;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -50,10 +50,9 @@ class UpdateAvailableNotificationsTest extends TestCase {
} }
/** /**
* @param array $methods
* @return UpdateAvailableNotifications|MockObject * @return UpdateAvailableNotifications|MockObject
*/ */
protected function getJob(array $methods = []) { protected function getJob(array $methods = []): UpdateAvailableNotifications {
if (empty($methods)) { if (empty($methods)) {
return new UpdateAvailableNotifications( return new UpdateAvailableNotifications(
$this->timeFactory, $this->timeFactory,
@ -125,7 +124,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
self::invokePrivate($job, 'run', [null]); self::invokePrivate($job, 'run', [null]);
} }
public function dataCheckCoreUpdate(): array { public static function dataCheckCoreUpdate(): array {
return [ return [
['daily', null, null, null, null], ['daily', null, null, null, null],
['git', null, null, null, null], ['git', null, null, null, null],
@ -155,14 +154,8 @@ class UpdateAvailableNotificationsTest extends TestCase {
/** /**
* @dataProvider dataCheckCoreUpdate * @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([ $job = $this->getJob([
'createNotifications', 'createNotifications',
'clearErrorNotifications', 'clearErrorNotifications',
@ -223,7 +216,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
self::invokePrivate($job, 'checkCoreUpdate'); self::invokePrivate($job, 'checkCoreUpdate');
} }
public function dataCheckAppUpdates(): array { public static function dataCheckAppUpdates(): array {
return [ return [
[ [
['app1', 'app2'], ['app1', 'app2'],
@ -240,10 +233,6 @@ class UpdateAvailableNotificationsTest extends TestCase {
/** /**
* @dataProvider dataCheckAppUpdates * @dataProvider dataCheckAppUpdates
*
* @param string[] $apps
* @param array $isUpdateAvailable
* @param array $notifications
*/ */
public function testCheckAppUpdates(array $apps, array $isUpdateAvailable, array $notifications): void { public function testCheckAppUpdates(array $apps, array $isUpdateAvailable, array $notifications): void {
$job = $this->getJob([ $job = $this->getJob([
@ -271,7 +260,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
self::invokePrivate($job, 'checkAppUpdates'); self::invokePrivate($job, 'checkAppUpdates');
} }
public function dataCreateNotifications(): array { public static function dataCreateNotifications(): array {
return [ return [
['app1', '1.0.0', '1.0.0', false, false, null, null], ['app1', '1.0.0', '1.0.0', false, false, null, null],
['app2', '1.0.1', '1.0.0', '1.0.0', true, ['user1'], [['user1']]], ['app2', '1.0.1', '1.0.0', '1.0.0', true, ['user1'], [['user1']]],
@ -281,16 +270,8 @@ class UpdateAvailableNotificationsTest extends TestCase {
/** /**
* @dataProvider dataCreateNotifications * @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([ $job = $this->getJob([
'deleteOutdatedNotifications', 'deleteOutdatedNotifications',
'getUsersToNotify', 'getUsersToNotify',
@ -363,7 +344,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
self::invokePrivate($job, 'createNotifications', [$app, $version]); self::invokePrivate($job, 'createNotifications', [$app, $version]);
} }
public function dataGetUsersToNotify(): array { public static function dataGetUsersToNotify(): array {
return [ return [
[['g1', 'g2'], ['g1' => null, 'g2' => ['u1', 'u2']], ['u1', 'u2']], [['g1', 'g2'], ['g1' => null, 'g2' => ['u1', 'u2']], ['u1', 'u2']],
[['g3', 'g4'], ['g3' => ['u1', 'u2'], 'g4' => ['u2', 'u3']], ['u1', 'u2', 'u3']], [['g3', 'g4'], ['g3' => ['u1', 'u2'], 'g4' => ['u2', 'u3']], ['u1', 'u2', 'u3']],
@ -372,9 +353,6 @@ class UpdateAvailableNotificationsTest extends TestCase {
/** /**
* @dataProvider dataGetUsersToNotify * @dataProvider dataGetUsersToNotify
* @param string[] $groups
* @param array $groupUsers
* @param string[] $expected
*/ */
public function testGetUsersToNotify(array $groups, array $groupUsers, array $expected): void { public function testGetUsersToNotify(array $groups, array $groupUsers, array $expected): void {
$job = $this->getJob(); $job = $this->getJob();
@ -408,7 +386,7 @@ class UpdateAvailableNotificationsTest extends TestCase {
$this->assertEquals($expected, $result); $this->assertEquals($expected, $result);
} }
public function dataDeleteOutdatedNotifications(): array { public static function dataDeleteOutdatedNotifications(): array {
return [ return [
['app1', '1.1.0'], ['app1', '1.1.0'],
['app2', '1.2.0'], ['app2', '1.2.0'],

@ -22,13 +22,13 @@ use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class AdminControllerTest extends TestCase { class AdminControllerTest extends TestCase {
private IRequest|MockObject $request; private IRequest&MockObject $request;
private IJobList|MockObject $jobList; private IJobList&MockObject $jobList;
private ISecureRandom|MockObject $secureRandom; private ISecureRandom&MockObject $secureRandom;
private IConfig|MockObject $config; private IConfig&MockObject $config;
private ITimeFactory|MockObject $timeFactory; private ITimeFactory&MockObject $timeFactory;
private IL10N|MockObject $l10n; private IL10N&MockObject $l10n;
private IAppConfig|MockObject $appConfig; private IAppConfig&MockObject $appConfig;
private AdminController $adminController; private AdminController $adminController;

@ -49,9 +49,9 @@ class NotifierTest extends TestCase {
/** /**
* @param array $methods * @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)) { if (empty($methods)) {
return new Notifier( return new Notifier(
$this->urlGenerator, $this->urlGenerator,
@ -81,7 +81,7 @@ class NotifierTest extends TestCase {
} }
} }
public function dataUpdateAlreadyInstalledCheck(): array { public static function dataUpdateAlreadyInstalledCheck(): array {
return [ return [
['1.1.0', '1.0.0', false], ['1.1.0', '1.0.0', false],
['1.1.0', '1.1.0', true], ['1.1.0', '1.1.0', true],
@ -91,10 +91,6 @@ class NotifierTest extends TestCase {
/** /**
* @dataProvider dataUpdateAlreadyInstalledCheck * @dataProvider dataUpdateAlreadyInstalledCheck
*
* @param string $versionNotification
* @param string $versionInstalled
* @param bool $exception
*/ */
public function testUpdateAlreadyInstalledCheck(string $versionNotification, string $versionInstalled, bool $exception): void { public function testUpdateAlreadyInstalledCheck(string $versionNotification, string $versionInstalled, bool $exception): void {
$notifier = $this->getNotifier(); $notifier = $this->getNotifier();

@ -29,9 +29,6 @@ use Psr\Log\LoggerInterface;
use Test\TestCase; use Test\TestCase;
class AdminTest extends TestCase { class AdminTest extends TestCase {
private Admin $admin;
private IFactory&MockObject $l10nFactory; private IFactory&MockObject $l10nFactory;
private IConfig&MockObject $config; private IConfig&MockObject $config;
private IAppConfig&MockObject $appConfig; private IAppConfig&MockObject $appConfig;
@ -43,6 +40,7 @@ class AdminTest extends TestCase {
private LoggerInterface&MockObject $logger; private LoggerInterface&MockObject $logger;
private IInitialState&MockObject $initialState; private IInitialState&MockObject $initialState;
private ServerVersion&MockObject $serverVersion; private ServerVersion&MockObject $serverVersion;
private Admin $admin;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -395,7 +393,7 @@ class AdminTest extends TestCase {
$this->assertSame(11, $this->admin->getPriority()); $this->assertSame(11, $this->admin->getPriority());
} }
public function changesProvider() { public static function changesProvider(): array {
return [ return [
[ #0, all info, en [ #0, all info, en
[ [

@ -11,18 +11,13 @@ namespace OCA\UserStatus\Tests\BackgroundJob;
use OCA\UserStatus\BackgroundJob\ClearOldStatusesBackgroundJob; use OCA\UserStatus\BackgroundJob\ClearOldStatusesBackgroundJob;
use OCA\UserStatus\Db\UserStatusMapper; use OCA\UserStatus\Db\UserStatusMapper;
use OCP\AppFramework\Utility\ITimeFactory; use OCP\AppFramework\Utility\ITimeFactory;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class ClearOldStatusesBackgroundJobTest extends TestCase { class ClearOldStatusesBackgroundJobTest extends TestCase {
private ITimeFactory&MockObject $time;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ private UserStatusMapper&MockObject $mapper;
private $time; private ClearOldStatusesBackgroundJob $job;
/** @var UserStatusMapper|\PHPUnit\Framework\MockObject\MockObject */
private $mapper;
/** @var ClearOldStatusesBackgroundJob */
private $job;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -10,15 +10,12 @@ namespace OCA\UserStatus\Tests;
use OCA\UserStatus\Capabilities; use OCA\UserStatus\Capabilities;
use OCP\IEmojiHelper; use OCP\IEmojiHelper;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class CapabilitiesTest extends TestCase { class CapabilitiesTest extends TestCase {
private IEmojiHelper&MockObject $emojiHelper;
/** @var IEmojiHelper|\PHPUnit\Framework\MockObject\MockObject */ private Capabilities $capabilities;
private $emojiHelper;
/** @var Capabilities */
private $capabilities;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -28,8 +25,6 @@ class CapabilitiesTest extends TestCase {
} }
/** /**
* @param bool $supportsEmojis
*
* @dataProvider getCapabilitiesDataProvider * @dataProvider getCapabilitiesDataProvider
*/ */
public function testGetCapabilities(bool $supportsEmojis): void { public function testGetCapabilities(bool $supportsEmojis): void {
@ -46,7 +41,7 @@ class CapabilitiesTest extends TestCase {
], $this->capabilities->getCapabilities()); ], $this->capabilities->getCapabilities());
} }
public function getCapabilitiesDataProvider(): array { public static function getCapabilitiesDataProvider(): array {
return [ return [
[true], [true],
[false], [false],

@ -11,15 +11,12 @@ namespace OCA\UserStatus\Tests\Connector;
use OCA\UserStatus\Connector\UserStatusProvider; use OCA\UserStatus\Connector\UserStatusProvider;
use OCA\UserStatus\Db\UserStatus; use OCA\UserStatus\Db\UserStatus;
use OCA\UserStatus\Service\StatusService; use OCA\UserStatus\Service\StatusService;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class UserStatusProviderTest extends TestCase { class UserStatusProviderTest extends TestCase {
private StatusService&MockObject $service;
/** @var \PHPUnit\Framework\MockObject\MockObject */ private UserStatusProvider $provider;
private $service;
/** @var UserStatusProvider */
private $provider;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -11,15 +11,12 @@ namespace OCA\UserStatus\Tests\Controller;
use OCA\UserStatus\Controller\PredefinedStatusController; use OCA\UserStatus\Controller\PredefinedStatusController;
use OCA\UserStatus\Service\PredefinedStatusService; use OCA\UserStatus\Service\PredefinedStatusService;
use OCP\IRequest; use OCP\IRequest;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class PredefinedStatusControllerTest extends TestCase { class PredefinedStatusControllerTest extends TestCase {
private PredefinedStatusService&MockObject $service;
/** @var PredefinedStatusService|\PHPUnit\Framework\MockObject\MockObject */ private PredefinedStatusController $controller;
private $service;
/** @var PredefinedStatusController */
private $controller;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -27,8 +24,7 @@ class PredefinedStatusControllerTest extends TestCase {
$request = $this->createMock(IRequest::class); $request = $this->createMock(IRequest::class);
$this->service = $this->createMock(PredefinedStatusService::class); $this->service = $this->createMock(PredefinedStatusService::class);
$this->controller = new PredefinedStatusController('user_status', $request, $this->controller = new PredefinedStatusController('user_status', $request, $this->service);
$this->service);
} }
public function testFindAll(): void { public function testFindAll(): void {

@ -14,15 +14,12 @@ use OCA\UserStatus\Service\StatusService;
use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\OCS\OCSNotFoundException; use OCP\AppFramework\OCS\OCSNotFoundException;
use OCP\IRequest; use OCP\IRequest;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class StatusesControllerTest extends TestCase { class StatusesControllerTest extends TestCase {
private StatusService&MockObject $service;
/** @var StatusService|\PHPUnit\Framework\MockObject\MockObject */ private StatusesController $controller;
private $service;
/** @var StatusesController */
private $controller;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -21,22 +21,16 @@ use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\OCS\OCSBadRequestException; use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSNotFoundException; use OCP\AppFramework\OCS\OCSNotFoundException;
use OCP\IRequest; use OCP\IRequest;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Test\TestCase; use Test\TestCase;
use Throwable; use Throwable;
class UserStatusControllerTest extends TestCase { class UserStatusControllerTest extends TestCase {
/** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ private LoggerInterface&MockObject $logger;
private $logger; private StatusService&MockObject $statusService;
private CalendarStatusService&MockObject $calendarStatusService;
/** @var StatusService|\PHPUnit\Framework\MockObject\MockObject */ private UserStatusController $controller;
private $statusService;
/** @var CalendarStatusService|\PHPUnit\Framework\MockObject\MockObject $calendarStatusService */
private $calendarStatusService;
/** @var UserStatusController */
private $controller;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); 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 * @dataProvider setStatusDataProvider
*/ */
public function testSetStatus(string $statusType, public function testSetStatus(
string $statusType,
?string $statusIcon, ?string $statusIcon,
?string $message, ?string $message,
?int $clearAt, ?int $clearAt,
@ -114,7 +99,8 @@ class UserStatusControllerTest extends TestCase {
bool $expectException, bool $expectException,
?Throwable $exception, ?Throwable $exception,
bool $expectLogger, bool $expectLogger,
?string $expectedLogMessage): void { ?string $expectedLogMessage,
): void {
$userStatus = $this->getUserStatus(); $userStatus = $this->getUserStatus();
if ($expectException) { if ($expectException) {
@ -155,7 +141,7 @@ class UserStatusControllerTest extends TestCase {
} }
} }
public function setStatusDataProvider(): array { public static function setStatusDataProvider(): array {
return [ return [
['busy', '👨🏽💻', 'Busy developing the status feature', 500, true, false, null, false, null], ['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, ['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 * @dataProvider setPredefinedMessageDataProvider
*/ */
public function testSetPredefinedMessage(string $messageId, public function testSetPredefinedMessage(
string $messageId,
?int $clearAt, ?int $clearAt,
bool $expectSuccess, bool $expectSuccess,
bool $expectException, bool $expectException,
?Throwable $exception, ?Throwable $exception,
bool $expectLogger, bool $expectLogger,
?string $expectedLogMessage): void { ?string $expectedLogMessage,
): void {
$userStatus = $this->getUserStatus(); $userStatus = $this->getUserStatus();
if ($expectException) { if ($expectException) {
@ -221,7 +201,7 @@ class UserStatusControllerTest extends TestCase {
} }
} }
public function setPredefinedMessageDataProvider(): array { public static function setPredefinedMessageDataProvider(): array {
return [ return [
['messageId-42', 500, true, false, null, false, null], ['messageId-42', 500, true, false, null, false, null],
['messageId-42', 500, false, true, new InvalidClearAtException('Original exception message'), true, ['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 * @dataProvider setCustomMessageDataProvider
*/ */
public function testSetCustomMessage(?string $statusIcon, public function testSetCustomMessage(
?string $statusIcon,
string $message, string $message,
?int $clearAt, ?int $clearAt,
bool $expectSuccess, bool $expectSuccess,
@ -252,7 +223,8 @@ class UserStatusControllerTest extends TestCase {
?Throwable $exception, ?Throwable $exception,
bool $expectLogger, bool $expectLogger,
?string $expectedLogMessage, ?string $expectedLogMessage,
bool $expectSuccessAsReset = false): void { bool $expectSuccessAsReset = false,
): void {
$userStatus = $this->getUserStatus(); $userStatus = $this->getUserStatus();
if ($expectException) { if ($expectException) {
@ -308,7 +280,7 @@ class UserStatusControllerTest extends TestCase {
} }
} }
public function setCustomMessageDataProvider(): array { public static function setCustomMessageDataProvider(): array {
return [ return [
['👨🏽💻', 'Busy developing the status feature', 500, true, false, null, false, null], ['👨🏽💻', 'Busy developing the status feature', 500, true, false, null, false, null],
['👨🏽💻', '', 500, true, false, null, false, null, false], ['👨🏽💻', '', 500, true, false, null, false, null, false],

@ -16,33 +16,18 @@ use OCP\IL10N;
use OCP\IURLGenerator; use OCP\IURLGenerator;
use OCP\IUserManager; use OCP\IUserManager;
use OCP\IUserSession; use OCP\IUserSession;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class UserStatusWidgetTest extends TestCase { class UserStatusWidgetTest extends TestCase {
private IL10N&MockObject $l10n;
/** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ private IDateTimeFormatter&MockObject $dateTimeFormatter;
private $l10n; private IURLGenerator&MockObject $urlGenerator;
private IInitialState&MockObject $initialState;
/** @var IDateTimeFormatter|\PHPUnit\Framework\MockObject\MockObject */ private IUserManager&MockObject $userManager;
private $dateTimeFormatter; private IUserSession&MockObject $userSession;
private StatusService&MockObject $service;
/** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ private UserStatusWidget $widget;
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;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -15,9 +15,7 @@ use OCP\DB\Exception;
use Test\TestCase; use Test\TestCase;
class UserStatusMapperTest extends TestCase { class UserStatusMapperTest extends TestCase {
private UserStatusMapper $mapper;
/** @var UserStatusMapper */
private $mapper;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -137,11 +135,6 @@ class UserStatusMapperTest extends TestCase {
} }
/** /**
* @param string $status
* @param bool $isUserDefined
* @param int $timestamp
* @param bool $expectsClean
*
* @dataProvider clearStatusesOlderThanDataProvider * @dataProvider clearStatusesOlderThanDataProvider
*/ */
public function testClearStatusesOlderThan(string $status, bool $isUserDefined, int $timestamp, bool $expectsClean): void { 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 [ return [
['offline', false, 6000, false], ['offline', false, 6000, false],
['online', true, 6000, false], ['online', true, 6000, false],
@ -231,7 +224,7 @@ class UserStatusMapperTest extends TestCase {
$this->mapper->insert($userStatus3); $this->mapper->insert($userStatus3);
} }
public function dataCreateBackupStatus(): array { public static function dataCreateBackupStatus(): array {
return [ return [
[false, false, false], [false, false, false],
[true, false, true], [true, false, true],
@ -242,9 +235,6 @@ class UserStatusMapperTest extends TestCase {
/** /**
* @dataProvider dataCreateBackupStatus * @dataProvider dataCreateBackupStatus
* @param bool $hasStatus
* @param bool $hasBackup
* @param bool $backupCreated
*/ */
public function testCreateBackupStatus(bool $hasStatus, bool $hasBackup, bool $backupCreated): void { public function testCreateBackupStatus(bool $hasStatus, bool $hasBackup, bool $backupCreated): void {
if ($hasStatus) { if ($hasStatus) {

@ -13,15 +13,12 @@ use OCA\UserStatus\Service\StatusService;
use OCP\EventDispatcher\GenericEvent; use OCP\EventDispatcher\GenericEvent;
use OCP\IUser; use OCP\IUser;
use OCP\User\Events\UserDeletedEvent; use OCP\User\Events\UserDeletedEvent;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class UserDeletedListenerTest extends TestCase { class UserDeletedListenerTest extends TestCase {
private StatusService&MockObject $service;
/** @var StatusService|\PHPUnit\Framework\MockObject\MockObject */ private UserDeletedListener $listener;
private $service;
/** @var UserDeletedListener */
private $listener;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();

@ -11,7 +11,6 @@ namespace OCA\UserStatus\Tests\Listener;
use OCA\DAV\CalDAV\Status\StatusService as CalendarStatusService; use OCA\DAV\CalDAV\Status\StatusService as CalendarStatusService;
use OCA\UserStatus\Db\UserStatus; use OCA\UserStatus\Db\UserStatus;
use OCA\UserStatus\Db\UserStatusMapper; use OCA\UserStatus\Db\UserStatusMapper;
use OCA\UserStatus\Listener\UserDeletedListener;
use OCA\UserStatus\Listener\UserLiveStatusListener; use OCA\UserStatus\Listener\UserLiveStatusListener;
use OCA\UserStatus\Service\StatusService; use OCA\UserStatus\Service\StatusService;
use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\DoesNotExistException;
@ -24,20 +23,13 @@ use Psr\Log\LoggerInterface;
use Test\TestCase; use Test\TestCase;
class UserLiveStatusListenerTest extends 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 LoggerInterface&MockObject $logger;
private $mapper; private UserLiveStatusListener $listener;
/** @var StatusService|MockObject */
private $statusService;
/** @var ITimeFactory|MockObject */
private $timeFactory;
/** @var UserDeletedListener */
private $listener;
private CalendarStatusService|MockObject $calendarStatusService;
private LoggerInterface|MockObject $logger;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); 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 * @dataProvider handleEventWithCorrectEventDataProvider
*/ */
public function testHandleWithCorrectEvent(string $userId, public function testHandleWithCorrectEvent(
string $userId,
string $previousStatus, string $previousStatus,
int $previousTimestamp, int $previousTimestamp,
bool $previousIsUserDefined, bool $previousIsUserDefined,
string $eventStatus, string $eventStatus,
int $eventTimestamp, int $eventTimestamp,
bool $expectExisting, bool $expectExisting,
bool $expectUpdate): void { bool $expectUpdate,
): void {
$userStatus = new UserStatus(); $userStatus = new UserStatus();
if ($expectExisting) { if ($expectExisting) {
@ -143,7 +128,7 @@ class UserLiveStatusListenerTest extends TestCase {
} }
} }
public function handleEventWithCorrectEventDataProvider(): array { public static function handleEventWithCorrectEventDataProvider(): array {
return [ return [
['john.doe', 'offline', 0, false, 'online', 5000, true, true], ['john.doe', 'offline', 0, false, 'online', 5000, true, true],
['john.doe', 'offline', 0, false, 'online', 5000, false, true], ['john.doe', 'offline', 0, false, 'online', 5000, false, true],

@ -10,15 +10,12 @@ namespace OCA\UserStatus\Tests\Service;
use OCA\UserStatus\Service\PredefinedStatusService; use OCA\UserStatus\Service\PredefinedStatusService;
use OCP\IL10N; use OCP\IL10N;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class PredefinedStatusServiceTest extends TestCase { class PredefinedStatusServiceTest extends TestCase {
protected IL10N&MockObject $l10n;
/** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ protected PredefinedStatusService $service;
protected $l10n;
/** @var PredefinedStatusService */
protected $service;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
@ -97,9 +94,6 @@ class PredefinedStatusServiceTest extends TestCase {
} }
/** /**
* @param string $id
* @param string|null $expectedIcon
*
* @dataProvider getIconForIdDataProvider * @dataProvider getIconForIdDataProvider
*/ */
public function testGetIconForId(string $id, ?string $expectedIcon): void { public function testGetIconForId(string $id, ?string $expectedIcon): void {
@ -107,10 +101,7 @@ class PredefinedStatusServiceTest extends TestCase {
$this->assertEquals($expectedIcon, $actual); $this->assertEquals($expectedIcon, $actual);
} }
/** public static function getIconForIdDataProvider(): array {
* @return array
*/
public function getIconForIdDataProvider(): array {
return [ return [
['meeting', '📅'], ['meeting', '📅'],
['commuting', '🚌'], ['commuting', '🚌'],
@ -123,9 +114,6 @@ class PredefinedStatusServiceTest extends TestCase {
} }
/** /**
* @param string $id
* @param string|null $expected
*
* @dataProvider getTranslatedStatusForIdDataProvider * @dataProvider getTranslatedStatusForIdDataProvider
*/ */
public function testGetTranslatedStatusForId(string $id, ?string $expected): void { public function testGetTranslatedStatusForId(string $id, ?string $expected): void {
@ -136,10 +124,7 @@ class PredefinedStatusServiceTest extends TestCase {
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
/** public static function getTranslatedStatusForIdDataProvider(): array {
* @return array
*/
public function getTranslatedStatusForIdDataProvider(): array {
return [ return [
['meeting', 'In a meeting'], ['meeting', 'In a meeting'],
['commuting', 'Commuting'], ['commuting', 'Commuting'],
@ -152,9 +137,6 @@ class PredefinedStatusServiceTest extends TestCase {
} }
/** /**
* @param string $id
* @param bool $expected
*
* @dataProvider isValidIdDataProvider * @dataProvider isValidIdDataProvider
*/ */
public function testIsValidId(string $id, bool $expected): void { public function testIsValidId(string $id, bool $expected): void {
@ -162,10 +144,7 @@ class PredefinedStatusServiceTest extends TestCase {
$this->assertEquals($expected, $actual); $this->assertEquals($expected, $actual);
} }
/** public static function isValidIdDataProvider(): array {
* @return array
*/
public function isValidIdDataProvider(): array {
return [ return [
['meeting', true], ['meeting', true],
['commuting', true], ['commuting', true],

@ -31,27 +31,13 @@ use Psr\Log\LoggerInterface;
use Test\TestCase; use Test\TestCase;
class StatusServiceTest extends TestCase { class StatusServiceTest extends TestCase {
private UserStatusMapper&MockObject $mapper;
/** @var UserStatusMapper|MockObject */ private ITimeFactory&MockObject $timeFactory;
private $mapper; private PredefinedStatusService&MockObject $predefinedStatusService;
private IEmojiHelper&MockObject $emojiHelper;
/** @var ITimeFactory|MockObject */ private IConfig&MockObject $config;
private $timeFactory; private IUserManager&MockObject $userManager;
private LoggerInterface&MockObject $logger;
/** @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 StatusService $service; 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 * @dataProvider setStatusDataProvider
*/ */
public function testSetStatus(string $userId, public function testSetStatus(
string $userId,
string $status, string $status,
?int $statusTimestamp, ?int $statusTimestamp,
bool $isUserDefined, bool $isUserDefined,
@ -258,7 +234,8 @@ class StatusServiceTest extends TestCase {
bool $expectTimeFactory, bool $expectTimeFactory,
bool $expectException, bool $expectException,
?string $expectedExceptionClass, ?string $expectedExceptionClass,
?string $expectedExceptionMessage): void { ?string $expectedExceptionMessage,
): void {
$userStatus = new UserStatus(); $userStatus = new UserStatus();
if ($expectExisting) { if ($expectExisting) {
@ -309,7 +286,7 @@ class StatusServiceTest extends TestCase {
} }
} }
public function setStatusDataProvider(): array { public static function setStatusDataProvider(): array {
return [ return [
['john.doe', 'online', 50, true, true, true, false, false, null, null], ['john.doe', 'online', 50, true, true, true, false, false, null, null],
['john.doe', 'online', 50, true, false, 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 * @dataProvider setPredefinedMessageDataProvider
*/ */
public function testSetPredefinedMessage(string $userId, public function testSetPredefinedMessage(
string $userId,
string $messageId, string $messageId,
bool $isValidMessageId, bool $isValidMessageId,
?int $clearAt, ?int $clearAt,
@ -388,7 +356,8 @@ class StatusServiceTest extends TestCase {
bool $expectSuccess, bool $expectSuccess,
bool $expectException, bool $expectException,
?string $expectedExceptionClass, ?string $expectedExceptionClass,
?string $expectedExceptionMessage): void { ?string $expectedExceptionMessage,
): void {
$userStatus = new UserStatus(); $userStatus = new UserStatus();
if ($expectExisting) { if ($expectExisting) {
@ -451,7 +420,7 @@ class StatusServiceTest extends TestCase {
} }
} }
public function setPredefinedMessageDataProvider(): array { public static function setPredefinedMessageDataProvider(): array {
return [ return [
['john.doe', 'sick-leave', true, null, true, true, false, null, null], ['john.doe', 'sick-leave', true, null, true, true, false, null, null],
['john.doe', 'sick-leave', true, null, false, 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 * @dataProvider setCustomMessageDataProvider
*/ */
public function testSetCustomMessage(string $userId, public function testSetCustomMessage(
string $userId,
?string $statusIcon, ?string $statusIcon,
bool $supportsEmoji, bool $supportsEmoji,
string $message, string $message,
@ -487,7 +446,8 @@ class StatusServiceTest extends TestCase {
bool $expectSuccess, bool $expectSuccess,
bool $expectException, bool $expectException,
?string $expectedExceptionClass, ?string $expectedExceptionClass,
?string $expectedExceptionMessage): void { ?string $expectedExceptionMessage,
): void {
$userStatus = new UserStatus(); $userStatus = new UserStatus();
if ($expectExisting) { if ($expectExisting) {
@ -548,7 +508,7 @@ class StatusServiceTest extends TestCase {
} }
} }
public function setCustomMessageDataProvider(): array { public static function setCustomMessageDataProvider(): array {
return [ return [
['john.doe', '😁', true, 'Custom message', null, true, true, false, null, null], ['john.doe', '😁', true, 'Custom message', null, true, true, false, null, null],
['john.doe', '😁', true, 'Custom message', null, false, 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'); $this->service->revertMultipleUserStatus(['john', 'nobackup', 'backuponly', 'nobackupanddnd'], 'call');
} }
public function dataSetUserStatus(): array { public static function dataSetUserStatus(): array {
return [ return [
[IUserStatus::MESSAGE_CALENDAR_BUSY, '', false], [IUserStatus::MESSAGE_CALENDAR_BUSY, '', false],

@ -44,7 +44,7 @@ class WebhookListenerMapperTest extends TestCase {
parent::tearDown(); parent::tearDown();
} }
protected function pruneTables() { protected function pruneTables(): void {
$query = $this->connection->getQueryBuilder(); $query = $this->connection->getQueryBuilder();
$query->delete(WebhookListenerMapper::TABLE_NAME)->executeStatement(); $query->delete(WebhookListenerMapper::TABLE_NAME)->executeStatement();
} }

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later * SPDX-License-Identifier: AGPL-3.0-or-later
@ -7,9 +10,10 @@ namespace OCA\WorkflowEngine\Tests\Check;
use OCA\WorkflowEngine\Check\AbstractStringCheck; use OCA\WorkflowEngine\Check\AbstractStringCheck;
use OCP\IL10N; use OCP\IL10N;
use PHPUnit\Framework\MockObject\MockObject;
class AbstractStringCheckTest extends \Test\TestCase { class AbstractStringCheckTest extends \Test\TestCase {
protected function getCheckMock() { protected function getCheckMock(): AbstractStringCheck|MockObject {
$l = $this->getMockBuilder(IL10N::class) $l = $this->getMockBuilder(IL10N::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->getMock(); ->getMock();
@ -19,7 +23,7 @@ class AbstractStringCheckTest extends \Test\TestCase {
return sprintf($string, $args); return sprintf($string, $args);
}); });
$check = $this->getMockBuilder('OCA\WorkflowEngine\Check\AbstractStringCheck') $check = $this->getMockBuilder(AbstractStringCheck::class)
->setConstructorArgs([ ->setConstructorArgs([
$l, $l,
]) ])
@ -32,7 +36,7 @@ class AbstractStringCheckTest extends \Test\TestCase {
return $check; return $check;
} }
public function dataExecuteStringCheck() { public static function dataExecuteStringCheck(): array {
return [ return [
['is', 'same', 'same', true], ['is', 'same', 'same', true],
['is', 'different', 'not the same', false], ['is', 'different', 'not the same', false],
@ -48,19 +52,15 @@ class AbstractStringCheckTest extends \Test\TestCase {
/** /**
* @dataProvider dataExecuteStringCheck * @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(); $check = $this->getCheckMock();
/** @var AbstractStringCheck $check */ /** @var AbstractStringCheck $check */
$this->assertEquals($expected, $this->invokePrivate($check, 'executeStringCheck', [$operation, $checkValue, $actualValue])); $this->assertEquals($expected, $this->invokePrivate($check, 'executeStringCheck', [$operation, $checkValue, $actualValue]));
} }
public function dataValidateCheck() { public static function dataValidateCheck(): array {
return [ return [
['is', '/Invalid(Regex/'], ['is', '/Invalid(Regex/'],
['!is', '/Invalid(Regex/'], ['!is', '/Invalid(Regex/'],
@ -71,10 +71,8 @@ class AbstractStringCheckTest extends \Test\TestCase {
/** /**
* @dataProvider dataValidateCheck * @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(); $check = $this->getCheckMock();
/** @var AbstractStringCheck $check */ /** @var AbstractStringCheck $check */
@ -83,7 +81,7 @@ class AbstractStringCheckTest extends \Test\TestCase {
$this->addToAssertionCount(1); $this->addToAssertionCount(1);
} }
public function dataValidateCheckInvalid() { public static function dataValidateCheckInvalid(): array {
return [ return [
['!!is', '', 1, 'The given operator is invalid'], ['!!is', '', 1, 'The given operator is invalid'],
['less', '', 1, 'The given operator is invalid'], ['less', '', 1, 'The given operator is invalid'],
@ -94,12 +92,8 @@ class AbstractStringCheckTest extends \Test\TestCase {
/** /**
* @dataProvider dataValidateCheckInvalid * @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(); $check = $this->getCheckMock();
try { try {
@ -111,7 +105,7 @@ class AbstractStringCheckTest extends \Test\TestCase {
} }
} }
public function dataMatch() { public static function dataMatch(): array {
return [ return [
['/valid/', 'valid', [], true], ['/valid/', 'valid', [], true],
['/valid/', 'valid', [md5('/valid/') => [md5('valid') => false]], false], // Cache hit ['/valid/', 'valid', [md5('/valid/') => [md5('valid') => false]], false], // Cache hit
@ -120,12 +114,8 @@ class AbstractStringCheckTest extends \Test\TestCase {
/** /**
* @dataProvider dataMatch * @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(); $check = $this->getCheckMock();
$this->invokePrivate($check, 'matches', [$matches]); $this->invokePrivate($check, 'matches', [$matches]);

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later * SPDX-License-Identifier: AGPL-3.0-or-later
@ -8,19 +11,14 @@ namespace OCA\WorkflowEngine\Tests\Check;
use OCA\WorkflowEngine\Check\RequestRemoteAddress; use OCA\WorkflowEngine\Check\RequestRemoteAddress;
use OCP\IL10N; use OCP\IL10N;
use OCP\IRequest; use OCP\IRequest;
use PHPUnit\Framework\MockObject\MockObject;
class RequestRemoteAddressTest extends \Test\TestCase { class RequestRemoteAddressTest extends \Test\TestCase {
/** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ protected IRequest&MockObject $request;
protected $request;
/** protected function getL10NMock(): IL10N&MockObject {
* @return IL10N|\PHPUnit\Framework\MockObject\MockObject $l = $this->createMock(IL10N::class);
*/
protected function getL10NMock() {
$l = $this->getMockBuilder(IL10N::class)
->disableOriginalConstructor()
->getMock();
$l->expects($this->any()) $l->expects($this->any())
->method('t') ->method('t')
->willReturnCallback(function ($string, $args) { ->willReturnCallback(function ($string, $args) {
@ -32,11 +30,10 @@ class RequestRemoteAddressTest extends \Test\TestCase {
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
$this->request = $this->getMockBuilder(IRequest::class) $this->request = $this->createMock(IRequest::class);
->getMock();
} }
public function dataExecuteCheckIPv4() { public static function dataExecuteCheckIPv4(): array {
return [ return [
['127.0.0.1/32', '127.0.0.1', true], ['127.0.0.1/32', '127.0.0.1', true],
['127.0.0.1/32', '127.0.0.0', false], ['127.0.0.1/32', '127.0.0.0', false],
@ -49,11 +46,8 @@ class RequestRemoteAddressTest extends \Test\TestCase {
/** /**
* @dataProvider dataExecuteCheckIPv4 * @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); $check = new RequestRemoteAddress($this->getL10NMock(), $this->request);
$this->request->expects($this->once()) $this->request->expects($this->once())
@ -65,11 +59,8 @@ class RequestRemoteAddressTest extends \Test\TestCase {
/** /**
* @dataProvider dataExecuteCheckIPv4 * @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); $check = new RequestRemoteAddress($this->getL10NMock(), $this->request);
$this->request->expects($this->once()) $this->request->expects($this->once())
@ -79,7 +70,7 @@ class RequestRemoteAddressTest extends \Test\TestCase {
$this->assertEquals(!$expected, $check->executeCheck('!matchesIPv4', $value)); $this->assertEquals(!$expected, $check->executeCheck('!matchesIPv4', $value));
} }
public function dataExecuteCheckIPv6() { public static function dataExecuteCheckIPv6(): array {
return [ return [
['::1/128', '::1', true], ['::1/128', '::1', true],
['::2/128', '::3', false], ['::2/128', '::3', false],
@ -93,11 +84,8 @@ class RequestRemoteAddressTest extends \Test\TestCase {
/** /**
* @dataProvider dataExecuteCheckIPv6 * @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); $check = new RequestRemoteAddress($this->getL10NMock(), $this->request);
$this->request->expects($this->once()) $this->request->expects($this->once())
@ -109,11 +97,8 @@ class RequestRemoteAddressTest extends \Test\TestCase {
/** /**
* @dataProvider dataExecuteCheckIPv6 * @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); $check = new RequestRemoteAddress($this->getL10NMock(), $this->request);
$this->request->expects($this->once()) $this->request->expects($this->once())

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later * SPDX-License-Identifier: AGPL-3.0-or-later
@ -8,19 +11,13 @@ namespace OCA\WorkflowEngine\Tests\Check;
use OCA\WorkflowEngine\Check\RequestTime; use OCA\WorkflowEngine\Check\RequestTime;
use OCP\AppFramework\Utility\ITimeFactory; use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IL10N; use OCP\IL10N;
use PHPUnit\Framework\MockObject\MockObject;
class RequestTimeTest extends \Test\TestCase { class RequestTimeTest extends \Test\TestCase {
protected ITimeFactory&MockObject $timeFactory;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ protected function getL10NMock(): IL10N&MockObject {
protected $timeFactory; $l = $this->createMock(IL10N::class);
/**
* @return IL10N|\PHPUnit\Framework\MockObject\MockObject
*/
protected function getL10NMock() {
$l = $this->getMockBuilder(IL10N::class)
->disableOriginalConstructor()
->getMock();
$l->expects($this->any()) $l->expects($this->any())
->method('t') ->method('t')
->willReturnCallback(function ($string, $args) { ->willReturnCallback(function ($string, $args) {
@ -32,11 +29,10 @@ class RequestTimeTest extends \Test\TestCase {
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
$this->timeFactory = $this->getMockBuilder('OCP\AppFramework\Utility\ITimeFactory') $this->timeFactory = $this->createMock(ITimeFactory::class);
->getMock();
} }
public function dataExecuteCheck() { public static function dataExecuteCheck(): array {
return [ 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']), 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 [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 * @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); $check = new RequestTime($this->getL10NMock(), $this->timeFactory);
$this->timeFactory->expects($this->once()) $this->timeFactory->expects($this->once())
@ -85,11 +78,8 @@ class RequestTimeTest extends \Test\TestCase {
/** /**
* @dataProvider dataExecuteCheck * @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); $check = new RequestTime($this->getL10NMock(), $this->timeFactory);
$this->timeFactory->expects($this->once()) $this->timeFactory->expects($this->once())
@ -99,7 +89,7 @@ class RequestTimeTest extends \Test\TestCase {
$this->assertEquals(!$expected, $check->executeCheck('!in', $value)); $this->assertEquals(!$expected, $check->executeCheck('!in', $value));
} }
public function dataValidateCheck() { public static function dataValidateCheck(): array {
return [ return [
['in', '["08:00 Europe/Berlin","17:00 Europe/Berlin"]'], ['in', '["08:00 Europe/Berlin","17:00 Europe/Berlin"]'],
['!in', '["08:00 Europe/Berlin","17:00 America/North_Dakota/Beulah"]'], ['!in', '["08:00 Europe/Berlin","17:00 America/North_Dakota/Beulah"]'],
@ -109,16 +99,14 @@ class RequestTimeTest extends \Test\TestCase {
/** /**
* @dataProvider dataValidateCheck * @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 = new RequestTime($this->getL10NMock(), $this->timeFactory);
$check->validateCheck($operator, $value); $check->validateCheck($operator, $value);
$this->addToAssertionCount(1); $this->addToAssertionCount(1);
} }
public function dataValidateCheckInvalid() { public static function dataValidateCheckInvalid(): array {
return [ return [
['!!in', '["08:00 Europe/Berlin","17:00 Europe/Berlin"]', 1, 'The given operator is invalid'], ['!!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'], ['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 * @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); $check = new RequestTime($this->getL10NMock(), $this->timeFactory);
try { try {

@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
/** /**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors * SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later * SPDX-License-Identifier: AGPL-3.0-or-later
@ -9,24 +12,19 @@ use OCA\WorkflowEngine\Check\AbstractStringCheck;
use OCA\WorkflowEngine\Check\RequestUserAgent; use OCA\WorkflowEngine\Check\RequestUserAgent;
use OCP\IL10N; use OCP\IL10N;
use OCP\IRequest; use OCP\IRequest;
use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
class RequestUserAgentTest extends TestCase { class RequestUserAgentTest extends TestCase {
protected IRequest&MockObject $request;
/** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ protected RequestUserAgent $check;
protected $request;
/** @var RequestUserAgent */
protected $check;
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
$this->request = $this->createMock(IRequest::class); $this->request = $this->createMock(IRequest::class);
/** @var IL10N|\PHPUnit\Framework\MockObject\MockObject $l */ /** @var IL10N&MockObject $l */
$l = $this->getMockBuilder(IL10N::class) $l = $this->createMock(IL10N::class);
->disableOriginalConstructor()
->getMock();
$l->expects($this->any()) $l->expects($this->any())
->method('t') ->method('t')
->willReturnCallback(function ($string, $args) { ->willReturnCallback(function ($string, $args) {
@ -36,7 +34,7 @@ class RequestUserAgentTest extends TestCase {
$this->check = new RequestUserAgent($l, $this->request); $this->check = new RequestUserAgent($l, $this->request);
} }
public function dataExecuteCheck() { public static function dataExecuteCheck(): array {
return [ return [
['is', 'android', 'Mozilla/5.0 (Android) Nextcloud-android/2.2.0', true], ['is', 'android', 'Mozilla/5.0 (Android) Nextcloud-android/2.2.0', true],
['is', 'android', 'Mozilla/5.0 (iOS) Nextcloud-iOS/2.2.0', false], ['is', 'android', 'Mozilla/5.0 (iOS) Nextcloud-iOS/2.2.0', false],
@ -86,12 +84,8 @@ class RequestUserAgentTest extends TestCase {
/** /**
* @dataProvider dataExecuteCheck * @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()) $this->request->expects($this->once())
->method('getHeader') ->method('getHeader')
->willReturn($actualValue); ->willReturn($actualValue);

@ -110,6 +110,7 @@ class Registry implements IRegistry {
\OC::$server->get(LoggerInterface::class)->critical('Could not load lazy crash reporter: ' . $e->getMessage(), [ \OC::$server->get(LoggerInterface::class)->critical('Could not load lazy crash reporter: ' . $e->getMessage(), [
'exception' => $e, 'exception' => $e,
]); ]);
return;
} }
/** /**
* Try to register the loaded reporter. Theoretically it could be of a wrong * Try to register the loaded reporter. Theoretically it could be of a wrong

@ -499,7 +499,7 @@ class AccountManagerTest extends TestCase {
$this->invokePrivate($accountManager, 'updateUser', [$user, $newData, $oldData]); $this->invokePrivate($accountManager, 'updateUser', [$user, $newData, $oldData]);
} }
public function dataTrueFalse(): array { public static function dataTrueFalse(): array {
return [ return [
#$newData | $oldData | $insertNew | $updateExisting #$newData | $oldData | $insertNew | $updateExisting
[['myProperty' => ['value' => 'newData']], ['myProperty' => ['value' => 'oldData']], false, true], [['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 [ return [
[ #0 Search for an existing name [ #0 Search for an existing name
IAccountManager::PROPERTY_DISPLAYNAME, IAccountManager::PROPERTY_DISPLAYNAME,
@ -948,21 +948,22 @@ class AccountManagerTest extends TestCase {
]; ];
} }
public function dataCheckEmailVerification(): array { public static function dataCheckEmailVerification(): array {
return [ return [
[$this->makeUser('steve', 'Steve Smith', 'steve@steve.steve'), null], [['steve', 'Steve Smith', 'steve@steve.steve'], null],
[$this->makeUser('emma', 'Emma Morales', 'emma@emma.com'), 'emma@morales.com'], [['emma', 'Emma Morales', 'emma@emma.com'], 'emma@morales.com'],
[$this->makeUser('sarah@web.org', 'Sarah Foster', 'sarah@web.org'), null], [['sarah@web.org', 'Sarah Foster', 'sarah@web.org'], null],
[$this->makeUser('cole@web.org', 'Cole Harrison', 'cole@web.org'), 'cole@example.com'], [['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'], [['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'), ''], [['11da2744-3f4d-4c17-8c13-4c057a379237', 'James Loranger', 'james@example.com'], ''],
]; ];
} }
/** /**
* @dataProvider dataCheckEmailVerification * @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 // Once because of getAccount, once because of getUser
$this->config->expects($this->exactly(2))->method('getSystemValue')->with('account_manager.default_property_scope', [])->willReturn([]); $this->config->expects($this->exactly(2))->method('getSystemValue')->with('account_manager.default_property_scope', [])->willReturn([]);
$account = $this->accountManager->getAccount($user); $account = $this->accountManager->getAccount($user);
@ -988,7 +989,7 @@ class AccountManagerTest extends TestCase {
$this->invokePrivate($this->accountManager, 'checkEmailVerification', [$account, $oldData]); $this->invokePrivate($this->accountManager, 'checkEmailVerification', [$account, $oldData]);
} }
public function dataSetDefaultPropertyScopes(): array { public static function dataSetDefaultPropertyScopes(): array {
return [ return [
[ [
[], [],

@ -56,7 +56,7 @@ class AccountPropertyTest extends TestCase {
$this->assertEquals(IAccountManager::SCOPE_LOCAL, $actualReturn->getScope()); $this->assertEquals(IAccountManager::SCOPE_LOCAL, $actualReturn->getScope());
} }
public function scopesProvider() { public static function scopesProvider(): array {
return [ return [
// current values // current values
[IAccountManager::SCOPE_PRIVATE, IAccountManager::SCOPE_PRIVATE], [IAccountManager::SCOPE_PRIVATE, IAccountManager::SCOPE_PRIVATE],

@ -96,14 +96,14 @@ class HooksTest extends TestCase {
} }
} }
$params['user'] = $this->createMock(IUser::class);
$this->hooks->changeUserHook($params['user'], $params['feature'], $params['value']); $this->hooks->changeUserHook($params['user'], $params['feature'], $params['value']);
} }
public function dataTestChangeUserHook() { public static function dataTestChangeUserHook(): array {
$user = $this->createMock(IUser::class);
return [ return [
[ [
['user' => $user, 'feature' => '', 'value' => ''], ['feature' => '', 'value' => ''],
[ [
IAccountManager::PROPERTY_EMAIL => ['value' => ''], IAccountManager::PROPERTY_EMAIL => ['value' => ''],
IAccountManager::PROPERTY_DISPLAYNAME => ['value' => ''] IAccountManager::PROPERTY_DISPLAYNAME => ['value' => '']
@ -111,7 +111,7 @@ class HooksTest extends TestCase {
false, false, true false, false, true
], ],
[ [
['user' => $user, 'feature' => 'foo', 'value' => 'bar'], ['feature' => 'foo', 'value' => 'bar'],
[ [
IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'], IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'],
IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName'] IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName']
@ -119,7 +119,7 @@ class HooksTest extends TestCase {
false, false, false 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_EMAIL => ['value' => 'oldMail@example.com'],
IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName'] IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName']
@ -127,7 +127,7 @@ class HooksTest extends TestCase {
true, false, false true, false, false
], ],
[ [
['user' => $user, 'feature' => 'displayName', 'value' => 'newDisplayName'], ['feature' => 'displayName', 'value' => 'newDisplayName'],
[ [
IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'], IAccountManager::PROPERTY_EMAIL => ['value' => 'oldMail@example.com'],
IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName'] IAccountManager::PROPERTY_DISPLAYNAME => ['value' => 'oldDisplayName']

@ -74,7 +74,7 @@ class ManagerTest extends TestCase {
self::invokePrivate($this->activityManager, 'getConsumers'); self::invokePrivate($this->activityManager, 'getConsumers');
} }
public function getUserFromTokenThrowInvalidTokenData() { public static function getUserFromTokenThrowInvalidTokenData(): array {
return [ return [
[null, []], [null, []],
['', []], ['', []],
@ -98,7 +98,7 @@ class ManagerTest extends TestCase {
self::invokePrivate($this->activityManager, 'getUserFromToken'); self::invokePrivate($this->activityManager, 'getUserFromToken');
} }
public function getUserFromTokenData() { public static function getUserFromTokenData(): array {
return [ return [
[null, '123456789012345678901234567890', 'user1'], [null, '123456789012345678901234567890', 'user1'],
['user2', null, 'user2'], ['user2', null, 'user2'],
@ -190,7 +190,7 @@ class ManagerTest extends TestCase {
$this->activityManager->publish($event); $this->activityManager->publish($event);
} }
public function dataPublish() { public static function dataPublish(): array {
return [ return [
[null, ''], [null, ''],
['test_author', 'test_author'], ['test_author', 'test_author'],

@ -125,7 +125,7 @@ class AllConfigTest extends \Test\TestCase {
$config->deleteUserValue('userPreCond', 'appPreCond', 'keyPreCond'); $config->deleteUserValue('userPreCond', 'appPreCond', 'keyPreCond');
} }
public function dataSetUserValueUnexpectedValue() { public static function dataSetUserValueUnexpectedValue(): array {
return [ return [
[true], [true],
[false], [false],

@ -301,7 +301,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no')); $this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no'));
} }
public function dataEnableAppForGroupsAllowedTypes() { public static function dataEnableAppForGroupsAllowedTypes(): array {
return [ return [
[[]], [[]],
[[ [[
@ -361,7 +361,7 @@ class AppManagerTest extends TestCase {
$this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no')); $this->assertEquals('["group1","group2"]', $this->appConfig->getValue('test', 'enabled', 'no'));
} }
public function dataEnableAppForGroupsForbiddenTypes() { public static function dataEnableAppForGroupsForbiddenTypes(): array {
return [ return [
['filesystem'], ['filesystem'],
['prelogin'], ['prelogin'],

@ -104,7 +104,7 @@ class AppDiscoverFetcherTest extends FetcherBase {
} }
} }
public function dataGetETag(): array { public static function dataGetETag(): array {
return [ return [
'file not found' => [null, true], 'file not found' => [null, true],
'empty file' => [null, false, ''], 'empty file' => [null, false, ''],

@ -1840,7 +1840,7 @@ EJL3BaQAQaASSsvFrcozYxrQG4VzEg==
$this->registry = $this->createMock(IRegistry::class); $this->registry = $this->createMock(IRegistry::class);
$this->fetcher = $this->getMockBuilder(AppFetcher::class) $this->fetcher = $this->getMockBuilder(AppFetcher::class)
->setMethods(['getChannel']) ->onlyMethods(['getChannel'])
->setConstructorArgs([ ->setConstructorArgs([
$factory, $factory,
$this->clientService, $this->clientService,

@ -22,7 +22,7 @@ class VersionParserTest extends TestCase {
/** /**
* @return array * @return array
*/ */
public function versionProvider() { public static function versionProvider(): array {
return [ return [
[ [
'*', '*',
@ -66,7 +66,7 @@ class VersionParserTest extends TestCase {
$this->assertEquals($expected, $this->versionParser->getVersion($input)); $this->assertEquals($expected, $this->versionParser->getVersion($input));
} }
public function testGetVersionException(): void { public function testGetVersionException(): void {
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
$this->expectExceptionMessage('Version cannot be parsed: BogusVersion'); $this->expectExceptionMessage('Version cannot be parsed: BogusVersion');
@ -74,7 +74,7 @@ class VersionParserTest extends TestCase {
$this->versionParser->getVersion('BogusVersion'); $this->versionParser->getVersion('BogusVersion');
} }
public function testGetVersionExceptionWithMultiple(): void { public function testGetVersionExceptionWithMultiple(): void {
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
$this->expectExceptionMessage('Version cannot be parsed: >=8.2 <=9.1a'); $this->expectExceptionMessage('Version cannot be parsed: >=8.2 <=9.1a');

@ -23,7 +23,7 @@ class CompareVersionTest extends TestCase {
$this->compare = new CompareVersion(); $this->compare = new CompareVersion();
} }
public function comparisonData() { public static function comparisonData(): array {
return [ return [
// Compatible versions // Compatible versions
['13.0.0.3', '13.0.0', '>=', true], ['13.0.0.3', '13.0.0', '>=', true],

@ -195,7 +195,7 @@ class DependencyAnalyzerTest extends TestCase {
/** /**
* @return array * @return array
*/ */
public function providesOC() { public static function providesOC(): array {
return [ return [
// no version -> no missing dependency // no version -> no missing dependency
[ [
@ -423,7 +423,7 @@ class DependencyAnalyzerTest extends TestCase {
/** /**
* @return array * @return array
*/ */
public function providesOS() { public static function providesOS(): array {
return [ return [
[[], null], [[], null],
[[], []], [[], []],
@ -435,7 +435,7 @@ class DependencyAnalyzerTest extends TestCase {
/** /**
* @return array * @return array
*/ */
public function providesLibs() { public static function providesLibs(): array {
return [ return [
// we expect curl to exist // we expect curl to exist
[[], 'curl'], [[], 'curl'],
@ -465,7 +465,7 @@ class DependencyAnalyzerTest extends TestCase {
/** /**
* @return array * @return array
*/ */
public function providesCommands() { public static function providesCommands(): array {
return [ return [
[[], null], [[], null],
// grep is known on linux // grep is known on linux
@ -483,7 +483,7 @@ class DependencyAnalyzerTest extends TestCase {
/** /**
* @return array * @return array
*/ */
public function providesDatabases() { public static function providesDatabases(): array {
return [ return [
// non BC - in case on databases are defined -> all are supported // non BC - in case on databases are defined -> all are supported
[[], null], [[], null],
@ -496,7 +496,7 @@ class DependencyAnalyzerTest extends TestCase {
/** /**
* @return array * @return array
*/ */
public function providesPhpVersion() { public static function providesPhpVersion(): array {
return [ return [
[[], null, null, null], [[], null, null, null],
[[], '5.4', null, null], [[], '5.4', null, null],

@ -45,7 +45,7 @@ class InfoParserTest extends TestCase {
$this->parserTest($expectedJson, $xmlFile, self::$cache); $this->parserTest($expectedJson, $xmlFile, self::$cache);
} }
public function providesInfoXml(): array { public static function providesInfoXml(): array {
return [ return [
['expected-info.json', 'valid-info.xml'], ['expected-info.json', 'valid-info.xml'],
[null, 'invalid-info.xml'], [null, 'invalid-info.xml'],

@ -20,7 +20,7 @@ class PlatformRepositoryTest extends \Test\TestCase {
$this->assertEquals($expected, $normalizedVersion); $this->assertEquals($expected, $normalizedVersion);
} }
public function providesVersions() { public static function providesVersions(): array {
return [ return [
'none' => ['1.0.0', '1.0.0.0'], 'none' => ['1.0.0', '1.0.0.0'],
'none/2' => ['1.2.3.4', '1.2.3.4'], 'none/2' => ['1.2.3.4', '1.2.3.4'],

@ -32,10 +32,10 @@ class AppConfigTest extends TestCase {
private array $originalConfig; private array $originalConfig;
/** /**
* @var array<string, array<array<string, string, int, bool, bool>>> * @var array<string, array<string, array<string, string, int, bool, bool>>>
* [appId => [configKey, configValue, valueType, lazy, sensitive]] * [appId => [configKey, configValue, valueType, lazy, sensitive]]
*/ */
private array $baseStruct = private static array $baseStruct =
[ [
'testapp' => [ 'testapp' => [
'enabled' => ['enabled', 'true'], '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) { foreach ($appData as $key => $row) {
$value = $row[1]; $value = $row[1];
$type = $row[2] ?? IAppConfig::VALUE_MIXED; $type = $row[2] ?? IAppConfig::VALUE_MIXED;
if (($row[4] ?? false) === true) { if (($row[4] ?? false) === true) {
$type |= IAppConfig::VALUE_SENSITIVE; $type |= IAppConfig::VALUE_SENSITIVE;
$value = self::invokePrivate(AppConfig::class, 'ENCRYPTION_PREFIX') . $this->crypto->encrypt($value); $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( $sql->setParameters(
@ -197,7 +197,7 @@ class AppConfigTest extends TestCase {
$this->assertSame(true, $status['fastLoaded'], $msg); $this->assertSame(true, $status['fastLoaded'], $msg);
$this->assertSame(false, $status['lazyLoaded'], $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->assertEqualsCanonicalizing($apps, array_keys($status['fastCache']), $msg);
$this->assertSame([], array_keys($status['lazyCache']), $msg); $this->assertSame([], array_keys($status['lazyCache']), $msg);
} }
@ -208,7 +208,7 @@ class AppConfigTest extends TestCase {
public function testGetApps(): void { public function testGetApps(): void {
$config = $this->generateAppConfig(false); $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', ]] * @return array<string, string[]> ['appId' => ['key1', 'key2', ]]
* @see testGetKeys * @see testGetKeys
*/ */
public function providerGetAppKeys(): array { public static function providerGetAppKeys(): array {
$appKeys = []; $appKeys = [];
foreach ($this->baseStruct as $appId => $appData) { foreach (self::$baseStruct as $appId => $appData) {
$keys = []; $keys = [];
foreach ($appData as $row) { foreach ($appData as $row) {
$keys[] = $row[0]; $keys[] = $row[0];
@ -238,9 +238,9 @@ class AppConfigTest extends TestCase {
* @see testIsLazy * @see testIsLazy
* @see testGetKeys * @see testGetKeys
*/ */
public function providerGetKeys(): array { public static function providerGetKeys(): array {
$appKeys = []; $appKeys = [];
foreach ($this->baseStruct as $appId => $appData) { foreach (self::$baseStruct as $appId => $appData) {
foreach ($appData as $row) { foreach ($appData as $row) {
$appKeys[] = [ $appKeys[] = [
(string)$appId, $row[0], $row[1], $row[2] ?? IAppConfig::VALUE_MIXED, $row[3] ?? false, (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 { public function testHasKeyOnNonExistentKeyReturnsFalse(): void {
$config = $this->generateAppConfig(); $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 { public function testHasKeyOnUnknownAppReturnsFalse(): void {
@ -319,7 +319,7 @@ class AppConfigTest extends TestCase {
public function testIsSensitiveOnNonExistentKeyThrowsException(): void { public function testIsSensitiveOnNonExistentKeyThrowsException(): void {
$config = $this->generateAppConfig(); $config = $this->generateAppConfig();
$this->expectException(AppConfigUnknownKeyException::class); $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 { public function testIsSensitiveOnUnknownAppThrowsException(): void {
@ -362,7 +362,7 @@ class AppConfigTest extends TestCase {
public function testIsLazyOnNonExistentKeyThrowsException(): void { public function testIsLazyOnNonExistentKeyThrowsException(): void {
$config = $this->generateAppConfig(); $config = $this->generateAppConfig();
$this->expectException(AppConfigUnknownKeyException::class); $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 { public function testIsLazyOnUnknownAppThrowsException(): void {
@ -530,7 +530,7 @@ class AppConfigTest extends TestCase {
* *
* @see testGetValueMixed * @see testGetValueMixed
*/ */
public function providerGetValueMixed(): array { public static function providerGetValueMixed(): array {
return [ return [
// key, value, type // key, value, type
['mixed', 'mix', IAppConfig::VALUE_MIXED], ['mixed', 'mix', IAppConfig::VALUE_MIXED],

@ -124,7 +124,7 @@ class AppTest extends \Test\TestCase {
App::main($this->controllerName, $this->controllerMethod, $this->container, []); App::main($this->controllerName, $this->controllerMethod, $this->container, []);
} }
public function dataNoOutput() { public static function dataNoOutput(): array {
return [ return [
['HTTP/2.0 204 No content'], ['HTTP/2.0 204 No content'],
['HTTP/2.0 304 Not modified'], ['HTTP/2.0 304 Not modified'],

@ -156,7 +156,7 @@ class RegistrationContextTest extends TestCase {
); );
} }
public function dataProvider_TrueFalse() { public static function dataProvider_TrueFalse(): array {
return[ return[
[true], [true],
[false] [false]

@ -38,7 +38,7 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
$this->request, $this->request,
$this->session, $this->session,
$this->urlGenerator $this->urlGenerator
])->setMethods([ ])->onlyMethods([
'authFailed', 'authFailed',
'getPasswordHash', 'getPasswordHash',
'isAuthenticated', 'isAuthenticated',
@ -64,7 +64,9 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
$this->controller->setToken('myToken'); $this->controller->setToken('myToken');
$this->session->method('get') $this->session->method('get')
->willReturnMap(['public_link_authenticate_redirect', ['foo' => 'bar']]); ->willReturnMap([
['public_link_authenticate_redirect', json_encode(['foo' => 'bar'])],
]);
$this->urlGenerator->method('linkToRoute') $this->urlGenerator->method('linkToRoute')
->willReturn('myLink!'); ->willReturn('myLink!');
@ -107,7 +109,9 @@ class AuthPublicShareControllerTest extends \Test\TestCase {
$this->session->expects($this->once()) $this->session->expects($this->once())
->method('regenerateId'); ->method('regenerateId');
$this->session->method('get') $this->session->method('get')
->willReturnMap(['public_link_authenticate_redirect', ['foo' => 'bar']]); ->willReturnMap([
['public_link_authenticate_redirect', json_encode(['foo' => 'bar'])],
]);
$tokenSet = false; $tokenSet = false;
$hashSet = false; $hashSet = false;

@ -66,7 +66,7 @@ class ControllerTest extends \Test\TestCase {
); );
$this->app = $this->getMockBuilder(DIContainer::class) $this->app = $this->getMockBuilder(DIContainer::class)
->setMethods(['getAppName']) ->onlyMethods(['getAppName'])
->setConstructorArgs(['test']) ->setConstructorArgs(['test'])
->getMock(); ->getMock();
$this->app->expects($this->any()) $this->app->expects($this->any())

@ -57,7 +57,7 @@ class PublicShareControllerTest extends \Test\TestCase {
$this->assertEquals('test', $controller->getToken()); $this->assertEquals('test', $controller->getToken());
} }
public function dataIsAuthenticated() { public static function dataIsAuthenticated(): array {
return [ return [
[false, 'token1', 'token1', 'hash1', 'hash1', true], [false, 'token1', 'token1', 'hash1', 'hash1', true],
[false, 'token1', 'token1', 'hash1', 'hash2', true], [false, 'token1', 'token1', 'hash1', 'hash2', true],

@ -211,7 +211,7 @@ class EntityTest extends \Test\TestCase {
} }
public function dataSetterCasts(): array { public static function dataSetterCasts(): array {
return [ return [
['Id', '3', 3], ['Id', '3', 3],
['smallInt', '3', 3], ['smallInt', '3', 3],

@ -99,7 +99,7 @@ class QBMapperTest extends \Test\TestCase {
$this->mapper = new QBTestMapper($this->db); $this->mapper = new QBTestMapper($this->db);
} }
public function testInsertEntityParameterTypeMapping(): void { public function testInsertEntityParameterTypeMapping(): void {
$datetime = new \DateTimeImmutable(); $datetime = new \DateTimeImmutable();
$entity = new QBTestEntity(); $entity = new QBTestEntity();
@ -117,31 +117,40 @@ class QBMapperTest extends \Test\TestCase {
$booleanParam = $this->qb->createNamedParameter('boolean_prop', IQueryBuilder::PARAM_BOOL); $booleanParam = $this->qb->createNamedParameter('boolean_prop', IQueryBuilder::PARAM_BOOL);
$datetimeParam = $this->qb->createNamedParameter('datetime_prop', IQueryBuilder::PARAM_DATETIME_IMMUTABLE); $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)) $this->qb->expects($this->exactly(6))
->method('createNamedParameter') ->method('createNamedParameter')
->withConsecutive( ->willReturnCallback(function () use (&$createNamedParameterCalls) {
[$this->equalTo(123), $this->equalTo(IQueryBuilder::PARAM_INT)], $expected = array_shift($createNamedParameterCalls);
[$this->equalTo(true), $this->equalTo(IQueryBuilder::PARAM_BOOL)], $this->assertEquals($expected, func_get_args());
[$this->equalTo('string'), $this->equalTo(IQueryBuilder::PARAM_STR)], });
[$this->equalTo(456), $this->equalTo(IQueryBuilder::PARAM_INT)],
[$this->equalTo(false), $this->equalTo(IQueryBuilder::PARAM_BOOL)], $setValueCalls = [
[$this->equalTo($datetime), $this->equalTo(IQueryBuilder::PARAM_DATETIME_IMMUTABLE)], ['int_prop', $intParam],
); ['bool_prop', $boolParam],
['string_prop', $stringParam],
['integer_prop', $integerParam],
['boolean_prop', $booleanParam],
['datetime_prop', $datetimeParam],
];
$this->qb->expects($this->exactly(6)) $this->qb->expects($this->exactly(6))
->method('setValue') ->method('setValue')
->withConsecutive( ->willReturnCallback(function () use (&$setValueCalls) {
[$this->equalTo('int_prop'), $this->equalTo($intParam)], $expected = array_shift($setValueCalls);
[$this->equalTo('bool_prop'), $this->equalTo($boolParam)], $this->assertEquals($expected, func_get_args());
[$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)],
);
$this->mapper->insert($entity); $this->mapper->insert($entity);
} }
public function testUpdateEntityParameterTypeMapping(): void { public function testUpdateEntityParameterTypeMapping(): void {
$datetime = new \DateTimeImmutable(); $datetime = new \DateTimeImmutable();
$entity = new QBTestEntity(); $entity = new QBTestEntity();
@ -163,30 +172,38 @@ class QBMapperTest extends \Test\TestCase {
$jsonParam = $this->qb->createNamedParameter('json_prop', IQueryBuilder::PARAM_JSON); $jsonParam = $this->qb->createNamedParameter('json_prop', IQueryBuilder::PARAM_JSON);
$datetimeParam = $this->qb->createNamedParameter('datetime_prop', IQueryBuilder::PARAM_DATETIME_IMMUTABLE); $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)) $this->qb->expects($this->exactly(8))
->method('createNamedParameter') ->method('createNamedParameter')
->withConsecutive( ->willReturnCallback(function () use (&$createNamedParameterCalls) {
[$this->equalTo(123), $this->equalTo(IQueryBuilder::PARAM_INT)], $expected = array_shift($createNamedParameterCalls);
[$this->equalTo(true), $this->equalTo(IQueryBuilder::PARAM_BOOL)], $this->assertEquals($expected, func_get_args());
[$this->equalTo('string'), $this->equalTo(IQueryBuilder::PARAM_STR)], });
[$this->equalTo(456), $this->equalTo(IQueryBuilder::PARAM_INT)],
[$this->equalTo(false), $this->equalTo(IQueryBuilder::PARAM_BOOL)], $setCalls = [
[$this->equalTo(['hello' => 'world']), $this->equalTo(IQueryBuilder::PARAM_JSON)], ['int_prop', $intParam],
[$this->equalTo($datetime), $this->equalTo(IQueryBuilder::PARAM_DATETIME_IMMUTABLE)], ['bool_prop', $boolParam],
[$this->equalTo(789), $this->equalTo(IQueryBuilder::PARAM_INT)], ['string_prop', $stringParam],
); ['integer_prop', $integerParam],
['boolean_prop', $booleanParam],
['json_prop', $datetimeParam],
['datetime_prop', $datetimeParam],
];
$this->qb->expects($this->exactly(7)) $this->qb->expects($this->exactly(7))
->method('set') ->method('set')
->withConsecutive( ->willReturnCallback(function () use (&$setCalls) {
[$this->equalTo('int_prop'), $this->equalTo($intParam)], $expected = array_shift($setCalls);
[$this->equalTo('bool_prop'), $this->equalTo($boolParam)], $this->assertEquals($expected, func_get_args());
[$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)],
);
$this->expr->expects($this->once()) $this->expr->expects($this->once())
->method('eq') ->method('eq')
@ -196,7 +213,7 @@ class QBMapperTest extends \Test\TestCase {
$this->mapper->update($entity); $this->mapper->update($entity);
} }
public function testGetParameterTypeForProperty(): void { public function testGetParameterTypeForProperty(): void {
$entity = new QBTestEntity(); $entity = new QBTestEntity();

@ -29,7 +29,7 @@ class DIContainerTest extends \Test\TestCase {
protected function setUp(): void { protected function setUp(): void {
parent::setUp(); parent::setUp();
$this->container = $this->getMockBuilder(DIContainer::class) $this->container = $this->getMockBuilder(DIContainer::class)
->setMethods(['isAdminUser']) ->onlyMethods(['isAdminUser'])
->setConstructorArgs(['name']) ->setConstructorArgs(['name'])
->getMock(); ->getMock();
} }

@ -8,6 +8,7 @@
namespace Test\AppFramework\Http; namespace Test\AppFramework\Http;
use OC\AppFramework\DependencyInjection\DIContainer;
use OC\AppFramework\Http\Dispatcher; use OC\AppFramework\Http\Dispatcher;
use OC\AppFramework\Http\Request; use OC\AppFramework\Http\Request;
use OC\AppFramework\Middleware\MiddlewareDispatcher; use OC\AppFramework\Middleware\MiddlewareDispatcher;
@ -20,6 +21,7 @@ use OCP\AppFramework\Http\ParameterOutOfRangeException;
use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\Response;
use OCP\Diagnostics\IEventLogger; use OCP\Diagnostics\IEventLogger;
use OCP\IConfig; use OCP\IConfig;
use OCP\IDBConnection;
use OCP\IRequest; use OCP\IRequest;
use OCP\IRequestId; use OCP\IRequestId;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
@ -63,6 +65,10 @@ class TestController extends Controller {
'text' => [$int, $bool, $test, $test2] '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->logger = $this->createMock(LoggerInterface::class);
$this->eventLogger = $this->createMock(IEventLogger::class); $this->eventLogger = $this->createMock(IEventLogger::class);
$this->container = $this->createMock(ContainerInterface::class); $this->container = $this->createMock(ContainerInterface::class);
$app = $this->getMockBuilder( $app = $this->createMock(DIContainer::class);
'OC\AppFramework\DependencyInjection\DIContainer') $request = $this->createMock(Request::class);
->disableOriginalConstructor() $this->http = $this->createMock(\OC\AppFramework\Http::class);
->getMock();
$request = $this->getMockBuilder(
'\OC\AppFramework\Http\Request')
->disableOriginalConstructor()
->getMock();
$this->http = $this->getMockBuilder(
\OC\AppFramework\Http::class)
->disableOriginalConstructor()
->getMock();
$this->middlewareDispatcher = $this->getMockBuilder( $this->middlewareDispatcher = $this->createMock(MiddlewareDispatcher::class);
'\OC\AppFramework\Middleware\MiddlewareDispatcher') $this->controller = $this->getMockBuilder(TestController::class)
->disableOriginalConstructor() ->onlyMethods([$this->controllerMethod])
->getMock();
$this->controller = $this->getMockBuilder(
'\OCP\AppFramework\Controller')
->setMethods([$this->controllerMethod])
->setConstructorArgs([$app, $request]) ->setConstructorArgs([$app, $request])
->getMock(); ->getMock();
$this->request = $this->getMockBuilder( $this->request = $this->createMock(Request::class);
'\OC\AppFramework\Http\Request')
->disableOriginalConstructor()
->getMock();
$this->reflector = new ControllerMethodReflector(); $this->reflector = new ControllerMethodReflector();
@ -140,7 +130,7 @@ class DispatcherTest extends \Test\TestCase {
$this->reflector, $this->reflector,
$this->request, $this->request,
$this->config, $this->config,
\OC::$server->getDatabaseConnection(), \OCP\Server::get(IDBConnection::class),
$this->logger, $this->logger,
$this->eventLogger, $this->eventLogger,
$this->container, $this->container,
@ -545,7 +535,7 @@ class DispatcherTest extends \Test\TestCase {
} }
public function rangeDataProvider(): array { public static function rangeDataProvider(): array {
return [ return [
[PHP_INT_MIN, PHP_INT_MAX, 42, false], [PHP_INT_MIN, PHP_INT_MAX, 42, false],
[0, 12, -5, true], [0, 12, -5, true],

@ -37,7 +37,7 @@ class DownloadResponseTest extends \Test\TestCase {
$this->assertEquals('attachment; filename="' . $expected . '"', $headers['Content-Disposition']); $this->assertEquals('attachment; filename="' . $expected . '"', $headers['Content-Disposition']);
} }
public function filenameEncodingProvider() : array { public static function filenameEncodingProvider() : array {
return [ return [
['TestName.txt', 'TestName.txt'], ['TestName.txt', 'TestName.txt'],
['A "Quoted" Filename.txt', 'A \\"Quoted\\" Filename.txt'], ['A "Quoted" Filename.txt', 'A \\"Quoted\\" Filename.txt'],

@ -46,10 +46,7 @@ class JSONResponseTest extends \Test\TestCase {
$this->assertEquals($expected, $this->json->render()); $this->assertEquals($expected, $this->json->render());
} }
/** public static function renderDataProvider(): array {
* @return array
*/
public function renderDataProvider() {
return [ return [
[ [
['test' => 'hi'], '{"test":"hi"}', ['test' => 'hi'], '{"test":"hi"}',

@ -10,6 +10,7 @@ namespace Test\AppFramework\Middleware;
use OC\AppFramework\Http\Request; use OC\AppFramework\Http\Request;
use OC\AppFramework\Middleware\MiddlewareDispatcher; use OC\AppFramework\Middleware\MiddlewareDispatcher;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Middleware; use OCP\AppFramework\Middleware;
use OCP\IConfig; use OCP\IConfig;
@ -84,6 +85,10 @@ class TestMiddleware extends Middleware {
} }
} }
class TestController extends Controller {
public function method(): void {
}
}
class MiddlewareDispatcherTest extends \Test\TestCase { class MiddlewareDispatcherTest extends \Test\TestCase {
public $exception; public $exception;
@ -110,8 +115,8 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
private function getControllerMock() { private function getControllerMock() {
return $this->getMockBuilder('OCP\AppFramework\Controller') return $this->getMockBuilder(TestController::class)
->setMethods(['method']) ->onlyMethods(['method'])
->setConstructorArgs(['app', ->setConstructorArgs(['app',
new Request( new Request(
['method' => 'GET'], ['method' => 'GET'],
@ -131,14 +136,14 @@ class MiddlewareDispatcherTest extends \Test\TestCase {
public function testAfterExceptionShouldReturnResponseOfMiddleware(): void { public function testAfterExceptionShouldReturnResponseOfMiddleware(): void {
$response = new Response(); $response = new Response();
$m1 = $this->getMockBuilder('\OCP\AppFramework\Middleware') $m1 = $this->getMockBuilder(\OCP\AppFramework\Middleware::class)
->setMethods(['afterException', 'beforeController']) ->onlyMethods(['afterException', 'beforeController'])
->getMock(); ->getMock();
$m1->expects($this->never()) $m1->expects($this->never())
->method('afterException'); ->method('afterException');
$m2 = $this->getMockBuilder('OCP\AppFramework\Middleware') $m2 = $this->getMockBuilder(\OCP\AppFramework\Middleware::class)
->setMethods(['afterException', 'beforeController']) ->onlyMethods(['afterException', 'beforeController'])
->getMock(); ->getMock();
$m2->expects($this->once()) $m2->expects($this->once())
->method('afterException') ->method('afterException')

@ -36,12 +36,9 @@ class MiddlewareTest extends \Test\TestCase {
$this->middleware = new ChildMiddleware(); $this->middleware = new ChildMiddleware();
$this->api = $this->getMockBuilder(DIContainer::class) $this->api = $this->createMock(DIContainer::class);
->disableOriginalConstructor()
->getMock();
$this->controller = $this->getMockBuilder(Controller::class) $this->controller = $this->getMockBuilder(Controller::class)
->setMethods([])
->setConstructorArgs([ ->setConstructorArgs([
$this->api, $this->api,
new Request( new Request(
@ -51,7 +48,7 @@ class MiddlewareTest extends \Test\TestCase {
) )
])->getMock(); ])->getMock();
$this->exception = new \Exception(); $this->exception = new \Exception();
$this->response = $this->getMockBuilder(Response::class)->getMock(); $this->response = $this->createMock(Response::class);
} }

@ -32,7 +32,7 @@ class NotModifiedMiddlewareTest extends \Test\TestCase {
$this->controller = $this->createMock(Controller::class); $this->controller = $this->createMock(Controller::class);
} }
public function dataModified(): array { public static function dataModified(): array {
$now = new \DateTime(); $now = new \DateTime();
return [ return [

@ -12,6 +12,7 @@ use OC\AppFramework\OCS\V1Response;
use OC\AppFramework\OCS\V2Response; use OC\AppFramework\OCS\V2Response;
use OCP\AppFramework\Controller; use OCP\AppFramework\Controller;
use OCP\AppFramework\Http; use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\OCS\OCSBadRequestException; use OCP\AppFramework\OCS\OCSBadRequestException;
use OCP\AppFramework\OCS\OCSException; use OCP\AppFramework\OCS\OCSException;
use OCP\AppFramework\OCS\OCSForbiddenException; use OCP\AppFramework\OCS\OCSForbiddenException;
@ -32,49 +33,37 @@ class OCSMiddlewareTest extends \Test\TestCase {
->getMock(); ->getMock();
} }
public function dataAfterException() { public static function dataAfterException(): array {
$OCSController = $this->getMockBuilder(OCSController::class)
->disableOriginalConstructor()
->getMock();
$controller = $this->getMockBuilder(Controller::class)
->disableOriginalConstructor()
->getMock();
return [ return [
[$OCSController, new \Exception(), true], [OCSController::class, new \Exception(), true],
[$OCSController, new OCSException(), false, '', Http::STATUS_INTERNAL_SERVER_ERROR], [OCSController::class, new OCSException(), false, '', Http::STATUS_INTERNAL_SERVER_ERROR],
[$OCSController, new OCSException('foo'), false, 'foo', Http::STATUS_INTERNAL_SERVER_ERROR], [OCSController::class, 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::class, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), false, 'foo', Http::STATUS_IM_A_TEAPOT],
[$OCSController, new OCSBadRequestException(), false, '', Http::STATUS_BAD_REQUEST], [OCSController::class, new OCSBadRequestException(), false, '', Http::STATUS_BAD_REQUEST],
[$OCSController, new OCSBadRequestException('foo'), false, 'foo', Http::STATUS_BAD_REQUEST], [OCSController::class, new OCSBadRequestException('foo'), false, 'foo', Http::STATUS_BAD_REQUEST],
[$OCSController, new OCSForbiddenException(), false, '', Http::STATUS_FORBIDDEN], [OCSController::class, new OCSForbiddenException(), false, '', Http::STATUS_FORBIDDEN],
[$OCSController, new OCSForbiddenException('foo'), false, 'foo', Http::STATUS_FORBIDDEN], [OCSController::class, new OCSForbiddenException('foo'), false, 'foo', Http::STATUS_FORBIDDEN],
[$OCSController, new OCSNotFoundException(), false, '', Http::STATUS_NOT_FOUND], [OCSController::class, new OCSNotFoundException(), false, '', Http::STATUS_NOT_FOUND],
[$OCSController, new OCSNotFoundException('foo'), false, 'foo', Http::STATUS_NOT_FOUND], [OCSController::class, new OCSNotFoundException('foo'), false, 'foo', Http::STATUS_NOT_FOUND],
[$controller, new \Exception(), true], [Controller::class, new \Exception(), true],
[$controller, new OCSException(), true], [Controller::class, new OCSException(), true],
[$controller, new OCSException('foo'), true], [Controller::class, new OCSException('foo'), true],
[$controller, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), true], [Controller::class, new OCSException('foo', Http::STATUS_IM_A_TEAPOT), true],
[$controller, new OCSBadRequestException(), true], [Controller::class, new OCSBadRequestException(), true],
[$controller, new OCSBadRequestException('foo'), true], [Controller::class, new OCSBadRequestException('foo'), true],
[$controller, new OCSForbiddenException(), true], [Controller::class, new OCSForbiddenException(), true],
[$controller, new OCSForbiddenException('foo'), true], [Controller::class, new OCSForbiddenException('foo'), true],
[$controller, new OCSNotFoundException(), true], [Controller::class, new OCSNotFoundException(), true],
[$controller, new OCSNotFoundException('foo'), true], [Controller::class, new OCSNotFoundException('foo'), true],
]; ];
} }
/** /**
* @dataProvider dataAfterException * @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 $this->request
->method('getScriptName') ->method('getScriptName')
->willReturn('/ocs/v1.php'); ->willReturn('/ocs/v1.php');
@ -103,14 +92,9 @@ class OCSMiddlewareTest extends \Test\TestCase {
/** /**
* @dataProvider dataAfterException * @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 $this->request
->method('getScriptName') ->method('getScriptName')
->willReturn('/ocs/v2.php'); ->willReturn('/ocs/v2.php');
@ -137,14 +121,9 @@ class OCSMiddlewareTest extends \Test\TestCase {
/** /**
* @dataProvider dataAfterException * @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 $this->request
->method('getScriptName') ->method('getScriptName')
->willReturn('/mysubfolder/ocs/v2.php'); ->willReturn('/mysubfolder/ocs/v2.php');
@ -152,7 +131,7 @@ class OCSMiddlewareTest extends \Test\TestCase {
$OCSMiddleware->beforeController($controller, 'method'); $OCSMiddleware->beforeController($controller, 'method');
if ($forward) { if ($forward) {
$this->expectException(get_class($exception)); $this->expectException($exception::class);
$this->expectExceptionMessage($exception->getMessage()); $this->expectExceptionMessage($exception->getMessage());
} }
@ -169,39 +148,28 @@ class OCSMiddlewareTest extends \Test\TestCase {
$this->assertSame($code, $result->getStatus()); $this->assertSame($code, $result->getStatus());
} }
public function dataAfterController() { public static function dataAfterController(): array {
$OCSController = $this->getMockBuilder(OCSController::class)
->disableOriginalConstructor()
->getMock();
$controller = $this->getMockBuilder(Controller::class)
->disableOriginalConstructor()
->getMock();
return [ return [
[$OCSController, new Http\Response(), false], [OCSController::class, new Response(), false],
[$OCSController, new Http\JSONResponse(), false], [OCSController::class, new Http\JSONResponse(), false],
[$OCSController, new Http\JSONResponse(['message' => 'foo']), false], [OCSController::class, new Http\JSONResponse(['message' => 'foo']), false],
[$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true, OCSController::RESPOND_UNAUTHORISED], [OCSController::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), true, OCSController::RESPOND_UNAUTHORISED],
[$OCSController, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true], [OCSController::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), true],
[$controller, new Http\Response(), false], [Controller::class, new Response(), false],
[$controller, new Http\JSONResponse(), false], [Controller::class, new Http\JSONResponse(), false],
[$controller, new Http\JSONResponse(['message' => 'foo']), false], [Controller::class, new Http\JSONResponse(['message' => 'foo']), false],
[$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false], [Controller::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_UNAUTHORIZED), false],
[$controller, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false], [Controller::class, new Http\JSONResponse(['message' => 'foo'], Http::STATUS_FORBIDDEN), false],
]; ];
} }
/** /**
* @dataProvider dataAfterController * @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); $OCSMiddleware = new OCSMiddleware($this->request);
$newResponse = $OCSMiddleware->afterController($controller, 'foo', $response); $newResponse = $OCSMiddleware->afterController($controller, 'foo', $response);

@ -58,7 +58,7 @@ class PublicShareMiddlewareTest extends \Test\TestCase {
$this->assertTrue(true); $this->assertTrue(true);
} }
public function dataShareApi() { public static function dataShareApi(): array {
return [ return [
['no', 'no',], ['no', 'no',],
['no', 'yes',], ['no', 'yes',],

@ -98,13 +98,19 @@ class BruteForceMiddlewareTest extends TestCase {
->expects($this->once()) ->expects($this->once())
->method('getRemoteAddress') ->method('getRemoteAddress')
->willReturn('::1'); ->willReturn('::1');
$calls = [
['::1', 'first'],
['::1', 'second'],
];
$this->throttler $this->throttler
->expects($this->exactly(2)) ->expects($this->exactly(2))
->method('sleepDelayOrThrowOnMax') ->method('sleepDelayOrThrowOnMax')
->withConsecutive( ->willReturnCallback(function () use (&$calls) {
['::1', 'first'], $expected = array_shift($calls);
['::1', 'second'], $this->assertEquals($expected, func_get_args());
); return 0;
});
$controller = new TestController('test', $this->request); $controller = new TestController('test', $this->request);
$this->reflector->reflect($controller, 'multipleAttributes'); $this->reflector->reflect($controller, 'multipleAttributes');
@ -221,20 +227,31 @@ class BruteForceMiddlewareTest extends TestCase {
->expects($this->once()) ->expects($this->once())
->method('getRemoteAddress') ->method('getRemoteAddress')
->willReturn('::1'); ->willReturn('::1');
$sleepCalls = [
['::1', 'first'],
['::1', 'second'],
];
$this->throttler $this->throttler
->expects($this->exactly(2)) ->expects($this->exactly(2))
->method('sleepDelayOrThrowOnMax') ->method('sleepDelayOrThrowOnMax')
->withConsecutive( ->willReturnCallback(function () use (&$sleepCalls) {
['::1', 'first'], $expected = array_shift($sleepCalls);
['::1', 'second'], $this->assertEquals($expected, func_get_args());
); return 0;
});
$attemptCalls = [
['first', '::1', []],
['second', '::1', []],
];
$this->throttler $this->throttler
->expects($this->exactly(2)) ->expects($this->exactly(2))
->method('registerAttempt') ->method('registerAttempt')
->withConsecutive( ->willReturnCallback(function () use (&$attemptCalls) {
['first', '::1'], $expected = array_shift($attemptCalls);
['second', '::1'], $this->assertEquals($expected, func_get_args());
); });
$controller = new TestController('test', $this->request); $controller = new TestController('test', $this->request);
$this->reflector->reflect($controller, 'multipleAttributes'); $this->reflector->reflect($controller, 'multipleAttributes');

@ -44,7 +44,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
); );
} }
public function dataSetCORSAPIHeader(): array { public static function dataSetCORSAPIHeader(): array {
return [ return [
['testSetCORSAPIHeader'], ['testSetCORSAPIHeader'],
['testSetCORSAPIHeaderAttribute'], ['testSetCORSAPIHeaderAttribute'],
@ -89,7 +89,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers)); $this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers));
} }
public function dataNoOriginHeaderNoCORSHEADER(): array { public static function dataNoOriginHeaderNoCORSHEADER(): array {
return [ return [
['testNoOriginHeaderNoCORSHEADER'], ['testNoOriginHeaderNoCORSHEADER'],
['testNoOriginHeaderNoCORSHEADERAttribute'], ['testNoOriginHeaderNoCORSHEADERAttribute'],
@ -113,7 +113,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers)); $this->assertFalse(array_key_exists('Access-Control-Allow-Origin', $headers));
} }
public function dataCorsIgnoredIfWithCredentialsHeaderPresent(): array { public static function dataCorsIgnoredIfWithCredentialsHeaderPresent(): array {
return [ return [
['testCorsIgnoredIfWithCredentialsHeaderPresent'], ['testCorsIgnoredIfWithCredentialsHeaderPresent'],
['testCorsAttributeIgnoredIfWithCredentialsHeaderPresent'], ['testCorsAttributeIgnoredIfWithCredentialsHeaderPresent'],
@ -143,7 +143,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->afterController($this->controller, $method, $response); $middleware->afterController($this->controller, $method, $response);
} }
public function dataNoCORSOnAnonymousPublicPage(): array { public static function dataNoCORSOnAnonymousPublicPage(): array {
return [ return [
['testNoCORSOnAnonymousPublicPage'], ['testNoCORSOnAnonymousPublicPage'],
['testNoCORSOnAnonymousPublicPageAttribute'], ['testNoCORSOnAnonymousPublicPageAttribute'],
@ -177,7 +177,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method); $middleware->beforeController($this->controller, $method);
} }
public function dataCORSShouldNeverAllowCookieAuth(): array { public static function dataCORSShouldNeverAllowCookieAuth(): array {
return [ return [
['testCORSShouldNeverAllowCookieAuth'], ['testCORSShouldNeverAllowCookieAuth'],
['testCORSShouldNeverAllowCookieAuthAttribute'], ['testCORSShouldNeverAllowCookieAuthAttribute'],
@ -211,7 +211,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method); $middleware->beforeController($this->controller, $method);
} }
public function dataCORSShouldRelogin(): array { public static function dataCORSShouldRelogin(): array {
return [ return [
['testCORSShouldRelogin'], ['testCORSShouldRelogin'],
['testCORSAttributeShouldRelogin'], ['testCORSAttributeShouldRelogin'],
@ -242,7 +242,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method); $middleware->beforeController($this->controller, $method);
} }
public function dataCORSShouldFailIfPasswordLoginIsForbidden(): array { public static function dataCORSShouldFailIfPasswordLoginIsForbidden(): array {
return [ return [
['testCORSShouldFailIfPasswordLoginIsForbidden'], ['testCORSShouldFailIfPasswordLoginIsForbidden'],
['testCORSAttributeShouldFailIfPasswordLoginIsForbidden'], ['testCORSAttributeShouldFailIfPasswordLoginIsForbidden'],
@ -275,7 +275,7 @@ class CORSMiddlewareTest extends \Test\TestCase {
$middleware->beforeController($this->controller, $method); $middleware->beforeController($this->controller, $method);
} }
public function dataCORSShouldNotAllowCookieAuth(): array { public static function dataCORSShouldNotAllowCookieAuth(): array {
return [ return [
['testCORSShouldNotAllowCookieAuth'], ['testCORSShouldNotAllowCookieAuth'],
['testCORSAttributeShouldNotAllowCookieAuth'], ['testCORSAttributeShouldNotAllowCookieAuth'],

@ -162,7 +162,7 @@ class PasswordConfirmationMiddlewareTest extends TestCase {
public function dataProvider() { public static function dataProvider(): array {
return [ return [
['foo', 2000, 4000, true], ['foo', 2000, 4000, true],
['foo', 2000, 3000, false], ['foo', 2000, 3000, false],

@ -103,7 +103,7 @@ class SameSiteCookieMiddlewareTest extends TestCase {
$middleware = $this->getMockBuilder(SameSiteCookieMiddleware::class) $middleware = $this->getMockBuilder(SameSiteCookieMiddleware::class)
->setConstructorArgs([$this->request, $this->reflector]) ->setConstructorArgs([$this->request, $this->reflector])
->setMethods(['setSameSiteCookie']) ->onlyMethods(['setSameSiteCookie'])
->getMock(); ->getMock();
$middleware->expects($this->once()) $middleware->expects($this->once())

@ -125,7 +125,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
); );
} }
public function dataNoCSRFRequiredPublicPage(): array { public static function dataNoCSRFRequiredPublicPage(): array {
return [ return [
['testAnnotationNoCSRFRequiredPublicPage'], ['testAnnotationNoCSRFRequiredPublicPage'],
['testAnnotationNoCSRFRequiredAttributePublicPage'], ['testAnnotationNoCSRFRequiredAttributePublicPage'],
@ -134,21 +134,21 @@ class SecurityMiddlewareTest extends \Test\TestCase {
]; ];
} }
public function dataPublicPage(): array { public static function dataPublicPage(): array {
return [ return [
['testAnnotationPublicPage'], ['testAnnotationPublicPage'],
['testAttributePublicPage'], ['testAttributePublicPage'],
]; ];
} }
public function dataNoCSRFRequired(): array { public static function dataNoCSRFRequired(): array {
return [ return [
['testAnnotationNoCSRFRequired'], ['testAnnotationNoCSRFRequired'],
['testAttributeNoCSRFRequired'], ['testAttributeNoCSRFRequired'],
]; ];
} }
public function dataPublicPageStrictCookieRequired(): array { public static function dataPublicPageStrictCookieRequired(): array {
return [ return [
['testAnnotationPublicPageStrictCookieRequired'], ['testAnnotationPublicPageStrictCookieRequired'],
['testAnnotationStrictCookieRequiredAttributePublicPage'], ['testAnnotationStrictCookieRequiredAttributePublicPage'],
@ -157,28 +157,28 @@ class SecurityMiddlewareTest extends \Test\TestCase {
]; ];
} }
public function dataNoCSRFRequiredPublicPageStrictCookieRequired(): array { public static function dataNoCSRFRequiredPublicPageStrictCookieRequired(): array {
return [ return [
['testAnnotationNoCSRFRequiredPublicPageStrictCookieRequired'], ['testAnnotationNoCSRFRequiredPublicPageStrictCookieRequired'],
['testAttributeNoCSRFRequiredPublicPageStrictCookiesRequired'], ['testAttributeNoCSRFRequiredPublicPageStrictCookiesRequired'],
]; ];
} }
public function dataNoAdminRequiredNoCSRFRequired(): array { public static function dataNoAdminRequiredNoCSRFRequired(): array {
return [ return [
['testAnnotationNoAdminRequiredNoCSRFRequired'], ['testAnnotationNoAdminRequiredNoCSRFRequired'],
['testAttributeNoAdminRequiredNoCSRFRequired'], ['testAttributeNoAdminRequiredNoCSRFRequired'],
]; ];
} }
public function dataNoAdminRequiredNoCSRFRequiredPublicPage(): array { public static function dataNoAdminRequiredNoCSRFRequiredPublicPage(): array {
return [ return [
['testAnnotationNoAdminRequiredNoCSRFRequiredPublicPage'], ['testAnnotationNoAdminRequiredNoCSRFRequiredPublicPage'],
['testAttributeNoAdminRequiredNoCSRFRequiredPublicPage'], ['testAttributeNoAdminRequiredNoCSRFRequiredPublicPage'],
]; ];
} }
public function dataNoCSRFRequiredSubAdminRequired(): array { public static function dataNoCSRFRequiredSubAdminRequired(): array {
return [ return [
['testAnnotationNoCSRFRequiredSubAdminRequired'], ['testAnnotationNoCSRFRequiredSubAdminRequired'],
['testAnnotationNoCSRFRequiredAttributeSubAdminRequired'], ['testAnnotationNoCSRFRequiredAttributeSubAdminRequired'],
@ -429,7 +429,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
$this->middleware->beforeController($this->controller, $method); $this->middleware->beforeController($this->controller, $method);
} }
public function dataCsrfOcsController(): array { public static function dataCsrfOcsController(): array {
return [ return [
[NormalController::class, false, false, true], [NormalController::class, false, false, true],
[NormalController::class, false, true, true], [NormalController::class, false, true, true],
@ -659,7 +659,7 @@ class SecurityMiddlewareTest extends \Test\TestCase {
/** /**
* @return array * @return array
*/ */
public function exceptionProvider() { public static function exceptionProvider(): array {
return [ return [
[ [
new AppNotEnabledException(), new AppNotEnabledException(),

@ -23,7 +23,7 @@ class V2ResponseTest extends \Test\TestCase {
$this->assertEquals($expected, $response->getStatus()); $this->assertEquals($expected, $response->getStatus());
} }
public function providesStatusCodes(): array { public static function providesStatusCodes(): array {
return [ return [
[Http::STATUS_OK, 200], [Http::STATUS_OK, 200],
[Http::STATUS_BAD_REQUEST, 104], [Http::STATUS_BAD_REQUEST, 104],

@ -348,23 +348,24 @@ class RoutingTest extends \Test\TestCase {
$urlWithParam = $url . '/{' . $paramName . '}'; $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: // we expect create to be called five times:
$router $router
->expects($this->exactly(5)) ->expects($this->exactly(5))
->method('create') ->method('create')
->withConsecutive( ->willReturnCallback(function (string $name, string $pattern) use (&$calls) {
[$this->equalTo('ocs.app1.' . $resourceName . '.index'), $this->equalTo($url)], $expected = array_shift($calls);
[$this->equalTo('ocs.app1.' . $resourceName . '.show'), $this->equalTo($urlWithParam)], $this->assertEquals($expected['name'], $name);
[$this->equalTo('ocs.app1.' . $resourceName . '.create'), $this->equalTo($url)], $this->assertEquals($expected['pattern'], $pattern);
[$this->equalTo('ocs.app1.' . $resourceName . '.update'), $this->equalTo($urlWithParam)], return $expected['route'];
[$this->equalTo('ocs.app1.' . $resourceName . '.destroy'), $this->equalTo($urlWithParam)], });
)->willReturnOnConsecutiveCalls(
$indexRoute,
$showRoute,
$createRoute,
$updateRoute,
$destroyRoute,
);
// load route configuration // load route configuration
$config = new RouteConfig($container, $router, $yaml); $config = new RouteConfig($container, $router, $yaml);
@ -402,23 +403,23 @@ class RoutingTest extends \Test\TestCase {
$urlWithParam = $url . '/{' . $paramName . '}'; $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: // we expect create to be called five times:
$router $router
->expects($this->exactly(5)) ->expects($this->exactly(5))
->method('create') ->method('create')
->withConsecutive( ->willReturnCallback(function (string $name, string $pattern) use (&$calls) {
[$this->equalTo('app1.' . $resourceName . '.index'), $this->equalTo($url)], $expected = array_shift($calls);
[$this->equalTo('app1.' . $resourceName . '.show'), $this->equalTo($urlWithParam)], $this->assertEquals($expected['name'], $name);
[$this->equalTo('app1.' . $resourceName . '.create'), $this->equalTo($url)], $this->assertEquals($expected['pattern'], $pattern);
[$this->equalTo('app1.' . $resourceName . '.update'), $this->equalTo($urlWithParam)], return $expected['route'];
[$this->equalTo('app1.' . $resourceName . '.destroy'), $this->equalTo($urlWithParam)], });
)->willReturnOnConsecutiveCalls(
$indexRoute,
$showRoute,
$createRoute,
$updateRoute,
$destroyRoute,
);
// load route configuration // load route configuration
$config = new RouteConfig($container, $router, $yaml); $config = new RouteConfig($container, $router, $yaml);

@ -28,7 +28,7 @@ class AppConfigTest extends TestCase {
parent::setUp(); parent::setUp();
$this->config = $this->createMock(IConfig::class); $this->config = $this->createMock(IConfig::class);
$this->appConfigCore = $this->createMock(AppConfigCore::class); $this->appConfigCore = $this->createMock(AppConfigCore::class);
$this->appConfig = new AppConfig($this->config, $this->appConfigCore, self::TEST_APPID); $this->appConfig = new AppConfig($this->config, $this->appConfigCore, self::TEST_APPID);
} }
@ -46,7 +46,7 @@ class AppConfigTest extends TestCase {
* @return array * @return array
* @see testHasAppKey * @see testHasAppKey
*/ */
public function providerHasAppKey(): array { public static function providerHasAppKey(): array {
return [ return [
// lazy, expected // lazy, expected
[false, true], [false, true],
@ -76,7 +76,7 @@ class AppConfigTest extends TestCase {
* @return array * @return array
* @see testIsSensitive * @see testIsSensitive
*/ */
public function providerIsSensitive(): array { public static function providerIsSensitive(): array {
return [ return [
// lazy, expected // lazy, expected
[false, true], [false, true],
@ -123,7 +123,7 @@ class AppConfigTest extends TestCase {
* @return array * @return array
* @see testIsLazy * @see testIsLazy
*/ */
public function providerIsLazy(): array { public static function providerIsLazy(): array {
return [ return [
// expected // expected
[true], [true],
@ -161,7 +161,7 @@ class AppConfigTest extends TestCase {
* @return array * @return array
* @see testGetAllAppValues * @see testGetAllAppValues
*/ */
public function providerGetAllAppValues(): array { public static function providerGetAllAppValues(): array {
return [ return [
// key, filtered // key, filtered
['', false], ['', false],
@ -214,7 +214,7 @@ class AppConfigTest extends TestCase {
* @see testSetAppValueArray * @see testSetAppValueArray
* @see testSetAppValueArrayException * @see testSetAppValueArrayException
*/ */
public function providerSetAppValue(): array { public static function providerSetAppValue(): array {
return [ return [
// lazy, sensitive, expected // lazy, sensitive, expected
[false, false, true], [false, false, true],
@ -340,7 +340,7 @@ class AppConfigTest extends TestCase {
* @return array * @return array
* @see testSetAppValueBool * @see testSetAppValueBool
*/ */
public function providerSetAppValueBool(): array { public static function providerSetAppValueBool(): array {
return [ return [
// lazy, expected // lazy, expected
[false, true], [false, true],
@ -456,7 +456,7 @@ class AppConfigTest extends TestCase {
* @see testGetAppValueArray * @see testGetAppValueArray
* @see testGetAppValueArrayException * @see testGetAppValueArrayException
*/ */
public function providerGetAppValue(): array { public static function providerGetAppValue(): array {
return [ return [
// lazy, exist // lazy, exist
[false, false], [false, false],

@ -191,7 +191,7 @@ class SimpleContainerTest extends \Test\TestCase {
$this->container->query('test'), $this->container->query('test1')); $this->container->query('test'), $this->container->query('test1'));
} }
public function sanitizeNameProvider() { public static function sanitizeNameProvider(): array {
return [ return [
['ABC\\Foo', 'ABC\\Foo'], ['ABC\\Foo', 'ABC\\Foo'],
['\\ABC\\Foo', '\\ABC\\Foo'], ['\\ABC\\Foo', '\\ABC\\Foo'],

@ -34,7 +34,7 @@ class AppTest extends \Test\TestCase {
public const TEST_GROUP1 = 'group1'; public const TEST_GROUP1 = 'group1';
public const TEST_GROUP2 = 'group2'; public const TEST_GROUP2 = 'group2';
public function appVersionsProvider() { public static function appVersionsProvider(): array {
return [ return [
// exact match // exact match
[ [
@ -335,7 +335,7 @@ class AppTest extends \Test\TestCase {
/** /**
* Providers for the app config values * Providers for the app config values
*/ */
public function appConfigValuesProvider() { public static function appConfigValuesProvider(): array {
return [ return [
// logged in user1 // logged in user1
[ [
@ -591,7 +591,7 @@ class AppTest extends \Test\TestCase {
/** /**
* Providers for the app data values * Providers for the app data values
*/ */
public function appDataProvider() { public static function appDataProvider(): array {
return [ return [
[ [
['description' => " \t This is a multiline \n test with \n \t \n \n some new lines "], ['description' => " \t This is a multiline \n test with \n \t \n \n some new lines "],

@ -16,6 +16,10 @@ class ZIPTest extends TestBase {
} }
protected function getNew() { 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);
} }
} }

@ -83,13 +83,18 @@ class UserDeletedTokenCleanupListenerTest extends TestCase {
$token2, $token2,
$token3, $token3,
]); ]);
$calls = [
['user123', 1],
['user123', 2],
['user123', 3],
];
$this->manager->expects($this->exactly(3)) $this->manager->expects($this->exactly(3))
->method('invalidateTokenById') ->method('invalidateTokenById')
->withConsecutive( ->willReturnCallback(function () use (&$calls) {
['user123', 1], $expected = array_shift($calls);
['user123', 2], $this->assertEquals($expected, func_get_args());
['user123', 3] });
);
$this->logger->expects($this->never()) $this->logger->expects($this->never())
->method('error'); ->method('error');

@ -8,14 +8,13 @@ declare(strict_types=1);
namespace Test\Authentication\Login; namespace Test\Authentication\Login;
use OC\Authentication\Login\ALoginCommand;
use OC\Authentication\Login\LoginData; use OC\Authentication\Login\LoginData;
use OCP\IRequest; use OCP\IRequest;
use OCP\IUser; use OCP\IUser;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
use Test\TestCase; use Test\TestCase;
abstract class ALoginCommandTest extends TestCase { abstract class ALoginTestCommand extends TestCase {
/** @var IRequest|MockObject */ /** @var IRequest|MockObject */
protected $request; protected $request;
@ -36,7 +35,7 @@ abstract class ALoginCommandTest extends TestCase {
/** @var IUser|MockObject */ /** @var IUser|MockObject */
protected $user; protected $user;
/** @var ALoginCommand */ /** @var ALoginTestCommand */
protected $cmd; protected $cmd;
protected function setUp(): void { protected function setUp(): void {

@ -13,7 +13,7 @@ use OC\Authentication\Login\ClearLostPasswordTokensCommand;
use OCP\IConfig; use OCP\IConfig;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
class ClearLostPasswordTokensCommandTest extends ALoginCommandTest { class ClearLostPasswordTokensCommandTest extends ALoginTestCommand {
/** @var IConfig|MockObject */ /** @var IConfig|MockObject */
private $config; private $config;

@ -13,7 +13,7 @@ use OC\Authentication\Login\CompleteLoginCommand;
use OC\User\Session; use OC\User\Session;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
class CompleteLoginCommandTest extends ALoginCommandTest { class CompleteLoginCommandTest extends ALoginTestCommand {
/** @var Session|MockObject */ /** @var Session|MockObject */
private $session; private $session;

@ -15,7 +15,7 @@ use OC\User\Session;
use OCP\IConfig; use OCP\IConfig;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
class CreateSessionTokenCommandTest extends ALoginCommandTest { class CreateSessionTokenCommandTest extends ALoginTestCommand {
/** @var IConfig|MockObject */ /** @var IConfig|MockObject */
private $config; private $config;

@ -14,7 +14,7 @@ use OC\User\Session;
use OCP\IConfig; use OCP\IConfig;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
class FinishRememberedLoginCommandTest extends ALoginCommandTest { class FinishRememberedLoginCommandTest extends ALoginTestCommand {
/** @var Session|MockObject */ /** @var Session|MockObject */
private $userSession; private $userSession;
/** @var IConfig|MockObject */ /** @var IConfig|MockObject */

@ -15,7 +15,7 @@ use OCP\EventDispatcher\IEventDispatcher;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
class LoggedInCheckCommandTest extends ALoginCommandTest { class LoggedInCheckCommandTest extends ALoginTestCommand {
/** @var LoggerInterface|MockObject */ /** @var LoggerInterface|MockObject */
private $logger; private $logger;

@ -14,7 +14,7 @@ use OC\User\Manager;
use OCP\IUserManager; use OCP\IUserManager;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
class PreLoginHookCommandTest extends ALoginCommandTest { class PreLoginHookCommandTest extends ALoginTestCommand {
/** @var IUserManager|MockObject */ /** @var IUserManager|MockObject */
private $userManager; private $userManager;

@ -14,7 +14,7 @@ use OCP\IConfig;
use OCP\ISession; use OCP\ISession;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
class SetUserTimezoneCommandTest extends ALoginCommandTest { class SetUserTimezoneCommandTest extends ALoginTestCommand {
/** @var IConfig|MockObject */ /** @var IConfig|MockObject */
private $config; private $config;

@ -18,7 +18,7 @@ use OCP\Authentication\TwoFactorAuth\IProvider as ITwoFactorAuthProvider;
use OCP\IURLGenerator; use OCP\IURLGenerator;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
class TwoFactorCommandTest extends ALoginCommandTest { class TwoFactorCommandTest extends ALoginTestCommand {
/** @var Manager|MockObject */ /** @var Manager|MockObject */
private $twoFactorManager; private $twoFactorManager;

@ -13,7 +13,7 @@ use OC\Authentication\Login\UidLoginCommand;
use OC\User\Manager; use OC\User\Manager;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
class UidLoginCommandTest extends ALoginCommandTest { class UidLoginCommandTest extends ALoginTestCommand {
/** @var Manager|MockObject */ /** @var Manager|MockObject */
private $userManager; private $userManager;

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save