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

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

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

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

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

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

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

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

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

@ -45,7 +45,7 @@ class FtpTest extends \Test\Files\Storage\Storage {
/**
* ftp has no proper way to handle spaces at the end of file names
*/
public function directoryProvider() {
public static function directoryProvider(): array {
return array_filter(parent::directoryProvider(), function ($item) {
return substr($item[0], -1) !== ' ';
});

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -1,4 +1,7 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
@ -8,19 +11,13 @@ namespace OCA\WorkflowEngine\Tests\Check;
use OCA\WorkflowEngine\Check\RequestTime;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IL10N;
use PHPUnit\Framework\MockObject\MockObject;
class RequestTimeTest extends \Test\TestCase {
protected ITimeFactory&MockObject $timeFactory;
/** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */
protected $timeFactory;
/**
* @return IL10N|\PHPUnit\Framework\MockObject\MockObject
*/
protected function getL10NMock() {
$l = $this->getMockBuilder(IL10N::class)
->disableOriginalConstructor()
->getMock();
protected function getL10NMock(): IL10N&MockObject {
$l = $this->createMock(IL10N::class);
$l->expects($this->any())
->method('t')
->willReturnCallback(function ($string, $args) {
@ -32,11 +29,10 @@ class RequestTimeTest extends \Test\TestCase {
protected function setUp(): void {
parent::setUp();
$this->timeFactory = $this->getMockBuilder('OCP\AppFramework\Utility\ITimeFactory')
->getMock();
$this->timeFactory = $this->createMock(ITimeFactory::class);
}
public function dataExecuteCheck() {
public static function dataExecuteCheck(): array {
return [
[json_encode(['08:00 Europe/Berlin', '17:00 Europe/Berlin']), 1467870105, false], // 2016-07-07T07:41:45+02:00
[json_encode(['08:00 Europe/Berlin', '17:00 Europe/Berlin']), 1467873705, true], // 2016-07-07T08:41:45+02:00
@ -69,11 +65,8 @@ class RequestTimeTest extends \Test\TestCase {
/**
* @dataProvider dataExecuteCheck
* @param string $value
* @param int $timestamp
* @param bool $expected
*/
public function testExecuteCheckIn($value, $timestamp, $expected): void {
public function testExecuteCheckIn(string $value, int $timestamp, bool $expected): void {
$check = new RequestTime($this->getL10NMock(), $this->timeFactory);
$this->timeFactory->expects($this->once())
@ -85,11 +78,8 @@ class RequestTimeTest extends \Test\TestCase {
/**
* @dataProvider dataExecuteCheck
* @param string $value
* @param int $timestamp
* @param bool $expected
*/
public function testExecuteCheckNotIn($value, $timestamp, $expected): void {
public function testExecuteCheckNotIn(string $value, int $timestamp, bool $expected): void {
$check = new RequestTime($this->getL10NMock(), $this->timeFactory);
$this->timeFactory->expects($this->once())
@ -99,7 +89,7 @@ class RequestTimeTest extends \Test\TestCase {
$this->assertEquals(!$expected, $check->executeCheck('!in', $value));
}
public function dataValidateCheck() {
public static function dataValidateCheck(): array {
return [
['in', '["08:00 Europe/Berlin","17:00 Europe/Berlin"]'],
['!in', '["08:00 Europe/Berlin","17:00 America/North_Dakota/Beulah"]'],
@ -109,16 +99,14 @@ class RequestTimeTest extends \Test\TestCase {
/**
* @dataProvider dataValidateCheck
* @param string $operator
* @param string $value
*/
public function testValidateCheck($operator, $value): void {
public function testValidateCheck(string $operator, string $value): void {
$check = new RequestTime($this->getL10NMock(), $this->timeFactory);
$check->validateCheck($operator, $value);
$this->addToAssertionCount(1);
}
public function dataValidateCheckInvalid() {
public static function dataValidateCheckInvalid(): array {
return [
['!!in', '["08:00 Europe/Berlin","17:00 Europe/Berlin"]', 1, 'The given operator is invalid'],
['in', '["28:00 Europe/Berlin","17:00 Europe/Berlin"]', 2, 'The given time span is invalid'],
@ -132,12 +120,8 @@ class RequestTimeTest extends \Test\TestCase {
/**
* @dataProvider dataValidateCheckInvalid
* @param string $operator
* @param string $value
* @param int $exceptionCode
* @param string $exceptionMessage
*/
public function testValidateCheckInvalid($operator, $value, $exceptionCode, $exceptionMessage): void {
public function testValidateCheckInvalid(string $operator, string $value, int $exceptionCode, string $exceptionMessage): void {
$check = new RequestTime($this->getL10NMock(), $this->timeFactory);
try {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -16,6 +16,10 @@ class ZIPTest extends TestBase {
}
protected function getNew() {
return new ZIP(\OC::$server->getTempManager()->getTempBaseDir() . '/newArchive.zip');
$newZip = \OC::$server->getTempManager()->getTempBaseDir() . '/newArchive.zip';
if (file_exists($newZip)) {
unlink($newZip);
}
return new ZIP($newZip);
}
}

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

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

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

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

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

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

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

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

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

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

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

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

Loading…
Cancel
Save