From 197645687e57d7512e8a9c43a71351032763af12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Thu, 24 Sep 2026 17:48:58 +0200 Subject: [PATCH 1/5] feat(tests): Add a way to autowire the tested class to mocked objects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- tests/lib/TestCase.php | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index ec5282867f1ec..8735377d66e57 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -52,6 +52,49 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { /** Original values keyed by config key; null means the key was unset. */ private array $systemConfigValues = []; + /** @var array */ + protected array $mocks = []; + + /** + * @template T + * @param class-string $class + * @return T + */ + protected function createInstance(string $class, array $overrides = []): object { + $reflection = new \ReflectionClass($class); + $constructor = $reflection->getConstructor(); + if ($constructor === null) { + /* No constructor, return a instance directly */ + return $reflection->newInstance(); + } + $params = []; + foreach ($constructor->getParameters() as $parameter) { + if (isset($overrides[$parameter->getName()])) { + $params[] = $overrides[$parameter->getName()]; + continue; + } + $type = $parameter->getType(); + if ($type === null) { + $params[] = null; + continue; + } + if (!($type instanceof \ReflectionNamedType)) { + throw new \TypeError('Not supported'); + } + if ($type->isBuiltin()) { + throw new \TypeError('Not supported, please override value'); + } + $className = $type->getName(); + if (isset($overrides[$className])) { + $params[] = $overrides[$className]; + continue; + } + $this->mocks[$className] = $this->createMock($className); + $params[] = $this->mocks[$className]; + } + return $reflection->newInstanceArgs($params); + } + #[\Override] protected function onNotSuccessfulTest(\Throwable $t): never { $this->restoreAllServices(); From b584a9db633edc2a5a2e7722162b4fab52a2ed9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Thu, 24 Sep 2026 17:49:51 +0200 Subject: [PATCH 2/5] chore: Migrate appstore controller tests to the new method MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- .../tests/Controller/ApiControllerTest.php | 71 +------------------ .../tests/Controller/PageControllerTest.php | 58 +++------------ 2 files changed, 14 insertions(+), 115 deletions(-) diff --git a/apps/appstore/tests/Controller/ApiControllerTest.php b/apps/appstore/tests/Controller/ApiControllerTest.php index 98bc537d9b976..9e2bdfebdef8e 100644 --- a/apps/appstore/tests/Controller/ApiControllerTest.php +++ b/apps/appstore/tests/Controller/ApiControllerTest.php @@ -1,6 +1,7 @@ request = $this->createMock(IRequest::class); - $this->config = $this->createMock(IConfig::class); - $this->appConfig = $this->createMock(IAppConfig::class); - $this->appManager = $this->createMock(AppManager::class); - $this->dependencyAnalyzer = $this->createMock(DependencyAnalyzer::class); - $this->categoryFetcher = $this->createMock(CategoryFetcher::class); - $this->appFetcher = $this->createMock(AppFetcher::class); - $this->l10nFactory = $this->createMock(IFactory::class); - $this->bundleFetcher = $this->createMock(BundleFetcher::class); - $this->installer = $this->createMock(Installer::class); - $this->subscriptionRegistry = $this->createMock(IRegistry::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - - $this->apiController = new ApiController( - $this->request, - $this->config, - $this->appConfig, - $this->appManager, - $this->dependencyAnalyzer, - $this->categoryFetcher, - $this->appFetcher, - $this->l10nFactory, - $this->bundleFetcher, - $this->installer, - $this->subscriptionRegistry, - $this->logger, - $this->urlGenerator, - ); + $this->apiController = $this->createInstance(ApiController::class); } public function testListCategories(): void { $json = file_get_contents(__DIR__ . '/../fixtures/categories.json'); - $this->categoryFetcher + $this->mocks[CategoryFetcher::class] ->expects($this->once()) ->method('get') ->willReturn(json_decode($json, true)['data']); diff --git a/apps/appstore/tests/Controller/PageControllerTest.php b/apps/appstore/tests/Controller/PageControllerTest.php index 600db1ba0a082..5561549f0496e 100644 --- a/apps/appstore/tests/Controller/PageControllerTest.php +++ b/apps/appstore/tests/Controller/PageControllerTest.php @@ -11,34 +11,15 @@ use OC\App\AppStore\Bundles\BundleFetcher; use OC\Installer; use OCA\Appstore\Controller\PageController; -use OCP\App\IAppManager; use OCP\AppFramework\Http\ContentSecurityPolicy; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Services\IInitialState; use OCP\IConfig; use OCP\IL10N; -use OCP\IRequest; -use OCP\IURLGenerator; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; #[\PHPUnit\Framework\Attributes\Group(name: 'DB')] final class PageControllerTest extends TestCase { - private IRequest&MockObject $request; - - private IL10N&MockObject $l10n; - - private IConfig&MockObject $config; - - private IAppManager&MockObject $appManager; - - private BundleFetcher&MockObject $bundleFetcher; - - private Installer&MockObject $installer; - - private IURLGenerator&MockObject $urlGenerator; - - private IInitialState&MockObject $initialState; private PageController $pageController; @@ -46,42 +27,25 @@ final class PageControllerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->request = $this->createMock(IRequest::class); - $this->l10n = $this->createMock(IL10N::class); - $this->l10n->expects($this->any()) + $this->pageController = $this->createInstance(PageController::class); + + $this->mocks[IL10N::class]->expects($this->any()) ->method('t') ->willReturnArgument(0); - $this->config = $this->createMock(IConfig::class); - $this->appManager = $this->createMock(IAppManager::class); - $this->bundleFetcher = $this->createMock(BundleFetcher::class); - $this->installer = $this->createMock(Installer::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - $this->initialState = $this->createMock(IInitialState::class); - - $this->pageController = new PageController( - $this->request, - $this->l10n, - $this->config, - $this->installer, - $this->appManager, - $this->urlGenerator, - $this->initialState, - $this->bundleFetcher, - ); } public function testViewApps(): void { - $this->bundleFetcher->expects($this->once())->method('getBundles')->willReturn([]); - $this->installer->expects($this->any()) + $this->mocks[BundleFetcher::class]->expects($this->once())->method('getBundles')->willReturn([]); + $this->mocks[Installer::class]->expects($this->any()) ->method('isUpdateAvailable') ->willReturn(false); - $this->config + $this->mocks[IConfig::class] ->expects($this->once()) ->method('getSystemValueBool') ->with('appstoreenabled', true) ->willReturn(true); - $this->initialState + $this->mocks[IInitialState::class] ->expects($this->exactly(4)) ->method('provideInitialState'); @@ -100,17 +64,17 @@ public function testViewApps(): void { } public function testViewAppsAppstoreNotEnabled(): void { - $this->installer->expects($this->any()) + $this->mocks[Installer::class]->expects($this->any()) ->method('isUpdateAvailable') ->willReturn(false); - $this->bundleFetcher->expects($this->once())->method('getBundles')->willReturn([]); - $this->config + $this->mocks[BundleFetcher::class]->expects($this->once())->method('getBundles')->willReturn([]); + $this->mocks[IConfig::class] ->expects($this->once()) ->method('getSystemValueBool') ->with('appstoreenabled', true) ->willReturn(false); - $this->initialState + $this->mocks[IInitialState::class] ->expects($this->exactly(4)) ->method('provideInitialState'); From b41b82a9ea2ee05ed9d0623bbaf19d598632d0a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Thu, 24 Sep 2026 18:36:35 +0200 Subject: [PATCH 3/5] fix: Improve auto-mocking and use it in a few more test classes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- .../tests/Controller/ApiControllerTest.php | 2 +- .../tests/Controller/PageControllerTest.php | 7 +- .../tests/Unit/Activity/ListenerTest.php | 36 ++--- .../Unit/Controller/NotificationsTest.php | 68 ++++------ .../tests/Unit/Notification/NotifierTest.php | 128 ++++-------------- tests/lib/TestCase.php | 34 ++++- 6 files changed, 94 insertions(+), 181 deletions(-) diff --git a/apps/appstore/tests/Controller/ApiControllerTest.php b/apps/appstore/tests/Controller/ApiControllerTest.php index 9e2bdfebdef8e..411e851b8b5df 100644 --- a/apps/appstore/tests/Controller/ApiControllerTest.php +++ b/apps/appstore/tests/Controller/ApiControllerTest.php @@ -23,7 +23,7 @@ final class ApiControllerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->apiController = $this->createInstance(ApiController::class); + $this->apiController = $this->createInstanceWithMocks(ApiController::class); } public function testListCategories(): void { diff --git a/apps/appstore/tests/Controller/PageControllerTest.php b/apps/appstore/tests/Controller/PageControllerTest.php index 5561549f0496e..e69e4489321d1 100644 --- a/apps/appstore/tests/Controller/PageControllerTest.php +++ b/apps/appstore/tests/Controller/PageControllerTest.php @@ -15,7 +15,6 @@ use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Services\IInitialState; use OCP\IConfig; -use OCP\IL10N; use Test\TestCase; #[\PHPUnit\Framework\Attributes\Group(name: 'DB')] @@ -27,11 +26,7 @@ final class PageControllerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->pageController = $this->createInstance(PageController::class); - - $this->mocks[IL10N::class]->expects($this->any()) - ->method('t') - ->willReturnArgument(0); + $this->pageController = $this->createInstanceWithMocks(PageController::class); } public function testViewApps(): void { diff --git a/apps/comments/tests/Unit/Activity/ListenerTest.php b/apps/comments/tests/Unit/Activity/ListenerTest.php index 1ae8a38c24509..3e23aade745e5 100644 --- a/apps/comments/tests/Unit/Activity/ListenerTest.php +++ b/apps/comments/tests/Unit/Activity/ListenerTest.php @@ -28,37 +28,17 @@ use Test\TestCase; class ListenerTest extends TestCase { - 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; #[\Override] protected function setUp(): void { parent::setUp(); - $this->activityManager = $this->createMock(IManager::class); - $this->session = $this->createMock(IUserSession::class); - $this->appManager = $this->createMock(IAppManager::class); - $this->mountProviderCollection = $this->createMock(IMountProviderCollection::class); - $this->rootFolder = $this->createMock(IRootFolder::class); - $this->shareHelper = $this->createMock(IShareHelper::class); - - $this->listener = new Listener( - $this->activityManager, - $this->session, - $this->appManager, - $this->mountProviderCollection, - $this->rootFolder, - $this->shareHelper - ); + $this->listener = $this->createInstanceWithMocks(Listener::class); } public function testCommentEvent(): void { - $this->appManager->expects($this->any()) + $this->mocks[IAppManager::class]->expects($this->any()) ->method('isEnabledForAnyone') ->with('activity') ->willReturn(true); @@ -89,7 +69,7 @@ public function testCommentEvent(): void { ->method('getMountsForFileId') ->willReturn($mounts); - $this->mountProviderCollection->expects($this->any()) + $this->mocks[IMountProviderCollection::class]->expects($this->any()) ->method('getMountCache') ->willReturn($userMountCache); @@ -100,7 +80,7 @@ public function testCommentEvent(): void { ->method('getFirstNodeById') ->willReturn($node); - $this->rootFolder->expects($this->any()) + $this->mocks[IRootFolder::class]->expects($this->any()) ->method('getUserFolder') ->willReturn($ownerFolder); @@ -109,11 +89,11 @@ public function testCommentEvent(): void { '254342' => 'there/i/have/it', 'sandra' => 'and/here/i/placed/it' ]]; - $this->shareHelper->expects($this->any()) + $this->mocks[IShareHelper::class]->expects($this->any()) ->method('getPathsForAccessList') ->willReturn($al); - $this->session->expects($this->any()) + $this->mocks[IUserSession::class]->expects($this->any()) ->method('getUser') ->willReturn($ownerUser); @@ -142,10 +122,10 @@ public function testCommentEvent(): void { ->with('add_comment_message', $this->anything()) ->willReturnSelf(); - $this->activityManager->expects($this->once()) + $this->mocks[IManager::class]->expects($this->once()) ->method('generateEvent') ->willReturn($activity); - $this->activityManager->expects($this->exactly(count($al['users']))) + $this->mocks[IManager::class]->expects($this->exactly(count($al['users']))) ->method('publish'); $this->listener->commentEvent($event); diff --git a/apps/comments/tests/Unit/Controller/NotificationsTest.php b/apps/comments/tests/Unit/Controller/NotificationsTest.php index 58c9ad664b321..d9d894b80ff61 100644 --- a/apps/comments/tests/Unit/Controller/NotificationsTest.php +++ b/apps/comments/tests/Unit/Controller/NotificationsTest.php @@ -19,61 +19,45 @@ use OCP\Files\IRootFolder; use OCP\Files\IUserFolder; use OCP\Files\Node; -use OCP\IRequest; use OCP\IURLGenerator; 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 { - protected ICommentsManager&MockObject $commentsManager; - protected IRootFolder&MockObject $rootFolder; - protected IUserSession&MockObject $session; - protected IManager&MockObject $notificationManager; - protected IURLGenerator&MockObject $urlGenerator; protected NotificationsController $notificationsController; #[\Override] protected function setUp(): void { parent::setUp(); - $this->commentsManager = $this->createMock(ICommentsManager::class); - $this->rootFolder = $this->createMock(IRootFolder::class); - $this->session = $this->createMock(IUserSession::class); - $this->notificationManager = $this->createMock(IManager::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - - $this->notificationsController = new NotificationsController( - 'comments', - $this->createMock(IRequest::class), - $this->commentsManager, - $this->rootFolder, - $this->urlGenerator, - $this->notificationManager, - $this->session + $this->notificationsController = $this->createInstanceWithMocks( + NotificationsController::class, + [ + 'appName' => 'comments', + ] ); } public function testViewGuestRedirect(): void { - $this->commentsManager->expects($this->never()) + $this->mocks[ICommentsManager::class]->expects($this->never()) ->method('get'); - $this->rootFolder->expects($this->never()) + $this->mocks[IRootFolder::class]->expects($this->never()) ->method('getUserFolder'); - $this->session->expects($this->once()) + $this->mocks[IUserSession::class]->expects($this->once()) ->method('getUser') ->willReturn(null); - $this->notificationManager->expects($this->never()) + $this->mocks[IManager::class]->expects($this->never()) ->method('createNotification'); - $this->notificationManager->expects($this->never()) + $this->mocks[IManager::class]->expects($this->never()) ->method('markProcessed'); - $this->urlGenerator->expects($this->exactly(2)) + $this->mocks[IURLGenerator::class]->expects($this->exactly(2)) ->method('linkToRoute') ->willReturnMap([ ['comments.Notifications.view', ['id' => '42'], 'link-to-comment'], @@ -95,7 +79,7 @@ public function testViewSuccess(): void { ->method('getId') ->willReturn('1234'); - $this->commentsManager->expects($this->any()) + $this->mocks[ICommentsManager::class]->expects($this->any()) ->method('get') ->with('42') ->willReturn($comment); @@ -104,7 +88,7 @@ public function testViewSuccess(): void { $folder = $this->createMock(IUserFolder::class); $user = $this->createMock(IUser::class); - $this->rootFolder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('getUserFolder') ->willReturn($folder); @@ -112,7 +96,7 @@ public function testViewSuccess(): void { ->method('getFirstNodeById') ->willReturn($file); - $this->session->expects($this->once()) + $this->mocks[IUserSession::class]->expects($this->once()) ->method('getUser') ->willReturn($user); @@ -125,10 +109,10 @@ public function testViewSuccess(): void { ->method($this->anything()) ->willReturn($notification); - $this->notificationManager->expects($this->once()) + $this->mocks[IManager::class]->expects($this->once()) ->method('createNotification') ->willReturn($notification); - $this->notificationManager->expects($this->once()) + $this->mocks[IManager::class]->expects($this->once()) ->method('markProcessed') ->with($notification); @@ -137,17 +121,17 @@ public function testViewSuccess(): void { } public function testViewInvalidComment(): void { - $this->commentsManager->expects($this->any()) + $this->mocks[ICommentsManager::class]->expects($this->any()) ->method('get') ->with('42') ->willThrowException(new NotFoundException()); - $this->rootFolder->expects($this->never()) + $this->mocks[IRootFolder::class]->expects($this->never()) ->method('getUserFolder'); $user = $this->createMock(IUser::class); - $this->session->expects($this->once()) + $this->mocks[IUserSession::class]->expects($this->once()) ->method('getUser') ->willReturn($user); @@ -155,9 +139,9 @@ public function testViewInvalidComment(): void { ->method('getUID') ->willReturn('user'); - $this->notificationManager->expects($this->never()) + $this->mocks[IManager::class]->expects($this->never()) ->method('createNotification'); - $this->notificationManager->expects($this->never()) + $this->mocks[IManager::class]->expects($this->never()) ->method('markProcessed'); $response = $this->notificationsController->view('42'); @@ -173,14 +157,14 @@ public function testViewNoFile(): void { ->method('getId') ->willReturn('1234'); - $this->commentsManager->expects($this->any()) + $this->mocks[ICommentsManager::class]->expects($this->any()) ->method('get') ->with('42') ->willReturn($comment); $folder = $this->createMock(IUserFolder::class); - $this->rootFolder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('getUserFolder') ->willReturn($folder); @@ -190,7 +174,7 @@ public function testViewNoFile(): void { $user = $this->createMock(IUser::class); - $this->session->expects($this->once()) + $this->mocks[IUserSession::class]->expects($this->once()) ->method('getUser') ->willReturn($user); @@ -203,10 +187,10 @@ public function testViewNoFile(): void { ->method($this->anything()) ->willReturn($notification); - $this->notificationManager->expects($this->once()) + $this->mocks[IManager::class]->expects($this->once()) ->method('createNotification') ->willReturn($notification); - $this->notificationManager->expects($this->once()) + $this->mocks[IManager::class]->expects($this->once()) ->method('markProcessed') ->with($notification); diff --git a/apps/comments/tests/Unit/Notification/NotifierTest.php b/apps/comments/tests/Unit/Notification/NotifierTest.php index 7bec485149dde..fa3d19bf57eaf 100644 --- a/apps/comments/tests/Unit/Notification/NotifierTest.php +++ b/apps/comments/tests/Unit/Notification/NotifierTest.php @@ -16,10 +16,8 @@ use OCP\Files\IRootFolder; use OCP\Files\IUserFolder; use OCP\Files\Node; -use OCP\IL10N; use OCP\IURLGenerator; use OCP\IUserManager; -use OCP\L10N\IFactory; use OCP\Notification\AlreadyProcessedException; use OCP\Notification\INotification; use OCP\Notification\UnknownNotificationException; @@ -27,12 +25,6 @@ use Test\TestCase; class NotifierTest extends TestCase { - 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; @@ -42,26 +34,7 @@ class NotifierTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->l10nFactory = $this->createMock(IFactory::class); - $this->folder = $this->createMock(IRootFolder::class); - $this->commentsManager = $this->createMock(ICommentsManager::class); - $this->url = $this->createMock(IURLGenerator::class); - $this->userManager = $this->createMock(IUserManager::class); - - $this->notifier = new Notifier( - $this->l10nFactory, - $this->folder, - $this->commentsManager, - $this->url, - $this->userManager - ); - - $this->l = $this->createMock(IL10N::class); - $this->l->expects($this->any()) - ->method('t') - ->willReturnCallback(function ($text, $parameters = []) { - return vsprintf($text, $parameters); - }); + $this->notifier = $this->createInstanceWithMocks(Notifier::class); $this->notification = $this->createMock(INotification::class); $this->comment = $this->createMock(IComment::class); @@ -83,7 +56,7 @@ public function testPrepareSuccess(): void { ->willReturn('/you/files/' . $fileName); $userFolder = $this->createMock(IUserFolder::class); - $this->folder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('getUserFolder') ->with('you') ->willReturn($userFolder); @@ -129,20 +102,15 @@ public function testPrepareSuccess(): void { ->with('absolute-image-path') ->willReturnSelf(); - $this->url->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('imagePath') ->with('core', 'actions/comment.svg') ->willReturn('image-path'); - $this->url->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('getAbsoluteURL') ->with('image-path') ->willReturn('absolute-image-path'); - $this->l10nFactory - ->expects($this->once()) - ->method('get') - ->willReturn($this->l); - $this->comment ->expects($this->any()) ->method('getActorId') @@ -163,17 +131,17 @@ public function testPrepareSuccess(): void { ->method('getId') ->willReturn('1234'); - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->once()) ->method('get') ->willReturn($this->comment); - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->once()) ->method('resolveDisplayName') ->with('user', 'you') ->willReturn('Your name'); - $this->userManager + $this->mocks[IUserManager::class] ->expects($this->exactly(2)) ->method('getDisplayName') ->willReturnMap([ @@ -199,7 +167,7 @@ public function testPrepareSuccessDeletedUser(): void { ->willReturn('/you/files/' . $fileName); $userFolder = $this->createMock(IUserFolder::class); - $this->folder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('getUserFolder') ->with('you') ->willReturn($userFolder); @@ -245,20 +213,15 @@ public function testPrepareSuccessDeletedUser(): void { ->with('absolute-image-path') ->willReturnSelf(); - $this->url->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('imagePath') ->with('core', 'actions/comment.svg') ->willReturn('image-path'); - $this->url->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('getAbsoluteURL') ->with('image-path') ->willReturn('absolute-image-path'); - $this->l10nFactory - ->expects($this->once()) - ->method('get') - ->willReturn($this->l); - $this->comment ->expects($this->any()) ->method('getActorId') @@ -276,17 +239,17 @@ public function testPrepareSuccessDeletedUser(): void { ->method('getMentions') ->willReturn([['type' => 'user', 'id' => 'you']]); - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->once()) ->method('get') ->willReturn($this->comment); - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->once()) ->method('resolveDisplayName') ->with('user', 'you') ->willReturn('Your name'); - $this->userManager + $this->mocks[IUserManager::class] ->expects($this->once()) ->method('getDisplayName') ->willReturnMap([ @@ -300,7 +263,7 @@ public function testPrepareSuccessDeletedUser(): void { public function testPrepareDifferentApp(): void { $this->expectException(UnknownNotificationException::class); - $this->folder + $this->mocks[IRootFolder::class] ->expects($this->never()) ->method('getFirstNodeById'); @@ -318,15 +281,11 @@ public function testPrepareDifferentApp(): void { ->expects($this->never()) ->method('setParsedSubject'); - $this->l10nFactory - ->expects($this->never()) - ->method('get'); - - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->never()) ->method('get'); - $this->userManager + $this->mocks[IUserManager::class] ->expects($this->never()) ->method('getDisplayName'); @@ -336,7 +295,7 @@ public function testPrepareDifferentApp(): void { public function testPrepareNotFound(): void { $this->expectException(UnknownNotificationException::class); - $this->folder + $this->mocks[IRootFolder::class] ->expects($this->never()) ->method('getFirstNodeById'); @@ -354,16 +313,12 @@ public function testPrepareNotFound(): void { ->expects($this->never()) ->method('setParsedSubject'); - $this->l10nFactory - ->expects($this->never()) - ->method('get'); - - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->once()) ->method('get') ->willThrowException(new NotFoundException()); - $this->userManager + $this->mocks[IUserManager::class] ->expects($this->never()) ->method('getDisplayName'); @@ -375,7 +330,7 @@ public function testPrepareDifferentSubject(): void { $displayName = 'Huraga'; - $this->folder + $this->mocks[IRootFolder::class] ->expects($this->never()) ->method('getFirstNodeById'); @@ -394,15 +349,6 @@ public function testPrepareDifferentSubject(): void { ->expects($this->never()) ->method('setParsedSubject'); - $this->l - ->expects($this->never()) - ->method('t'); - - $this->l10nFactory - ->expects($this->once()) - ->method('get') - ->willReturn($this->l); - $this->comment ->expects($this->any()) ->method('getActorId') @@ -412,12 +358,12 @@ public function testPrepareDifferentSubject(): void { ->method('getActorType') ->willReturn('users'); - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->once()) ->method('get') ->willReturn($this->comment); - $this->userManager + $this->mocks[IUserManager::class] ->expects($this->once()) ->method('getDisplayName') ->with('huraga') @@ -431,7 +377,7 @@ public function testPrepareNotFiles(): void { $displayName = 'Huraga'; - $this->folder + $this->mocks[IRootFolder::class] ->expects($this->never()) ->method('getFirstNodeById'); @@ -451,15 +397,6 @@ public function testPrepareNotFiles(): void { ->expects($this->never()) ->method('setParsedSubject'); - $this->l - ->expects($this->never()) - ->method('t'); - - $this->l10nFactory - ->expects($this->once()) - ->method('get') - ->willReturn($this->l); - $this->comment ->expects($this->any()) ->method('getActorId') @@ -469,12 +406,12 @@ public function testPrepareNotFiles(): void { ->method('getActorType') ->willReturn('users'); - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->once()) ->method('get') ->willReturn($this->comment); - $this->userManager + $this->mocks[IUserManager::class] ->expects($this->once()) ->method('getDisplayName') ->with('huraga') @@ -489,7 +426,7 @@ public function testPrepareUnresolvableFileID(): void { $displayName = 'Huraga'; $userFolder = $this->createMock(IUserFolder::class); - $this->folder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('getUserFolder') ->with('you') ->willReturn($userFolder); @@ -517,15 +454,6 @@ public function testPrepareUnresolvableFileID(): void { ->expects($this->never()) ->method('setParsedSubject'); - $this->l - ->expects($this->never()) - ->method('t'); - - $this->l10nFactory - ->expects($this->once()) - ->method('get') - ->willReturn($this->l); - $this->comment ->expects($this->any()) ->method('getActorId') @@ -535,12 +463,12 @@ public function testPrepareUnresolvableFileID(): void { ->method('getActorType') ->willReturn('users'); - $this->commentsManager + $this->mocks[ICommentsManager::class] ->expects($this->once()) ->method('get') ->willReturn($this->comment); - $this->userManager + $this->mocks[IUserManager::class] ->expects($this->once()) ->method('getDisplayName') ->with('huraga') diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index 8735377d66e57..59b00d43af024 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -32,6 +32,7 @@ use OCP\IAppConfig; use OCP\IConfig; use OCP\IDBConnection; +use OCP\IL10N; use OCP\IUserManager; use OCP\IUserSession; use OCP\Lock\ILockingProvider; @@ -39,6 +40,7 @@ use OCP\Security\ISecureRandom; use OCP\Server; use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerExceptionInterface; abstract class TestCase extends \PHPUnit\Framework\TestCase { @@ -52,7 +54,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { /** Original values keyed by config key; null means the key was unset. */ private array $systemConfigValues = []; - /** @var array */ + /** @var array */ protected array $mocks = []; /** @@ -60,7 +62,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase { * @param class-string $class * @return T */ - protected function createInstance(string $class, array $overrides = []): object { + protected function createInstanceWithMocks(string $class, array $overrides = []): object { $reflection = new \ReflectionClass($class); $constructor = $reflection->getConstructor(); if ($constructor === null) { @@ -89,12 +91,36 @@ protected function createInstance(string $class, array $overrides = []): object $params[] = $overrides[$className]; continue; } - $this->mocks[$className] = $this->createMock($className); - $params[] = $this->mocks[$className]; + if (isset($this->mocks[$className])) { + $params[] = $this->mocks[$className]; + } else { + $params[] = $this->createAutoMock($className); + } } return $reflection->newInstanceArgs($params); } + protected function createAutoMock($className): MockObject { + $mock = $this->createMock($className); + switch ($className) { + case IL10N::class: + // Return the english string with parameters applied + $mock + ->method('t') + ->willReturnCallback( + fn (string $text, array $parameters = []) => vsprintf($text, $parameters) + ); + break; + case \OCP\L10N\IFactory::class: + $mockL10n = $this->createAutoMock(IL10N::class); + $mock->method('get') + ->willReturn($mockL10n); + break; + } + $this->mocks[$className] = $mock; + return $mock; + } + #[\Override] protected function onNotSuccessfulTest(\Throwable $t): never { $this->restoreAllServices(); From 9ef72fa977c3e1f999d84f3c0a7b8dd2e2bd2dbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Fri, 25 Sep 2026 16:37:17 +0200 Subject: [PATCH 4/5] chore: migrate tests using rector MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- .../Command/Config/App/DeleteConfigTest.php | 12 +- .../Core/Command/Config/App/GetConfigTest.php | 12 +- .../Core/Command/Config/App/SetConfigTest.php | 16 +- tests/Core/Command/Db/DbIndexUsageTest.php | 34 +- tests/Core/Command/Db/DbInfoTest.php | 26 +- tests/Core/Command/Db/DbLocksTest.php | 30 +- tests/Core/Command/Db/DbSizeTest.php | 22 +- tests/Core/Command/Group/AddTest.php | 15 +- tests/Core/Command/Group/AddUserTest.php | 29 +- tests/Core/Command/Group/DeleteTest.php | 21 +- tests/Core/Command/Group/RemoveUserTest.php | 29 +- .../Maintenance/Mimetype/UpdateDBTest.php | 38 +- .../Core/Command/Maintenance/UpdateTheme.php | 15 +- tests/Core/Command/Preview/CleanupTest.php | 38 +- .../Command/TwoFactorAuth/CleanupTest.php | 15 +- .../Command/TwoFactorAuth/DisableTest.php | 22 +- .../Core/Command/TwoFactorAuth/EnableTest.php | 22 +- .../Command/TwoFactorAuth/EnforceTest.php | 28 +- .../Core/Command/TwoFactorAuth/StateTest.php | 19 +- tests/Core/Command/User/DisableTest.php | 10 +- tests/Core/Command/User/EnableTest.php | 10 +- .../Controller/WellKnownControllerTest.php | 19 +- .../Listener/AvatarVersionListenerTest.php | 14 +- .../AppStore/AppStoreLinkVisibilityTest.php | 22 +- .../Bootstrap/BootContextTest.php | 16 +- .../Bootstrap/CoordinatorTest.php | 41 +-- .../Bootstrap/RegistrationContextTest.php | 18 +- .../Http/FileDisplayResponseTest.php | 20 +- .../AdditionalScriptsMiddlewareTest.php | 34 +- .../Middleware/CompressionMiddlewareTest.php | 18 +- .../Middleware/NotModifiedMiddlewareTest.php | 10 +- .../PublicShare/PublicShareMiddlewareTest.php | 58 ++-- .../Middleware/Security/CSPMiddlewareTest.php | 25 +- .../Security/FeaturePolicyMiddlewareTest.php | 11 +- .../Security/SameSiteCookieMiddlewareTest.php | 41 +-- .../RemoteWipeActivityListenerTest.php | 27 +- .../Listeners/RemoteWipeEmailListenerTest.php | 69 ++-- .../RemoteWipeNotificationsListenerTest.php | 27 +- .../UserDeletedTokenCleanupListenerTest.php | 29 +- .../ClearLostPasswordTokensCommandTest.php | 12 +- .../Login/CompleteLoginCommandTest.php | 12 +- .../Login/CreateSessionTokenCommandTest.php | 44 +-- .../FinishRememberedLoginCommandTest.php | 24 +- .../Login/LoggedInCheckCommandTest.php | 18 +- .../Login/PreLoginHookCommandTest.php | 11 +- .../Login/SetUserTimezoneCommandTest.php | 33 +- .../Login/TwoFactorCommandTest.php | 120 +++---- .../Login/UidLoginCommandTest.php | 14 +- .../UpdateLastPasswordConfirmCommandTest.php | 12 +- .../Login/UserDisabledCheckCommandTest.php | 22 +- .../LoginCredentials/StoreTest.php | 80 ++--- .../lib/Authentication/Token/ManagerTest.php | 56 ++- .../Authentication/Token/RemoteWipeTest.php | 50 +-- .../TwoFactorAuth/ManagerTest.php | 201 +++++------ .../TwoFactorAuth/MandatoryTwoFactorTest.php | 36 +- .../TwoFactorAuth/ProviderManagerTest.php | 31 +- .../TwoFactorAuth/RegistryTest.php | 40 +-- tests/lib/Avatar/AvatarManagerTest.php | 104 ++---- tests/lib/Calendar/ManagerTest.php | 325 ++++++++---------- tests/lib/Calendar/Resource/ManagerTest.php | 20 +- tests/lib/Calendar/Room/ManagerTest.php | 20 +- .../Collaborators/SearchTest.php | 11 +- tests/lib/Command/Integrity/SignAppTest.php | 28 +- tests/lib/Command/Integrity/SignCoreTest.php | 23 +- .../lib/Contacts/ContactsMenu/ManagerTest.php | 48 +-- .../Providers/LocalTimeProviderTest.php | 50 +-- tests/lib/EmojiHelperTest.php | 9 +- .../lib/Encryption/EncryptionWrapperTest.php | 18 +- tests/lib/Encryption/ManagerTest.php | 51 +-- tests/lib/ErrorHandlerTest.php | 10 +- tests/lib/Files/AppData/FactoryTest.php | 15 +- tests/lib/Files/Cache/SearchBuilderTest.php | 20 +- .../PrimaryObjectStoreConfigTest.php | 19 +- tests/lib/Files/SimpleFS/SimpleFileTest.php | 33 +- tests/lib/Http/Client/ClientTest.php | 130 +++---- .../lib/Http/Client/NegativeDnsCacheTest.php | 9 +- .../lib/Http/WellKnown/RequestManagerTest.php | 32 +- tests/lib/L10N/LanguageIteratorTest.php | 16 +- tests/lib/Log/PsrLoggerAdapterTest.php | 10 +- tests/lib/Mail/EmailValidatorTest.php | 8 +- .../lib/Memcache/KeyValueCacheFactoryTest.php | 23 +- tests/lib/NavigationManagerTest.php | 176 ++++------ tests/lib/Notification/ManagerTest.php | 101 ++---- tests/lib/Notification/NotificationTest.php | 13 +- tests/lib/OCM/Rfc9421SignatoryManagerTest.php | 17 +- tests/lib/Preview/GeneratorTest.php | 107 ++---- .../Storage/LocalPreviewStorageTest.php | 77 ++--- tests/lib/Repair/ClearFrontendCachesTest.php | 11 +- .../Repair/ClearGeneratedAvatarCacheTest.php | 15 +- .../NC29/SanitizeAccountPropertiesTest.php | 8 +- .../CleanPreviewsBackgroundJobTest.php | 55 +-- .../lib/Repair/Owncloud/CleanPreviewsTest.php | 30 +- tests/lib/Repair/RepairDavSharesTest.php | 23 +- tests/lib/Search/SearchComposerTest.php | 31 +- .../Backend/MemoryCacheBackendTest.php | 17 +- .../Security/Bruteforce/CapabilitiesTest.php | 25 +- .../ContentSecurityPolicyNonceManagerTest.php | 19 +- tests/lib/Security/HasherTest.php | 18 +- .../Backend/MemoryCacheBackendTest.php | 27 +- .../lib/Security/RateLimiting/LimiterTest.php | 31 +- .../lib/Security/RemoteHostValidatorTest.php | 34 +- .../VerificationTokenTest.php | 76 ++-- tests/lib/Settings/DeclarativeManagerTest.php | 61 +--- tests/lib/Settings/ManagerTest.php | 67 +--- tests/lib/Share20/ShareHelperTest.php | 11 +- tests/lib/Share20/ShareTest.php | 10 +- .../lib/Support/Subscription/RegistryTest.php | 38 +- .../SystemReport/SystemReportManagerTest.php | 29 +- tests/lib/Talk/BrokerTest.php | 48 +-- tests/lib/Template/JSCombinerTest.php | 51 +-- tests/lib/TestCase.php | 3 +- tests/lib/UpdaterTest.php | 53 +-- .../lib/User/AvailabilityCoordinatorTest.php | 38 +- tests/lib/User/DatabaseTest.php | 11 +- tests/lib/User/ManagerTest.php | 18 +- 115 files changed, 1368 insertions(+), 2791 deletions(-) diff --git a/tests/Core/Command/Config/App/DeleteConfigTest.php b/tests/Core/Command/Config/App/DeleteConfigTest.php index 219ead209a524..71505d5e51587 100644 --- a/tests/Core/Command/Config/App/DeleteConfigTest.php +++ b/tests/Core/Command/Config/App/DeleteConfigTest.php @@ -9,7 +9,6 @@ namespace Tests\Core\Command\Config\App; -use OC\Config\ConfigManager; use OC\Core\Command\Config\App\DeleteConfig; use OCP\IAppConfig; use PHPUnit\Framework\MockObject\MockObject; @@ -19,8 +18,6 @@ use Test\TestCase; class DeleteConfigTest extends TestCase { - protected IAppConfig&MockObject $appConfig; - protected ConfigManager&MockObject $configManager; protected InputInterface&MockObject $consoleInput; protected OutputInterface&MockObject $consoleOutput; protected Command $command; @@ -28,13 +25,10 @@ class DeleteConfigTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->appConfig = $this->createMock(IAppConfig::class); - $this->configManager = $this->createMock(ConfigManager::class); $this->consoleInput = $this->createMock(InputInterface::class); $this->consoleOutput = $this->createMock(OutputInterface::class); - $this->command = new DeleteConfig($this->appConfig, $this->configManager); + $this->command = $this->createInstanceWithMocks(DeleteConfig::class); } public static function dataDelete(): array { @@ -72,12 +66,12 @@ public static function dataDelete(): array { #[\PHPUnit\Framework\Attributes\DataProvider('dataDelete')] public function testDelete(string $configName, bool $configExists, bool $checkIfExists, int $expectedReturn, string $expectedMessage): void { - $this->appConfig->expects(($checkIfExists) ? $this->once() : $this->never()) + $this->mocks[IAppConfig::class]->expects(($checkIfExists) ? $this->once() : $this->never()) ->method('getKeys') ->with('app-name') ->willReturn($configExists ? [$configName] : []); - $this->appConfig->expects(($expectedReturn === 0) ? $this->once() : $this->never()) + $this->mocks[IAppConfig::class]->expects(($expectedReturn === 0) ? $this->once() : $this->never()) ->method('deleteKey') ->with('app-name', $configName); diff --git a/tests/Core/Command/Config/App/GetConfigTest.php b/tests/Core/Command/Config/App/GetConfigTest.php index 36f96803dc35b..5485b6a4a7c4b 100644 --- a/tests/Core/Command/Config/App/GetConfigTest.php +++ b/tests/Core/Command/Config/App/GetConfigTest.php @@ -9,7 +9,6 @@ namespace Tests\Core\Command\Config\App; -use OC\Config\ConfigManager; use OC\Core\Command\Config\App\GetConfig; use OCP\Exceptions\AppConfigUnknownKeyException; use OCP\IAppConfig; @@ -20,8 +19,6 @@ use Test\TestCase; class GetConfigTest extends TestCase { - protected IAppConfig&MockObject $appConfig; - protected ConfigManager&MockObject $configManager; protected InputInterface&MockObject $consoleInput; protected OutputInterface&MockObject $consoleOutput; protected Command $command; @@ -29,13 +26,10 @@ class GetConfigTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->appConfig = $this->createMock(IAppConfig::class); - $this->configManager = $this->createMock(ConfigManager::class); $this->consoleInput = $this->createMock(InputInterface::class); $this->consoleOutput = $this->createMock(OutputInterface::class); - $this->command = new GetConfig($this->appConfig, $this->configManager); + $this->command = $this->createInstanceWithMocks(GetConfig::class); } public static function dataGet(): array { @@ -83,7 +77,7 @@ public static function dataGet(): array { public function testGet(string $configName, mixed $value, bool $configExists, mixed $defaultValue, bool $hasDefault, string $outputFormat, int $expectedReturn, ?string $expectedMessage): void { if (!$expectedReturn) { if ($configExists) { - $this->appConfig->expects($this->once()) + $this->mocks[IAppConfig::class]->expects($this->once()) ->method('getDetails') ->with('app-name', $configName) ->willReturn(['value' => $value]); @@ -91,7 +85,7 @@ public function testGet(string $configName, mixed $value, bool $configExists, mi } if (!$configExists) { - $this->appConfig->expects($this->once()) + $this->mocks[IAppConfig::class]->expects($this->once()) ->method('getDetails') ->with('app-name', $configName) ->willThrowException(new AppConfigUnknownKeyException()); diff --git a/tests/Core/Command/Config/App/SetConfigTest.php b/tests/Core/Command/Config/App/SetConfigTest.php index 25cd1c5be738a..9b479edca476a 100644 --- a/tests/Core/Command/Config/App/SetConfigTest.php +++ b/tests/Core/Command/Config/App/SetConfigTest.php @@ -10,7 +10,6 @@ namespace Tests\Core\Command\Config\App; use OC\AppConfig; -use OC\Config\ConfigManager; use OC\Core\Command\Config\App\SetConfig; use OCP\Exceptions\AppConfigUnknownKeyException; use OCP\IAppConfig; @@ -21,8 +20,6 @@ use Test\TestCase; class SetConfigTest extends TestCase { - protected IAppConfig&MockObject $appConfig; - protected ConfigManager&MockObject $configManager; protected InputInterface&MockObject $consoleInput; protected OutputInterface&MockObject $consoleOutput; protected Command $command; @@ -30,13 +27,10 @@ class SetConfigTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->appConfig = $this->createMock(AppConfig::class); - $this->configManager = $this->createMock(ConfigManager::class); $this->consoleInput = $this->createMock(InputInterface::class); $this->consoleOutput = $this->createMock(OutputInterface::class); - $this->command = new SetConfig($this->appConfig, $this->configManager); + $this->command = $this->createInstanceWithMocks(SetConfig::class); } public static function dataSet(): array { @@ -62,20 +56,20 @@ public static function dataSet(): array { #[\PHPUnit\Framework\Attributes\DataProvider('dataSet')] public function testSet(string $configName, mixed $newValue, bool $configExists, bool $updateOnly, bool $updated, string $expectedMessage): void { - $this->appConfig->method('hasKey') + $this->mocks[AppConfig::class]->method('hasKey') ->with('app-name', $configName) ->willReturn($configExists); if (!$configExists) { - $this->appConfig->method('getValueType') + $this->mocks[AppConfig::class]->method('getValueType') ->willThrowException(new AppConfigUnknownKeyException()); } else { - $this->appConfig->method('getValueType') + $this->mocks[AppConfig::class]->method('getValueType') ->willReturn(IAppConfig::VALUE_MIXED); } if ($updated) { - $this->appConfig->expects($this->once()) + $this->mocks[AppConfig::class]->expects($this->once()) ->method('setValueMixed') ->with('app-name', $configName, $newValue); } diff --git a/tests/Core/Command/Db/DbIndexUsageTest.php b/tests/Core/Command/Db/DbIndexUsageTest.php index c5520499a90df..21ebfc07d5b49 100644 --- a/tests/Core/Command/Db/DbIndexUsageTest.php +++ b/tests/Core/Command/Db/DbIndexUsageTest.php @@ -22,15 +22,13 @@ class DbIndexUsageTest extends TestCase { - private Connection&MockObject $connection; private InputInterface&MockObject $input; private DbIndexUsage $command; protected function setUp(): void { parent::setUp(); - $this->connection = $this->createMock(Connection::class); $this->input = $this->createMock(InputInterface::class); - $this->command = new DbIndexUsage($this->connection); + $this->command = $this->createInstanceWithMocks(DbIndexUsage::class); } private function mockMySQLRows(): array { @@ -53,9 +51,9 @@ private function mockResult(array $rows): Result&MockObject { } public function testNoUnusedIndexesPrintsSuccessMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult([])); $this->input->method('getOption')->willReturnMap([['json', false], ['all', false]]); @@ -67,9 +65,9 @@ public function testNoUnusedIndexesPrintsSuccessMessage(): void { } public function testMySQLUnusedIndexesRendersTable(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockMySQLRows())); $this->input->method('getOption')->willReturnMap([['json', false], ['all', false]]); @@ -85,9 +83,9 @@ public function testMySQLUnusedIndexesRendersTable(): void { } public function testPostgreSQLUnusedIndexesRendersTable(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(PostgreSQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockPostgreSQLRows())); $this->input->method('getOption')->willReturnMap([['json', false], ['all', false]]); @@ -101,9 +99,9 @@ public function testPostgreSQLUnusedIndexesRendersTable(): void { } public function testAllFlagSuppressesCountMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockMySQLRows())); $this->input->method('getOption')->willReturnMap([['json', false], ['all', true]]); @@ -114,9 +112,9 @@ public function testAllFlagSuppressesCountMessage(): void { } public function testDefaultFilterIncludedInQuery(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->expects($this->once()) + $this->mocks[Connection::class]->expects($this->once()) ->method('executeQuery') ->with($this->stringContains('count_read = 0')) ->willReturn($this->mockResult([])); @@ -126,9 +124,9 @@ public function testDefaultFilterIncludedInQuery(): void { } public function testAllFlagRemovesFilterFromQuery(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->expects($this->once()) + $this->mocks[Connection::class]->expects($this->once()) ->method('executeQuery') ->with($this->logicalNot($this->stringContains('count_read = 0'))) ->willReturn($this->mockResult([])); @@ -138,9 +136,9 @@ public function testAllFlagRemovesFilterFromQuery(): void { } public function testJsonOutputWhenRowsExist(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockMySQLRows())); $this->input->method('getOption')->willReturnMap([['json', true], ['all', false]]); @@ -156,7 +154,7 @@ public function testJsonOutputWhenRowsExist(): void { } public function testSQLiteReturnsSuccessWithMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(SqlitePlatform::class)); $this->input->method('getOption')->willReturnMap([['json', false], ['all', false]]); diff --git a/tests/Core/Command/Db/DbInfoTest.php b/tests/Core/Command/Db/DbInfoTest.php index bf5d5be492b86..de4d977295260 100644 --- a/tests/Core/Command/Db/DbInfoTest.php +++ b/tests/Core/Command/Db/DbInfoTest.php @@ -23,15 +23,13 @@ class DbInfoTest extends TestCase { - private Connection&MockObject $connection; private InputInterface&MockObject $input; private DbInfo $command; protected function setUp(): void { parent::setUp(); - $this->connection = $this->createMock(Connection::class); $this->input = $this->createMock(InputInterface::class); - $this->command = new DbInfo($this->connection); + $this->command = $this->createInstanceWithMocks(DbInfo::class); } private function mockMySQLResult(array $overrides = []): Result&MockObject { @@ -58,9 +56,9 @@ private function mockPostgreSQLResult(): Result&MockObject { } public function testMySQLTableOutput(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockMySQLResult()); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -74,9 +72,9 @@ public function testMySQLTableOutput(): void { } public function testPostgreSQLTableOutput(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(PostgreSQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockPostgreSQLResult()); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -88,11 +86,11 @@ public function testPostgreSQLTableOutput(): void { } public function testSQLiteTableOutput(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(SqlitePlatform::class)); $result = $this->createMock(Result::class); $result->method('fetchAssociative')->willReturn(['version' => '3.43.0']); - $this->connection->method('executeQuery')->willReturn($result); + $this->mocks[Connection::class]->method('executeQuery')->willReturn($result); $this->input->method('getOption')->willReturnMap([['json', false]]); $output = new BufferedOutput(); @@ -103,7 +101,7 @@ public function testSQLiteTableOutput(): void { } public function testUnsupportedPlatformReturnsFailure(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(AbstractPlatform::class)); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -115,9 +113,9 @@ public function testUnsupportedPlatformReturnsFailure(): void { } public function testJsonOutputContainsSettingKeys(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockMySQLResult()); $this->input->method('getOption')->willReturnMap([['json', true]]); @@ -149,9 +147,9 @@ public function testMySQLHealthCheckStatus( bool $expectedOk, string $settingLabel, ): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockMySQLResult([$field => $value])); $this->input->method('getOption')->willReturnMap([['json', true]]); diff --git a/tests/Core/Command/Db/DbLocksTest.php b/tests/Core/Command/Db/DbLocksTest.php index c0621141c9816..a540a8b3fd4f5 100644 --- a/tests/Core/Command/Db/DbLocksTest.php +++ b/tests/Core/Command/Db/DbLocksTest.php @@ -22,15 +22,13 @@ class DbLocksTest extends TestCase { - private Connection&MockObject $connection; private InputInterface&MockObject $input; private DbLocks $command; protected function setUp(): void { parent::setUp(); - $this->connection = $this->createMock(Connection::class); $this->input = $this->createMock(InputInterface::class); - $this->command = new DbLocks($this->connection); + $this->command = $this->createInstanceWithMocks(DbLocks::class); } private function mockMySQLLocks(): array { @@ -62,9 +60,9 @@ private function mockResult(array $rows): Result&MockObject { } public function testMySQLNoLocksShowsInfoMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult([])); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -76,9 +74,9 @@ public function testMySQLNoLocksShowsInfoMessage(): void { } public function testPostgreSQLNoLocksShowsInfoMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(PostgreSQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult([])); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -90,9 +88,9 @@ public function testPostgreSQLNoLocksShowsInfoMessage(): void { } public function testMySQLLocksFoundShowsErrorMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockMySQLLocks())); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -104,9 +102,9 @@ public function testMySQLLocksFoundShowsErrorMessage(): void { } public function testPostgreSQLLocksFoundShowsErrorMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(PostgreSQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockPostgreSQLLocks())); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -118,9 +116,9 @@ public function testPostgreSQLLocksFoundShowsErrorMessage(): void { } public function testJsonOutputWhenLocksExist(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockMySQLLocks())); $this->input->method('getOption')->willReturnMap([['json', true]]); @@ -135,7 +133,7 @@ public function testJsonOutputWhenLocksExist(): void { } public function testSQLiteReturnsSuccessWithMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(SqlitePlatform::class)); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -147,9 +145,9 @@ public function testSQLiteReturnsSuccessWithMessage(): void { } public function testNullColumnRenderedAsDash(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockMySQLLocks())); // blocking_query = null $this->input->method('getOption')->willReturnMap([['json', false]]); diff --git a/tests/Core/Command/Db/DbSizeTest.php b/tests/Core/Command/Db/DbSizeTest.php index 17aadb9b5a930..0ae147dd946a4 100644 --- a/tests/Core/Command/Db/DbSizeTest.php +++ b/tests/Core/Command/Db/DbSizeTest.php @@ -22,15 +22,13 @@ class DbSizeTest extends TestCase { - private Connection&MockObject $connection; private InputInterface&MockObject $input; private DbSize $command; protected function setUp(): void { parent::setUp(); - $this->connection = $this->createMock(Connection::class); $this->input = $this->createMock(InputInterface::class); - $this->command = new DbSize($this->connection); + $this->command = $this->createInstanceWithMocks(DbSize::class); } private function mockRows(): array { @@ -47,9 +45,9 @@ private function mockResult(array $rows): Result&MockObject { } public function testMySQLOutputContainsTableAndTotal(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockRows())); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -63,9 +61,9 @@ public function testMySQLOutputContainsTableAndTotal(): void { } public function testPostgreSQLOutputContainsTableAndTotal(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(PostgreSQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockRows())); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -77,7 +75,7 @@ public function testPostgreSQLOutputContainsTableAndTotal(): void { } public function testSQLiteReturnsSuccessWithMessage(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(SqlitePlatform::class)); $this->input->method('getOption')->willReturnMap([['json', false]]); @@ -89,9 +87,9 @@ public function testSQLiteReturnsSuccessWithMessage(): void { } public function testJsonOutputIsValidArray(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockRows())); $this->input->method('getOption')->willReturnMap([['json', true]]); @@ -107,9 +105,9 @@ public function testJsonOutputIsValidArray(): void { } public function testTotalSizeCalculation(): void { - $this->connection->method('getDatabasePlatform') + $this->mocks[Connection::class]->method('getDatabasePlatform') ->willReturn($this->createMock(MySQLPlatform::class)); - $this->connection->method('executeQuery') + $this->mocks[Connection::class]->method('executeQuery') ->willReturn($this->mockResult($this->mockRows())); $this->input->method('getOption')->willReturnMap([['json', false]]); diff --git a/tests/Core/Command/Group/AddTest.php b/tests/Core/Command/Group/AddTest.php index 52186411c5254..7740240294e34 100644 --- a/tests/Core/Command/Group/AddTest.php +++ b/tests/Core/Command/Group/AddTest.php @@ -15,9 +15,6 @@ use Test\TestCase; class AddTest extends TestCase { - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; - /** @var Add */ private $command; @@ -30,9 +27,7 @@ class AddTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->groupManager = $this->createMock(IGroupManager::class); - $this->command = new Add($this->groupManager); + $this->command = $this->createInstanceWithMocks(Add::class); $this->input = $this->createMock(InputInterface::class); $this->input->method('getArgument') @@ -48,11 +43,11 @@ protected function setUp(): void { public function testGroupExists(): void { $gid = 'myGroup'; $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with($gid) ->willReturn($group); - $this->groupManager->expects($this->never()) + $this->mocks[IGroupManager::class]->expects($this->never()) ->method('createGroup'); $this->output->expects($this->once()) ->method('writeln') @@ -66,10 +61,10 @@ public function testAdd(): void { $group = $this->createMock(IGroup::class); $group->method('getGID') ->willReturn($gid); - $this->groupManager->method('createGroup') + $this->mocks[IGroupManager::class]->method('createGroup') ->willReturn($group); - $this->groupManager->expects($this->once()) + $this->mocks[IGroupManager::class]->expects($this->once()) ->method('createGroup') ->with($this->equalTo($gid)); $this->output->expects($this->once()) diff --git a/tests/Core/Command/Group/AddUserTest.php b/tests/Core/Command/Group/AddUserTest.php index 920e2994e3113..60854c2211e99 100644 --- a/tests/Core/Command/Group/AddUserTest.php +++ b/tests/Core/Command/Group/AddUserTest.php @@ -17,12 +17,6 @@ use Test\TestCase; class AddUserTest extends TestCase { - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; - - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - /** @var AddUser */ private $command; @@ -35,10 +29,7 @@ class AddUserTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->groupManager = $this->createMock(IGroupManager::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->command = new AddUser($this->userManager, $this->groupManager); + $this->command = $this->createInstanceWithMocks(AddUser::class); $this->output = $this->createMock(OutputInterface::class); } @@ -59,7 +50,7 @@ protected function configureInput(array|string $returnGroup, array|string $retur public function testNoGroup(): void { $this->configureInput('myGroup', 'myUser'); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn(null); @@ -74,11 +65,11 @@ public function testNoUser(): void { $this->configureInput('myGroup', 'myUser'); $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn($group); - $this->userManager->method('get') + $this->mocks[IUserManager::class]->method('get') ->with('myUser') ->willReturn(null); @@ -93,12 +84,12 @@ public function testAdd(): void { $this->configureInput('myGroup', 'myUser'); $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn($group); $user = $this->createMock(IUser::class); - $this->userManager->method('get') + $this->mocks[IUserManager::class]->method('get') ->with('myUser') ->willReturn($user); @@ -113,13 +104,13 @@ public function testAddMultiple(): void { $this->configureInput('myGroup', ['myUser', 'myOtherUser']); $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn($group); $user1 = $this->createMock(IUser::class); $user2 = $this->createMock(IUser::class); - $this->userManager->method('get') + $this->mocks[IUserManager::class]->method('get') ->willReturnMap([ ['myUser', $user1], ['myOtherUser', $user2], @@ -144,12 +135,12 @@ public function testAddMultiplePartialSuccess(): void { $this->configureInput('myGroup', ['myUser', 'myOtherUser']); $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn($group); $user = $this->createMock(IUser::class); - $this->userManager->method('get') + $this->mocks[IUserManager::class]->method('get') ->willReturnMap([ ['myUser', $user], ['myOtherUser', null], diff --git a/tests/Core/Command/Group/DeleteTest.php b/tests/Core/Command/Group/DeleteTest.php index 1778ec817b3ed..fa48b26a6debc 100644 --- a/tests/Core/Command/Group/DeleteTest.php +++ b/tests/Core/Command/Group/DeleteTest.php @@ -15,9 +15,6 @@ use Test\TestCase; class DeleteTest extends TestCase { - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; - /** @var Delete */ private $command; @@ -30,9 +27,7 @@ class DeleteTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->groupManager = $this->createMock(IGroupManager::class); - $this->command = new Delete($this->groupManager); + $this->command = $this->createInstanceWithMocks(Delete::class); $this->input = $this->createMock(InputInterface::class); $this->output = $this->createMock(OutputInterface::class); @@ -47,11 +42,11 @@ public function testDoesNotExists(): void { } throw new \Exception(); }); - $this->groupManager->method('groupExists') + $this->mocks[IGroupManager::class]->method('groupExists') ->with($gid) ->willReturn(false); - $this->groupManager->expects($this->never()) + $this->mocks[IGroupManager::class]->expects($this->never()) ->method('get'); $this->output->expects($this->once()) ->method('writeln') @@ -70,7 +65,7 @@ public function testDeleteAdmin(): void { throw new \Exception(); }); - $this->groupManager->expects($this->never()) + $this->mocks[IGroupManager::class]->expects($this->never()) ->method($this->anything()); $this->output->expects($this->once()) ->method('writeln') @@ -91,10 +86,10 @@ public function testDeleteFailed(): void { $group = $this->createMock(IGroup::class); $group->method('delete') ->willReturn(false); - $this->groupManager->method('groupExists') + $this->mocks[IGroupManager::class]->method('groupExists') ->with($gid) ->willReturn(true); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with($gid) ->willReturn($group); @@ -117,10 +112,10 @@ public function testDelete(): void { $group = $this->createMock(IGroup::class); $group->method('delete') ->willReturn(true); - $this->groupManager->method('groupExists') + $this->mocks[IGroupManager::class]->method('groupExists') ->with($gid) ->willReturn(true); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with($gid) ->willReturn($group); diff --git a/tests/Core/Command/Group/RemoveUserTest.php b/tests/Core/Command/Group/RemoveUserTest.php index 90ba3b3937a16..bbd319d632049 100644 --- a/tests/Core/Command/Group/RemoveUserTest.php +++ b/tests/Core/Command/Group/RemoveUserTest.php @@ -17,12 +17,6 @@ use Test\TestCase; class RemoveUserTest extends TestCase { - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - private $groupManager; - - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - /** @var RemoveUser */ private $command; @@ -35,10 +29,7 @@ class RemoveUserTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->groupManager = $this->createMock(IGroupManager::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->command = new RemoveUser($this->userManager, $this->groupManager); + $this->command = $this->createInstanceWithMocks(RemoveUser::class); $this->output = $this->createMock(OutputInterface::class); } @@ -59,7 +50,7 @@ protected function configureInput(array|string $returnGroup, array|string $retur public function testNoGroup(): void { $this->configureInput('myGroup', 'myUser'); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn(null); @@ -74,11 +65,11 @@ public function testNoUser(): void { $this->configureInput('myGroup', 'myUser'); $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn($group); - $this->userManager->method('get') + $this->mocks[IUserManager::class]->method('get') ->with('myUser') ->willReturn(null); @@ -93,12 +84,12 @@ public function testRemove(): void { $this->configureInput('myGroup', 'myUser'); $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn($group); $user = $this->createMock(IUser::class); - $this->userManager->method('get') + $this->mocks[IUserManager::class]->method('get') ->with('myUser') ->willReturn($user); @@ -113,13 +104,13 @@ public function testRemoveMultiple(): void { $this->configureInput('myGroup', ['myUser', 'myOtherUser']); $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn($group); $user1 = $this->createMock(IUser::class); $user2 = $this->createMock(IUser::class); - $this->userManager->method('get') + $this->mocks[IUserManager::class]->method('get') ->willReturnMap([ ['myUser', $user1], ['myOtherUser', $user2], @@ -144,12 +135,12 @@ public function testRemoveMultiplePartialSuccess(): void { $this->configureInput('myGroup', ['myUser', 'myOtherUser']); $group = $this->createMock(IGroup::class); - $this->groupManager->method('get') + $this->mocks[IGroupManager::class]->method('get') ->with('myGroup') ->willReturn($group); $user = $this->createMock(IUser::class); - $this->userManager->method('get') + $this->mocks[IUserManager::class]->method('get') ->willReturnMap([ ['myUser', $user], ['myOtherUser', null], diff --git a/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php b/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php index eda4c2fbc6577..71c2e268be0e5 100644 --- a/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php +++ b/tests/Core/Command/Maintenance/Mimetype/UpdateDBTest.php @@ -11,18 +11,11 @@ use OC\Core\Command\Maintenance\Mimetype\UpdateDB; use OC\Files\Type\Detection; use OC\Files\Type\Loader; -use OCP\Files\IMimeTypeDetector; -use OCP\Files\IMimeTypeLoader; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Test\TestCase; class UpdateDBTest extends TestCase { - /** @var IMimeTypeDetector */ - protected $detector; - /** @var IMimeTypeLoader */ - protected $loader; - /** @var \PHPUnit\Framework\MockObject\MockObject */ protected $consoleInput; /** @var \PHPUnit\Framework\MockObject\MockObject */ @@ -34,13 +27,10 @@ class UpdateDBTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->detector = $this->createMock(Detection::class); - $this->loader = $this->createMock(Loader::class); $this->consoleInput = $this->createMock(InputInterface::class); $this->consoleOutput = $this->createMock(OutputInterface::class); - $this->command = new UpdateDB($this->detector, $this->loader); + $this->command = $this->createInstanceWithMocks(UpdateDB::class); } public function testNoop(): void { @@ -48,17 +38,17 @@ public function testNoop(): void { ->with('repair-filecache') ->willReturn(false); - $this->detector->expects($this->once()) + $this->mocks[Detection::class]->expects($this->once()) ->method('getAllMappings') ->willReturn([ 'ext' => ['testing/existingmimetype'] ]); - $this->loader->expects($this->once()) + $this->mocks[Loader::class]->expects($this->once()) ->method('exists') ->with('testing/existingmimetype') ->willReturn(true); - $this->loader->expects($this->never()) + $this->mocks[Loader::class]->expects($this->never()) ->method('updateFilecache'); $calls = [ @@ -80,26 +70,26 @@ public function testAddMimetype(): void { ->with('repair-filecache') ->willReturn(false); - $this->detector->expects($this->once()) + $this->mocks[Detection::class]->expects($this->once()) ->method('getAllMappings') ->willReturn([ 'ext' => ['testing/existingmimetype'], 'new' => ['testing/newmimetype'] ]); - $this->loader->expects($this->exactly(2)) + $this->mocks[Loader::class]->expects($this->exactly(2)) ->method('exists') ->willReturnMap([ ['testing/existingmimetype', true], ['testing/newmimetype', false], ]); - $this->loader->expects($this->exactly(2)) + $this->mocks[Loader::class]->expects($this->exactly(2)) ->method('getId') ->willReturnMap([ ['testing/existingmimetype', 1], ['testing/newmimetype', 2], ]); - $this->loader->expects($this->once()) + $this->mocks[Loader::class]->expects($this->once()) ->method('updateFilecache') ->with('new', 2) ->willReturn(3); @@ -121,12 +111,12 @@ public function testAddMimetype(): void { } public function testSkipComments(): void { - $this->detector->expects($this->once()) + $this->mocks[Detection::class]->expects($this->once()) ->method('getAllMappings') ->willReturn([ '_comment' => 'some comment in the JSON' ]); - $this->loader->expects($this->never()) + $this->mocks[Loader::class]->expects($this->never()) ->method('exists'); self::invokePrivate($this->command, 'execute', [$this->consoleInput, $this->consoleOutput]); @@ -137,23 +127,23 @@ public function testRepairFilecache(): void { ->with('repair-filecache') ->willReturn(true); - $this->detector->expects($this->once()) + $this->mocks[Detection::class]->expects($this->once()) ->method('getAllMappings') ->willReturn([ 'ext' => ['testing/existingmimetype'], ]); - $this->loader->expects($this->exactly(1)) + $this->mocks[Loader::class]->expects($this->exactly(1)) ->method('exists') ->willReturnMap([ ['testing/existingmimetype', true], ]); - $this->loader->expects($this->exactly(1)) + $this->mocks[Loader::class]->expects($this->exactly(1)) ->method('getId') ->willReturnMap([ ['testing/existingmimetype', 1], ]); - $this->loader->expects($this->once()) + $this->mocks[Loader::class]->expects($this->once()) ->method('updateFilecache') ->with('ext', 1) ->willReturn(3); diff --git a/tests/Core/Command/Maintenance/UpdateTheme.php b/tests/Core/Command/Maintenance/UpdateTheme.php index 8774412b8ec24..792af3502fbc7 100644 --- a/tests/Core/Command/Maintenance/UpdateTheme.php +++ b/tests/Core/Command/Maintenance/UpdateTheme.php @@ -9,7 +9,6 @@ use OC\Core\Command\Maintenance\UpdateTheme; use OC\Files\Type\Detection; -use OCP\Files\IMimeTypeDetector; use OCP\ICache; use OCP\ICacheFactory; use Symfony\Component\Console\Input\InputInterface; @@ -17,11 +16,6 @@ use Test\TestCase; class UpdateThemeTest extends TestCase { - /** @var IMimeTypeDetector */ - protected $detector; - /** @var ICacheFactory */ - protected $cacheFactory; - /** @var \PHPUnit\Framework\MockObject\MockObject */ protected $consoleInput; /** @var \PHPUnit\Framework\MockObject\MockObject */ @@ -34,27 +28,24 @@ class UpdateThemeTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->detector = $this->createMock(Detection::class); - $this->cacheFactory = $this->createMock(ICacheFactory::class); - $this->consoleInput = $this->getMockBuilder(InputInterface::class)->getMock(); $this->consoleOutput = $this->getMockBuilder(OutputInterface::class)->getMock(); - $this->command = new UpdateTheme($this->detector, $this->cacheFactory); + $this->command = $this->createInstanceWithMocks(UpdateTheme::class); } public function testThemeUpdate(): void { $this->consoleInput->method('getOption') ->with('maintenance:theme:update') ->willReturn(true); - $this->detector->expects($this->once()) + $this->mocks[Detection::class]->expects($this->once()) ->method('getAllAliases') ->willReturn([]); $cache = $this->createMock(ICache::class); $cache->expects($this->once()) ->method('clear') ->with(''); - $this->cacheFactory->expects($this->once()) + $this->mocks[ICacheFactory::class]->expects($this->once()) ->method('createDistributed') ->with('imagePath') ->willReturn($cache); diff --git a/tests/Core/Command/Preview/CleanupTest.php b/tests/Core/Command/Preview/CleanupTest.php index f00b206ad4c9d..ad6e28d4edc12 100644 --- a/tests/Core/Command/Preview/CleanupTest.php +++ b/tests/Core/Command/Preview/CleanupTest.php @@ -20,31 +20,21 @@ use Test\TestCase; class CleanupTest extends TestCase { - private IRootFolder&MockObject $rootFolder; - private LoggerInterface&MockObject $logger; private InputInterface&MockObject $input; private OutputInterface&MockObject $output; - private PreviewService&MockObject $previewService; private Cleanup $repair; #[\Override] protected function setUp(): void { parent::setUp(); - $this->rootFolder = $this->createMock(IRootFolder::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->previewService = $this->createMock(PreviewService::class); - $this->repair = new Cleanup( - $this->rootFolder, - $this->logger, - $this->previewService, - ); + $this->repair = $this->createInstanceWithMocks(Cleanup::class); $this->input = $this->createMock(InputInterface::class); $this->output = $this->createMock(OutputInterface::class); } public function testCleanup(): void { - $this->previewService->expects($this->once())->method('deleteAll'); + $this->mocks[PreviewService::class]->expects($this->once())->method('deleteAll'); $previewFolder = $this->createMock(Folder::class); $previewFolder->expects($this->once()) @@ -57,11 +47,11 @@ public function testCleanup(): void { $appDataFolder = $this->createMock(Folder::class); $appDataFolder->expects($this->once())->method('get')->with('preview')->willReturn($previewFolder); - $this->rootFolder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('getAppDataDirectoryName') ->willReturn('appdata_some_id'); - $this->rootFolder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('get') ->with('appdata_some_id') ->willReturn($appDataFolder); @@ -90,16 +80,16 @@ public function testCleanupWhenNotDeletable(): void { $appDataFolder = $this->createMock(Folder::class); $appDataFolder->expects($this->once())->method('get')->with('preview')->willReturn($previewFolder); - $this->rootFolder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('getAppDataDirectoryName') ->willReturn('appdata_some_id'); - $this->rootFolder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('get') ->with('appdata_some_id') ->willReturn($appDataFolder); - $this->logger->expects($this->once())->method('error')->with("Previews can't be removed: preview folder isn't deletable"); + $this->mocks[LoggerInterface::class]->expects($this->once())->method('error')->with("Previews can't be removed: preview folder isn't deletable"); $this->output->expects($this->once())->method('writeln')->with("Previews can't be removed: preview folder isn't deletable"); $this->assertEquals(1, $this->repair->run($this->input, $this->output)); @@ -119,16 +109,16 @@ public function testCleanupWithDeleteException(string $exceptionClass, string $e $appDataFolder = $this->createMock(Folder::class); $appDataFolder->expects($this->once())->method('get')->with('preview')->willReturn($previewFolder); - $this->rootFolder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('getAppDataDirectoryName') ->willReturn('appdata_some_id'); - $this->rootFolder->expects($this->once()) + $this->mocks[IRootFolder::class]->expects($this->once()) ->method('get') ->with('appdata_some_id') ->willReturn($appDataFolder); - $this->logger->expects($this->once())->method('error')->with($errorMessage); + $this->mocks[LoggerInterface::class]->expects($this->once())->method('error')->with($errorMessage); $this->output->expects($this->once())->method('writeln')->with($errorMessage); $this->assertEquals(1, $this->repair->run($this->input, $this->output)); @@ -142,14 +132,14 @@ public static function dataForTestCleanupWithDeleteException(): array { } public function testCleanupWithPreviewServiceException(): void { - $this->rootFolder->method('getAppDataDirectoryName') + $this->mocks[IRootFolder::class]->method('getAppDataDirectoryName') ->willThrowException(new NotFoundException()); - $this->previewService->expects($this->once())->method('deleteAll') + $this->mocks[PreviewService::class]->expects($this->once())->method('deleteAll') ->willThrowException(new NotPermittedException('abc')); - $this->logger->expects($this->once())->method('info')->with("Legacy previews can't be removed: appdata folder can't be found"); - $this->logger->expects($this->once())->method('error')->with("Previews can't be removed: exception occurred: abc"); + $this->mocks[LoggerInterface::class]->expects($this->once())->method('info')->with("Legacy previews can't be removed: appdata folder can't be found"); + $this->mocks[LoggerInterface::class]->expects($this->once())->method('error')->with("Previews can't be removed: exception occurred: abc"); $this->assertEquals(1, $this->repair->run($this->input, $this->output)); } diff --git a/tests/Core/Command/TwoFactorAuth/CleanupTest.php b/tests/Core/Command/TwoFactorAuth/CleanupTest.php index 72436e90d391b..84bfe080ecb0a 100644 --- a/tests/Core/Command/TwoFactorAuth/CleanupTest.php +++ b/tests/Core/Command/TwoFactorAuth/CleanupTest.php @@ -11,18 +11,10 @@ use OC\Core\Command\TwoFactorAuth\Cleanup; use OCP\Authentication\TwoFactorAuth\IRegistry; -use OCP\IUserManager; -use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Tester\CommandTester; use Test\TestCase; class CleanupTest extends TestCase { - /** @var IRegistry|MockObject */ - private $registry; - - /** @var IUserManager|MockObject */ - private $userManager; - /** @var CommandTester */ private $cmd; @@ -30,15 +22,12 @@ class CleanupTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->registry = $this->createMock(IRegistry::class); - $this->userManager = $this->createMock(IUserManager::class); - - $cmd = new Cleanup($this->registry, $this->userManager); + $cmd = $this->createInstanceWithMocks(Cleanup::class); $this->cmd = new CommandTester($cmd); } public function testCleanup(): void { - $this->registry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('cleanUp') ->with('u2f'); diff --git a/tests/Core/Command/TwoFactorAuth/DisableTest.php b/tests/Core/Command/TwoFactorAuth/DisableTest.php index 4663d3785f7c6..e086cc8ac8bf9 100644 --- a/tests/Core/Command/TwoFactorAuth/DisableTest.php +++ b/tests/Core/Command/TwoFactorAuth/DisableTest.php @@ -13,17 +13,10 @@ use OC\Core\Command\TwoFactorAuth\Disable; use OCP\IUser; use OCP\IUserManager; -use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Tester\CommandTester; use Test\TestCase; class DisableTest extends TestCase { - /** @var ProviderManager|MockObject */ - private $providerManager; - - /** @var IUserManager|MockObject */ - private $userManager; - /** @var CommandTester */ private $command; @@ -31,15 +24,12 @@ class DisableTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->providerManager = $this->createMock(ProviderManager::class); - $this->userManager = $this->createMock(IUserManager::class); - - $cmd = new Disable($this->providerManager, $this->userManager); + $cmd = $this->createInstanceWithMocks(Disable::class); $this->command = new CommandTester($cmd); } public function testInvalidUID(): void { - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn(null); @@ -55,11 +45,11 @@ public function testInvalidUID(): void { public function testEnableNotSupported(): void { $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('ricky') ->willReturn($user); - $this->providerManager->expects($this->once()) + $this->mocks[ProviderManager::class]->expects($this->once()) ->method('tryDisableProviderFor') ->with('totp', $user) ->willReturn(false); @@ -75,11 +65,11 @@ public function testEnableNotSupported(): void { public function testEnabled(): void { $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('ricky') ->willReturn($user); - $this->providerManager->expects($this->once()) + $this->mocks[ProviderManager::class]->expects($this->once()) ->method('tryDisableProviderFor') ->with('totp', $user) ->willReturn(true); diff --git a/tests/Core/Command/TwoFactorAuth/EnableTest.php b/tests/Core/Command/TwoFactorAuth/EnableTest.php index 90859ffe1323b..5ac099cf133fc 100644 --- a/tests/Core/Command/TwoFactorAuth/EnableTest.php +++ b/tests/Core/Command/TwoFactorAuth/EnableTest.php @@ -13,17 +13,10 @@ use OC\Core\Command\TwoFactorAuth\Enable; use OCP\IUser; use OCP\IUserManager; -use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Tester\CommandTester; use Test\TestCase; class EnableTest extends TestCase { - /** @var ProviderManager|MockObject */ - private $providerManager; - - /** @var IUserManager|MockObject */ - private $userManager; - /** @var CommandTester */ private $command; @@ -31,15 +24,12 @@ class EnableTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->providerManager = $this->createMock(ProviderManager::class); - $this->userManager = $this->createMock(IUserManager::class); - - $cmd = new Enable($this->providerManager, $this->userManager); + $cmd = $this->createInstanceWithMocks(Enable::class); $this->command = new CommandTester($cmd); } public function testInvalidUID(): void { - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn(null); @@ -55,11 +45,11 @@ public function testInvalidUID(): void { public function testEnableNotSupported(): void { $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('belle') ->willReturn($user); - $this->providerManager->expects($this->once()) + $this->mocks[ProviderManager::class]->expects($this->once()) ->method('tryEnableProviderFor') ->with('totp', $user) ->willReturn(false); @@ -75,11 +65,11 @@ public function testEnableNotSupported(): void { public function testEnabled(): void { $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('belle') ->willReturn($user); - $this->providerManager->expects($this->once()) + $this->mocks[ProviderManager::class]->expects($this->once()) ->method('tryEnableProviderFor') ->with('totp', $user) ->willReturn(true); diff --git a/tests/Core/Command/TwoFactorAuth/EnforceTest.php b/tests/Core/Command/TwoFactorAuth/EnforceTest.php index 78804eb5e92f8..5a62a366ffa0a 100644 --- a/tests/Core/Command/TwoFactorAuth/EnforceTest.php +++ b/tests/Core/Command/TwoFactorAuth/EnforceTest.php @@ -12,32 +12,26 @@ use OC\Authentication\TwoFactorAuth\EnforcementState; use OC\Authentication\TwoFactorAuth\MandatoryTwoFactor; use OC\Core\Command\TwoFactorAuth\Enforce; -use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Tester\CommandTester; use Test\TestCase; class EnforceTest extends TestCase { - /** @var MandatoryTwoFactor|MockObject */ - private $mandatoryTwoFactor; - /** @var CommandTester */ private $command; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->mandatoryTwoFactor = $this->createMock(MandatoryTwoFactor::class); - $command = new Enforce($this->mandatoryTwoFactor); + $command = $this->createInstanceWithMocks(Enforce::class); $this->command = new CommandTester($command); } public function testEnforce(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('setState') ->with($this->equalTo(new EnforcementState(true))); - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('getState') ->willReturn(new EnforcementState(true)); @@ -51,10 +45,10 @@ public function testEnforce(): void { } public function testEnforceForOneGroup(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('setState') ->with($this->equalTo(new EnforcementState(true, ['twofactorers']))); - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('getState') ->willReturn(new EnforcementState(true, ['twofactorers'])); @@ -69,10 +63,10 @@ public function testEnforceForOneGroup(): void { } public function testEnforceForAllExceptOneGroup(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('setState') ->with($this->equalTo(new EnforcementState(true, [], ['yoloers']))); - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('getState') ->willReturn(new EnforcementState(true, [], ['yoloers'])); @@ -87,10 +81,10 @@ public function testEnforceForAllExceptOneGroup(): void { } public function testDisableEnforced(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('setState') ->with(new EnforcementState(false)); - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('getState') ->willReturn(new EnforcementState(false)); @@ -104,7 +98,7 @@ public function testDisableEnforced(): void { } public function testCurrentStateEnabled(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('getState') ->willReturn(new EnforcementState(true)); @@ -116,7 +110,7 @@ public function testCurrentStateEnabled(): void { } public function testCurrentStateDisabled(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('getState') ->willReturn(new EnforcementState(false)); diff --git a/tests/Core/Command/TwoFactorAuth/StateTest.php b/tests/Core/Command/TwoFactorAuth/StateTest.php index cb1dff02ec0cc..67255be2a6fb4 100644 --- a/tests/Core/Command/TwoFactorAuth/StateTest.php +++ b/tests/Core/Command/TwoFactorAuth/StateTest.php @@ -18,12 +18,6 @@ use Test\TestCase; class StateTest extends TestCase { - /** @var IRegistry|MockObject */ - private $registry; - - /** @var IUserManager|MockObject */ - private $userManager; - /** @var CommandTester|MockObject */ private $cmd; @@ -31,10 +25,7 @@ class StateTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->registry = $this->createMock(IRegistry::class); - $this->userManager = $this->createMock(IUserManager::class); - - $cmd = new State($this->registry, $this->userManager); + $cmd = $this->createInstanceWithMocks(State::class); $this->cmd = new CommandTester($cmd); } @@ -49,7 +40,7 @@ public function testWrongUID(): void { public function testStateNoProvidersActive(): void { $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('eldora') ->willReturn($user); @@ -57,7 +48,7 @@ public function testStateNoProvidersActive(): void { 'u2f' => false, 'totp' => false, ]; - $this->registry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->with($user) ->willReturn($states); @@ -72,7 +63,7 @@ public function testStateNoProvidersActive(): void { public function testStateOneProviderActive(): void { $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('mohamed') ->willReturn($user); @@ -80,7 +71,7 @@ public function testStateOneProviderActive(): void { 'u2f' => true, 'totp' => false, ]; - $this->registry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->with($user) ->willReturn($states); diff --git a/tests/Core/Command/User/DisableTest.php b/tests/Core/Command/User/DisableTest.php index 5f765a9bee971..8c5e5dd19a238 100644 --- a/tests/Core/Command/User/DisableTest.php +++ b/tests/Core/Command/User/DisableTest.php @@ -15,8 +15,6 @@ use Test\TestCase; class DisableTest extends TestCase { - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $userManager; /** @var InputInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $consoleInput; /** @var OutputInterface|\PHPUnit\Framework\MockObject\MockObject */ @@ -28,12 +26,10 @@ class DisableTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->userManager = $this->createMock(IUserManager::class); $this->consoleInput = $this->createMock(InputInterface::class); $this->consoleOutput = $this->createMock(OutputInterface::class); - $this->command = new Disable($this->userManager); + $this->command = $this->createInstanceWithMocks(Disable::class); } public function testValidUser(): void { @@ -42,7 +38,7 @@ public function testValidUser(): void { ->method('setEnabled') ->with(false); - $this->userManager + $this->mocks[IUserManager::class] ->method('get') ->with('user') ->willReturn($user); @@ -60,7 +56,7 @@ public function testValidUser(): void { } public function testInvalidUser(): void { - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('user') ->willReturn(null); diff --git a/tests/Core/Command/User/EnableTest.php b/tests/Core/Command/User/EnableTest.php index cf133015cd7c5..5a52ec1b52e8c 100644 --- a/tests/Core/Command/User/EnableTest.php +++ b/tests/Core/Command/User/EnableTest.php @@ -15,8 +15,6 @@ use Test\TestCase; class EnableTest extends TestCase { - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $userManager; /** @var InputInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $consoleInput; /** @var OutputInterface|\PHPUnit\Framework\MockObject\MockObject */ @@ -28,12 +26,10 @@ class EnableTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->userManager = $this->createMock(IUserManager::class); $this->consoleInput = $this->createMock(InputInterface::class); $this->consoleOutput = $this->createMock(OutputInterface::class); - $this->command = new Enable($this->userManager); + $this->command = $this->createInstanceWithMocks(Enable::class); } public function testValidUser(): void { @@ -42,7 +38,7 @@ public function testValidUser(): void { ->method('setEnabled') ->with(true); - $this->userManager + $this->mocks[IUserManager::class] ->method('get') ->with('user') ->willReturn($user); @@ -60,7 +56,7 @@ public function testValidUser(): void { } public function testInvalidUser(): void { - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('user') ->willReturn(null); diff --git a/tests/Core/Controller/WellKnownControllerTest.php b/tests/Core/Controller/WellKnownControllerTest.php index 98a1aa6e8cfe7..e65cb3d71bdee 100644 --- a/tests/Core/Controller/WellKnownControllerTest.php +++ b/tests/Core/Controller/WellKnownControllerTest.php @@ -14,16 +14,9 @@ use OCP\AppFramework\Http\JSONResponse; use OCP\Http\WellKnown\IResponse; use OCP\IRequest; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class WellKnownControllerTest extends TestCase { - /** @var IRequest|MockObject */ - private $request; - - /** @var RequestManager|MockObject */ - private $manager; - /** @var WellKnownController */ private $controller; @@ -31,13 +24,7 @@ class WellKnownControllerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->request = $this->createMock(IRequest::class); - $this->manager = $this->createMock(RequestManager::class); - - $this->controller = new WellKnownController( - $this->request, - $this->manager, - ); + $this->controller = $this->createInstanceWithMocks(WellKnownController::class); } public function testHandleNotProcessed(): void { @@ -53,11 +40,11 @@ public function testHandle(): void { $response->expects(self::once()) ->method('toHttpResponse') ->willReturn($jsonResponse); - $this->manager->expects(self::once()) + $this->mocks[RequestManager::class]->expects(self::once()) ->method('process') ->with( 'nodeinfo', - $this->request + $this->mocks[IRequest::class] )->willReturn($response); $jsonResponse->expects(self::once()) ->method('addHeader') diff --git a/tests/Core/Listener/AvatarVersionListenerTest.php b/tests/Core/Listener/AvatarVersionListenerTest.php index 4580d5421cab2..a4e08a0fc4436 100644 --- a/tests/Core/Listener/AvatarVersionListenerTest.php +++ b/tests/Core/Listener/AvatarVersionListenerTest.php @@ -14,25 +14,21 @@ use OCP\EventDispatcher\Event; use OCP\IUser; use OCP\User\Events\UserChangedEvent; -use PHPUnit\Framework\MockObject\MockObject; class AvatarVersionListenerTest extends \Test\TestCase { - private IUserConfig&MockObject $userConfig; private AvatarVersionListener $listener; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->userConfig = $this->createMock(IUserConfig::class); - $this->listener = new AvatarVersionListener($this->userConfig); + $this->listener = $this->createInstanceWithMocks(AvatarVersionListener::class); } public function testBumpsTheVersionWhenTheAccountChanges(): void { $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('alice'); - $this->userConfig->expects($this->once())->method('setValueInt') + $this->mocks[IUserConfig::class]->expects($this->once())->method('setValueInt') ->with('alice', 'avatar', 'version', 1); $this->listener->handle(new UserUpdatedEvent($user, [])); @@ -42,7 +38,7 @@ public function testBumpsTheVersionWhenTheAccountIsDisabled(): void { $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('alice'); - $this->userConfig->expects($this->once())->method('setValueInt') + $this->mocks[IUserConfig::class]->expects($this->once())->method('setValueInt') ->with('alice', 'avatar', 'version', 1); $this->listener->handle(new UserChangedEvent($user, 'enabled', false, true)); @@ -51,13 +47,13 @@ public function testBumpsTheVersionWhenTheAccountIsDisabled(): void { public function testIgnoresUnrelatedUserChanges(): void { $user = $this->createMock(IUser::class); - $this->userConfig->expects($this->never())->method('setValueInt'); + $this->mocks[IUserConfig::class]->expects($this->never())->method('setValueInt'); $this->listener->handle(new UserChangedEvent($user, 'quota', '1 GB', '2 GB')); } public function testIgnoresOtherEvents(): void { - $this->userConfig->expects($this->never())->method('setValueInt'); + $this->mocks[IUserConfig::class]->expects($this->never())->method('setValueInt'); $this->listener->handle(new Event()); } diff --git a/tests/lib/App/AppStore/AppStoreLinkVisibilityTest.php b/tests/lib/App/AppStore/AppStoreLinkVisibilityTest.php index 2bed8c32f4e33..83d30bc218e8c 100644 --- a/tests/lib/App/AppStore/AppStoreLinkVisibilityTest.php +++ b/tests/lib/App/AppStore/AppStoreLinkVisibilityTest.php @@ -17,28 +17,16 @@ use OCP\IConfig; use OCP\Support\Subscription\IRegistry; use PHPUnit\Framework\Attributes\DataProvider; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class AppStoreLinkVisibilityTest extends TestCase { - private IConfig&MockObject $config; - private IAppConfig&MockObject $appConfig; - private IRegistry&MockObject $registry; private AppStoreLinkVisibility $visibility; #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->appConfig = $this->createMock(IAppConfig::class); - $this->registry = $this->createMock(IRegistry::class); - - $this->visibility = new AppStoreLinkVisibility( - $this->config, - $this->appConfig, - $this->registry, - ); + $this->visibility = $this->createInstanceWithMocks(AppStoreLinkVisibility::class); } /** @@ -46,16 +34,16 @@ protected function setUp(): void { * @param bool $value the stored value, or the lexicon default when $stored is false */ private function arrange(bool $stored, bool $value, bool $appStoreEnabled, bool $subscription): void { - $this->appConfig->method('hasKey') + $this->mocks[IAppConfig::class]->method('hasKey') ->with('core', ConfigLexicon::APPSTORE_LINK_SHOWN) ->willReturn($stored); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->with('core', ConfigLexicon::APPSTORE_LINK_SHOWN) ->willReturn($value); - $this->config->method('getSystemValueBool') + $this->mocks[IConfig::class]->method('getSystemValueBool') ->with('appstoreenabled', true) ->willReturn($appStoreEnabled); - $this->registry->method('delegateHasValidSubscription') + $this->mocks[IRegistry::class]->method('delegateHasValidSubscription') ->willReturn($subscription); } diff --git a/tests/lib/AppFramework/Bootstrap/BootContextTest.php b/tests/lib/AppFramework/Bootstrap/BootContextTest.php index 9eb3b22c01e76..07d32ea04ad48 100644 --- a/tests/lib/AppFramework/Bootstrap/BootContextTest.php +++ b/tests/lib/AppFramework/Bootstrap/BootContextTest.php @@ -12,37 +12,27 @@ use OC\AppFramework\Bootstrap\BootContext; use OC\Server; use OCP\AppFramework\IAppContainer; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class BootContextTest extends TestCase { - private IAppContainer&MockObject $appContainer; - private Server&MockObject $server; - private BootContext $context; #[\Override] protected function setUp(): void { parent::setUp(); - $this->server = $this->createMock(Server::class); - $this->appContainer = $this->createMock(IAppContainer::class); - - $this->context = new BootContext( - $this->server, - $this->appContainer, - ); + $this->context = $this->createInstanceWithMocks(BootContext::class); } public function testGetAppContainer(): void { $container = $this->context->getAppContainer(); - $this->assertSame($this->appContainer, $container); + $this->assertSame($this->mocks[IAppContainer::class], $container); } public function testGetServerContainer(): void { $container = $this->context->getServerContainer(); - $this->assertSame($this->server, $container); + $this->assertSame($this->mocks[Server::class], $container); } } diff --git a/tests/lib/AppFramework/Bootstrap/CoordinatorTest.php b/tests/lib/AppFramework/Bootstrap/CoordinatorTest.php index b9b82235bda4d..0bb5208bb8f92 100644 --- a/tests/lib/AppFramework/Bootstrap/CoordinatorTest.php +++ b/tests/lib/AppFramework/Bootstrap/CoordinatorTest.php @@ -12,65 +12,36 @@ use OC\App\AppManager; use OC\AppFramework\Bootstrap\Coordinator; use OC\Server; -use OC\Support\CrashReport\Registry; use OCA\Settings\AppInfo\Application; use OCP\AppFramework\App; use OCP\AppFramework\Bootstrap\IBootContext; use OCP\AppFramework\Bootstrap\IBootstrap; use OCP\AppFramework\Bootstrap\IRegistrationContext; use OCP\AppFramework\QueryException; -use OCP\Dashboard\IManager; -use OCP\Diagnostics\IEventLogger; -use OCP\EventDispatcher\IEventDispatcher; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class CoordinatorTest extends TestCase { - private AppManager&MockObject $appManager; - private Server&MockObject $serverContainer; - private Registry&MockObject $crashReporterRegistry; - private IManager&MockObject $dashboardManager; - private IEventDispatcher&MockObject $eventDispatcher; - private IEventLogger&MockObject $eventLogger; - private LoggerInterface&MockObject $logger; private Coordinator $coordinator; #[\Override] protected function setUp(): void { parent::setUp(); - $this->appManager = $this->createMock(AppManager::class); - $this->serverContainer = $this->createMock(Server::class); - $this->crashReporterRegistry = $this->createMock(Registry::class); - $this->dashboardManager = $this->createMock(IManager::class); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->eventLogger = $this->createMock(IEventLogger::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->appManager->expects($this->any()) + $this->coordinator = $this->createInstanceWithMocks(Coordinator::class); + $this->mocks[AppManager::class]->expects($this->any()) ->method('getAppNamespace') ->with('settings') ->willReturn('OCA\\Settings'); - - $this->coordinator = new Coordinator( - $this->serverContainer, - $this->crashReporterRegistry, - $this->dashboardManager, - $this->eventDispatcher, - $this->eventLogger, - $this->appManager, - $this->logger, - ); } public function testBootAppNotLoadable(): void { $appId = 'settings'; - $this->serverContainer->expects($this->once()) + $this->mocks[Server::class]->expects($this->once()) ->method('get') ->with(Application::class) ->willThrowException(new QueryException('')); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('error'); $this->coordinator->bootApp($appId); @@ -79,7 +50,7 @@ public function testBootAppNotLoadable(): void { public function testBootAppNotBootable(): void { $appId = 'settings'; $mockApp = $this->createMock(Application::class); - $this->serverContainer->expects($this->once()) + $this->mocks[Server::class]->expects($this->once()) ->method('get') ->with(Application::class) ->willReturn($mockApp); @@ -102,7 +73,7 @@ public function register(IRegistrationContext $context): void { public function boot(IBootContext $context): void { } }; - $this->serverContainer->expects($this->once()) + $this->mocks[Server::class]->expects($this->once()) ->method('get') ->with(Application::class) ->willReturn($mockApp); diff --git a/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php b/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php index 665bc2d825ce8..c298ef796302c 100644 --- a/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php +++ b/tests/lib/AppFramework/Bootstrap/RegistrationContextTest.php @@ -15,23 +15,17 @@ use OC\Core\Middleware\TwoFactorMiddleware; use OCP\AppFramework\App; use OCP\EventDispatcher\IEventDispatcher; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class RegistrationContextTest extends TestCase { - private LoggerInterface&MockObject $logger; private RegistrationContext $context; #[\Override] protected function setUp(): void { parent::setUp(); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->context = new RegistrationContext( - $this->logger - ); + $this->context = $this->createInstanceWithMocks(RegistrationContext::class); } public function testRegisterCapability(): void { @@ -43,7 +37,7 @@ public function testRegisterCapability(): void { $container->expects($this->once()) ->method('registerCapability') ->with($name); - $this->logger->expects($this->never()) + $this->mocks[LoggerInterface::class]->expects($this->never()) ->method('error'); $this->context->for('myapp')->registerCapability($name); @@ -59,7 +53,7 @@ public function testRegisterEventListener(): void { $dispatcher->expects($this->once()) ->method('addServiceListener') ->with($event, $service, 0); - $this->logger->expects($this->never()) + $this->mocks[LoggerInterface::class]->expects($this->never()) ->method('error'); $this->context->for('myapp')->registerEventListener($event, $service); @@ -79,7 +73,7 @@ public function testRegisterService(bool $shared): void { $container->expects($this->once()) ->method('registerService') ->with($service, $factory, $shared); - $this->logger->expects($this->never()) + $this->mocks[LoggerInterface::class]->expects($this->never()) ->method('error'); $this->context->for('myapp')->registerService($service, $factory, $shared); @@ -98,7 +92,7 @@ public function testRegisterServiceAlias(): void { $container->expects($this->once()) ->method('registerAlias') ->with($alias, $target); - $this->logger->expects($this->never()) + $this->mocks[LoggerInterface::class]->expects($this->never()) ->method('error'); $this->context->for('myapp')->registerServiceAlias($alias, $target); @@ -117,7 +111,7 @@ public function testRegisterParameter(): void { $container->expects($this->once()) ->method('registerParameter') ->with($name, $value); - $this->logger->expects($this->never()) + $this->mocks[LoggerInterface::class]->expects($this->never()) ->method('error'); $this->context->for('myapp')->registerParameter($name, $value); diff --git a/tests/lib/AppFramework/Http/FileDisplayResponseTest.php b/tests/lib/AppFramework/Http/FileDisplayResponseTest.php index 82b8263616e70..9f72ceaf6113d 100644 --- a/tests/lib/AppFramework/Http/FileDisplayResponseTest.php +++ b/tests/lib/AppFramework/Http/FileDisplayResponseTest.php @@ -14,28 +14,24 @@ use OCP\AppFramework\Http\IOutput; use OCP\Files\File; use OCP\Files\SimpleFS\ISimpleFile; -use PHPUnit\Framework\MockObject\MockObject; class FileDisplayResponseTest extends \Test\TestCase { - private File&MockObject $file; private FileDisplayResponse $response; #[\Override] protected function setUp(): void { parent::setUp(); - $this->file = $this->createMock(File::class); - $this->file->expects($this->once()) + $this->response = $this->createInstanceWithMocks(FileDisplayResponse::class); + $this->mocks[File::class]->expects($this->once()) ->method('getETag') ->willReturn('myETag'); - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('getName') ->willReturn('myFileName'); - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('getMTime') ->willReturn(1464825600); - - $this->response = new FileDisplayResponse($this->file); } public function testHeader(): void { @@ -64,7 +60,7 @@ public function test304(): void { ->willReturn(Http::STATUS_NOT_MODIFIED); $output->expects($this->never()) ->method('setOutput'); - $this->file->expects($this->never()) + $this->mocks[File::class]->expects($this->never()) ->method('getContent'); $this->response->callback($output); @@ -75,10 +71,10 @@ public function testNon304(): void { fwrite($resource, 'my data'); rewind($resource); - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('fopen') ->willReturn($resource); - $this->file->expects($this->any()) + $this->mocks[File::class]->expects($this->any()) ->method('getSize') ->willReturn(7); @@ -99,7 +95,7 @@ public function testNon304(): void { } public function testFileNotFound(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('fopen') ->willReturn(false); diff --git a/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php b/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php index b05f38debefa9..6970b39ca8c7e 100644 --- a/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/AdditionalScriptsMiddlewareTest.php @@ -17,56 +17,44 @@ use OCP\AppFramework\PublicShareController; use OCP\EventDispatcher\IEventDispatcher; use OCP\IUserSession; -use PHPUnit\Framework\MockObject\MockObject; class AdditionalScriptsMiddlewareTest extends \Test\TestCase { - /** @var IUserSession|MockObject */ - private $userSession; - /** @var Controller */ private $controller; /** @var AdditionalScriptsMiddleware */ private $middleWare; - /** @var IEventDispatcher|MockObject */ - private $dispatcher; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->userSession = $this->createMock(IUserSession::class); - $this->dispatcher = $this->createMock(IEventDispatcher::class); - $this->middleWare = new AdditionalScriptsMiddleware( - $this->userSession, - $this->dispatcher - ); + $this->middleWare = $this->createInstanceWithMocks(AdditionalScriptsMiddleware::class); $this->controller = $this->createMock(Controller::class); } public function testNoTemplateResponse(): void { - $this->userSession->expects($this->never()) + $this->mocks[IUserSession::class]->expects($this->never()) ->method($this->anything()); - $this->dispatcher->expects($this->never()) + $this->mocks[IEventDispatcher::class]->expects($this->never()) ->method($this->anything()); $this->middleWare->afterController($this->controller, 'myMethod', $this->createMock(Response::class)); } public function testPublicShareController(): void { - $this->userSession->expects($this->never()) + $this->mocks[IUserSession::class]->expects($this->never()) ->method($this->anything()); - $this->dispatcher->expects($this->never()) + $this->mocks[IEventDispatcher::class]->expects($this->never()) ->method($this->anything()); $this->middleWare->afterController($this->createMock(PublicShareController::class), 'myMethod', $this->createMock(Response::class)); } public function testStandaloneTemplateResponse(): void { - $this->userSession->expects($this->never()) + $this->mocks[IUserSession::class]->expects($this->never()) ->method($this->anything()); - $this->dispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->willReturnCallback(function ($event): void { if ($event instanceof BeforeTemplateRenderedEvent && $event->isLoggedIn() === false) { @@ -80,9 +68,9 @@ public function testStandaloneTemplateResponse(): void { } public function testTemplateResponseNotLoggedIn(): void { - $this->userSession->method('isLoggedIn') + $this->mocks[IUserSession::class]->method('isLoggedIn') ->willReturn(false); - $this->dispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->willReturnCallback(function ($event): void { if ($event instanceof BeforeTemplateRenderedEvent && $event->isLoggedIn() === false) { @@ -98,9 +86,9 @@ public function testTemplateResponseNotLoggedIn(): void { public function testTemplateResponseLoggedIn(): void { $events = []; - $this->userSession->method('isLoggedIn') + $this->mocks[IUserSession::class]->method('isLoggedIn') ->willReturn(true); - $this->dispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->willReturnCallback(function ($event): void { if ($event instanceof BeforeTemplateRenderedEvent && $event->isLoggedIn() === true) { diff --git a/tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php b/tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php index 7eff769b19061..b8771b2e085ca 100644 --- a/tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/CompressionMiddlewareTest.php @@ -18,8 +18,6 @@ use OCP\IRequest; class CompressionMiddlewareTest extends \Test\TestCase { - /** @var IRequest */ - private $request; /** @var Controller */ private $controller; /** @var CompressionMiddleware */ @@ -28,17 +26,13 @@ class CompressionMiddlewareTest extends \Test\TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->request = $this->createMock(IRequest::class); - $this->middleWare = new CompressionMiddleware( - $this->request - ); + $this->middleWare = $this->createInstanceWithMocks(CompressionMiddleware::class); $this->controller = $this->createMock(Controller::class); } public function testGzipOCSV1(): void { - $this->request->method('getHeader') + $this->mocks[IRequest::class]->method('getHeader') ->with('Accept-Encoding') ->willReturn('gzip'); @@ -60,7 +54,7 @@ public function testGzipOCSV1(): void { } public function testGzipOCSV2(): void { - $this->request->method('getHeader') + $this->mocks[IRequest::class]->method('getHeader') ->with('Accept-Encoding') ->willReturn('gzip'); @@ -82,7 +76,7 @@ public function testGzipOCSV2(): void { } public function testGzipJSONResponse(): void { - $this->request->method('getHeader') + $this->mocks[IRequest::class]->method('getHeader') ->with('Accept-Encoding') ->willReturn('gzip'); @@ -104,7 +98,7 @@ public function testGzipJSONResponse(): void { } public function testNoGzipDataResponse(): void { - $this->request->method('getHeader') + $this->mocks[IRequest::class]->method('getHeader') ->with('Accept-Encoding') ->willReturn('gzip'); @@ -124,7 +118,7 @@ public function testNoGzipDataResponse(): void { } public function testNoGzipNo200(): void { - $this->request->method('getHeader') + $this->mocks[IRequest::class]->method('getHeader') ->with('Accept-Encoding') ->willReturn('gzip'); diff --git a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php index fbdbaca1bd8c5..a023b02729153 100644 --- a/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/NotModifiedMiddlewareTest.php @@ -16,8 +16,6 @@ use OCP\IRequest; class NotModifiedMiddlewareTest extends \Test\TestCase { - /** @var IRequest */ - private $request; /** @var Controller */ private $controller; /** @var NotModifiedMiddleware */ @@ -26,11 +24,7 @@ class NotModifiedMiddlewareTest extends \Test\TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->request = $this->createMock(IRequest::class); - $this->middleWare = new NotModifiedMiddleware( - $this->request - ); + $this->middleWare = $this->createInstanceWithMocks(NotModifiedMiddleware::class); $this->controller = $this->createMock(Controller::class); } @@ -58,7 +52,7 @@ public static function dataModified(): array { #[\PHPUnit\Framework\Attributes\DataProvider('dataModified')] public function testMiddleware(?string $etag, string $etagHeader, ?\DateTime $lastModified, string $lastModifiedHeader, bool $notModifiedSet): void { - $this->request->method('getHeader') + $this->mocks[IRequest::class]->method('getHeader') ->willReturnCallback(function (string $name) use ($etagHeader, $lastModifiedHeader) { if ($name === 'IF_NONE_MATCH') { return $etagHeader; diff --git a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php index 7a32aa33b2f34..23cc5dfc09fd4 100644 --- a/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/PublicShare/PublicShareMiddlewareTest.php @@ -22,31 +22,15 @@ use OCP\IRequest; use OCP\ISession; use OCP\IURLGenerator; -use OCP\Security\Bruteforce\IThrottler; -use PHPUnit\Framework\MockObject\MockObject; class PublicShareMiddlewareTest extends \Test\TestCase { - private IRequest&MockObject $request; - private ISession&MockObject $session; - private IAppConfig&MockObject $appConfig; - private IThrottler&MockObject $throttler; private PublicShareMiddleware $middleware; #[\Override] protected function setUp(): void { parent::setUp(); - $this->request = $this->createMock(IRequest::class); - $this->session = $this->createMock(ISession::class); - $this->appConfig = $this->createMock(IAppConfig::class); - $this->throttler = $this->createMock(IThrottler::class); - - $this->middleware = new PublicShareMiddleware( - $this->request, - $this->session, - $this->appConfig, - $this->throttler - ); + $this->middleware = $this->createInstanceWithMocks(PublicShareMiddleware::class); } #[\PHPUnit\Framework\Attributes\DoesNotPerformAssertions] @@ -68,7 +52,7 @@ public static function dataShareApi(): array { public function testBeforeControllerShareApiDisabled(bool $shareApi, bool $shareLinks): void { $controller = $this->createMock(PublicShareController::class); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->willReturnMap([ ['core', 'shareapi_enabled', true, $shareApi], ['core', 'shareapi_allow_links', true, $shareLinks], @@ -81,7 +65,7 @@ public function testBeforeControllerShareApiDisabled(bool $shareApi, bool $share public function testBeforeControllerNoTokenParam(): void { $controller = $this->createMock(PublicShareController::class); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->willReturnMap([ ['core', 'shareapi_enabled', true, true], ['core', 'shareapi_allow_links', true, true], @@ -94,13 +78,13 @@ public function testBeforeControllerNoTokenParam(): void { public function testBeforeControllerInvalidToken(): void { $controller = $this->createMock(PublicShareController::class); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->willReturnMap([ ['core', 'shareapi_enabled', true, true], ['core', 'shareapi_allow_links', true, true], ]); - $this->request->method('getParam') + $this->mocks[IRequest::class]->method('getParam') ->with('token', null) ->willReturn('myToken'); @@ -115,16 +99,16 @@ public function testBeforeControllerInvalidToken(): void { public function testBeforeControllerValidTokenNotAuthenticated(): void { $controller = $this->getMockBuilder(PublicShareController::class) - ->setConstructorArgs(['app', $this->request, $this->session]) + ->setConstructorArgs(['app', $this->mocks[IRequest::class], $this->mocks[ISession::class]]) ->getMock(); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->willReturnMap([ ['core', 'shareapi_enabled', true, true], ['core', 'shareapi_allow_links', true, true], ]); - $this->request->method('getParam') + $this->mocks[IRequest::class]->method('getParam') ->with('token', null) ->willReturn('myToken'); @@ -140,16 +124,16 @@ public function testBeforeControllerValidTokenNotAuthenticated(): void { public function testBeforeControllerValidTokenAuthenticateMethod(): void { $controller = $this->getMockBuilder(PublicShareController::class) - ->setConstructorArgs(['app', $this->request, $this->session]) + ->setConstructorArgs(['app', $this->mocks[IRequest::class], $this->mocks[ISession::class]]) ->getMock(); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->willReturnMap([ ['core', 'shareapi_enabled', true, true], ['core', 'shareapi_allow_links', true, true], ]); - $this->request->method('getParam') + $this->mocks[IRequest::class]->method('getParam') ->with('token', null) ->willReturn('myToken'); @@ -162,16 +146,16 @@ public function testBeforeControllerValidTokenAuthenticateMethod(): void { public function testBeforeControllerValidTokenShowAuthenticateMethod(): void { $controller = $this->getMockBuilder(PublicShareController::class) - ->setConstructorArgs(['app', $this->request, $this->session]) + ->setConstructorArgs(['app', $this->mocks[IRequest::class], $this->mocks[ISession::class]]) ->getMock(); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->willReturnMap([ ['core', 'shareapi_enabled', true, true], ['core', 'shareapi_allow_links', true, true], ]); - $this->request->method('getParam') + $this->mocks[IRequest::class]->method('getParam') ->with('token', null) ->willReturn('myToken'); @@ -184,16 +168,16 @@ public function testBeforeControllerValidTokenShowAuthenticateMethod(): void { public function testBeforeControllerAuthPublicShareController(): void { $controller = $this->getMockBuilder(AuthPublicShareController::class) - ->setConstructorArgs(['app', $this->request, $this->session, $this->createMock(IURLGenerator::class)]) + ->setConstructorArgs(['app', $this->mocks[IRequest::class], $this->mocks[ISession::class], $this->createMock(IURLGenerator::class)]) ->getMock(); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->willReturnMap([ ['core', 'shareapi_enabled', true, true], ['core', 'shareapi_allow_links', true, true], ]); - $this->request->method('getParam') + $this->mocks[IRequest::class]->method('getParam') ->with('token', null) ->willReturn('myToken'); @@ -203,7 +187,7 @@ public function testBeforeControllerAuthPublicShareController(): void { $controller->method('isPasswordProtected') ->willReturn(true); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('set') ->with('public_link_authenticate_redirect', '[]'); @@ -246,15 +230,15 @@ public function testAfterExceptionAuthPublicShareController(): void { $controller = $this->getMockBuilder(AuthPublicShareController::class) ->setConstructorArgs([ 'app', - $this->request, - $this->session, + $this->mocks[IRequest::class], + $this->mocks[ISession::class], $this->createMock(IURLGenerator::class), ])->getMock(); $controller->setToken('token'); $exception = new NeedAuthenticationException(); - $this->request->method('getParam') + $this->mocks[IRequest::class]->method('getParam') ->with('_route') ->willReturn('my.route'); diff --git a/tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php index cffbf06233060..2eb78f0cddd5b 100644 --- a/tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/CSPMiddlewareTest.php @@ -22,26 +22,17 @@ class CSPMiddlewareTest extends \Test\TestCase { private $middleware; /** @var Controller&MockObject */ private $controller; - /** @var ContentSecurityPolicyManager&MockObject */ - private $contentSecurityPolicyManager; - /** @var ContentSecurityPolicyNonceManager&MockObject */ - private $cspNonceManager; #[\Override] protected function setUp(): void { parent::setUp(); $this->controller = $this->createMock(Controller::class); - $this->contentSecurityPolicyManager = $this->createMock(ContentSecurityPolicyManager::class); - $this->cspNonceManager = $this->createMock(ContentSecurityPolicyNonceManager::class); - $this->middleware = new CSPMiddleware( - $this->contentSecurityPolicyManager, - $this->cspNonceManager, - ); + $this->middleware = $this->createInstanceWithMocks(CSPMiddleware::class); } public function testAfterController(): void { - $this->cspNonceManager + $this->mocks[ContentSecurityPolicyNonceManager::class] ->expects($this->once()) ->method('browserSupportsCspV3') ->willReturn(false); @@ -56,11 +47,11 @@ public function testAfterController(): void { ->expects($this->exactly(2)) ->method('getContentSecurityPolicy') ->willReturn($currentPolicy); - $this->contentSecurityPolicyManager + $this->mocks[ContentSecurityPolicyManager::class] ->expects($this->once()) ->method('getDefaultPolicy') ->willReturn($defaultPolicy); - $this->contentSecurityPolicyManager + $this->mocks[ContentSecurityPolicyManager::class] ->expects($this->once()) ->method('mergePolicies') ->with($defaultPolicy, $currentPolicy) @@ -85,12 +76,12 @@ public function testAfterControllerEmptyCSP(): void { } public function testAfterControllerWithContentSecurityPolicy3Support(): void { - $this->cspNonceManager + $this->mocks[ContentSecurityPolicyNonceManager::class] ->expects($this->once()) ->method('browserSupportsCspV3') ->willReturn(true); $token = base64_encode('the-nonce'); - $this->cspNonceManager + $this->mocks[ContentSecurityPolicyNonceManager::class] ->expects($this->once()) ->method('getNonce') ->willReturn($token); @@ -105,11 +96,11 @@ public function testAfterControllerWithContentSecurityPolicy3Support(): void { ->expects($this->exactly(2)) ->method('getContentSecurityPolicy') ->willReturn($currentPolicy); - $this->contentSecurityPolicyManager + $this->mocks[ContentSecurityPolicyManager::class] ->expects($this->once()) ->method('getDefaultPolicy') ->willReturn($defaultPolicy); - $this->contentSecurityPolicyManager + $this->mocks[ContentSecurityPolicyManager::class] ->expects($this->once()) ->method('mergePolicies') ->with($defaultPolicy, $currentPolicy) diff --git a/tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php index 122c7bbf56a72..ede543c2a7188 100644 --- a/tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/FeaturePolicyMiddlewareTest.php @@ -21,18 +21,13 @@ class FeaturePolicyMiddlewareTest extends \Test\TestCase { private $middleware; /** @var Controller|MockObject */ private $controller; - /** @var FeaturePolicyManager|MockObject */ - private $manager; #[\Override] protected function setUp(): void { parent::setUp(); $this->controller = $this->createMock(Controller::class); - $this->manager = $this->createMock(FeaturePolicyManager::class); - $this->middleware = new FeaturePolicyMiddleware( - $this->manager - ); + $this->middleware = $this->createInstanceWithMocks(FeaturePolicyMiddleware::class); } public function testAfterController(): void { @@ -45,9 +40,9 @@ public function testAfterController(): void { $mergedPolicy->addAllowedGeoLocationDomain('mergedPolicy'); $response->method('getFeaturePolicy') ->willReturn($currentPolicy); - $this->manager->method('getDefaultPolicy') + $this->mocks[FeaturePolicyManager::class]->method('getDefaultPolicy') ->willReturn($defaultPolicy); - $this->manager->method('mergePolicies') + $this->mocks[FeaturePolicyManager::class]->method('mergePolicies') ->with($defaultPolicy, $currentPolicy) ->willReturn($mergedPolicy); $response->expects($this->once()) diff --git a/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php b/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php index 08691f6b4b27c..d404040099494 100644 --- a/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php +++ b/tests/lib/AppFramework/Middleware/Security/SameSiteCookieMiddlewareTest.php @@ -35,77 +35,72 @@ public function foo(): Response { class SameSiteCookieMiddlewareTest extends TestCase { private SameSiteCookieMiddleware $middleware; - private Request&MockObject $request; - private ControllerMethodReflector&MockObject $reflector; private LoggerInterface&MockObject $logger; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->request = $this->createMock(Request::class); $this->logger = $this->createMock(LoggerInterface::class); - $this->reflector = $this->createMock(ControllerMethodReflector::class); - $this->middleware = new SameSiteCookieMiddleware($this->request, $this->reflector); + $this->middleware = $this->createInstanceWithMocks(SameSiteCookieMiddleware::class); } #[\PHPUnit\Framework\Attributes\DoesNotPerformAssertions] public function testBeforeControllerNoIndex(): void { - $this->request->method('getScriptName') + $this->mocks[Request::class]->method('getScriptName') ->willReturn('/ocs/v2.php'); - $this->middleware->beforeController(new NoAnnotationController('foo', $this->request), 'foo'); + $this->middleware->beforeController(new NoAnnotationController('foo', $this->mocks[Request::class]), 'foo'); } public function testBeforeControllerIndexHasAnnotation(): void { - $this->request->method('getScriptName') + $this->mocks[Request::class]->method('getScriptName') ->willReturn('/index.php'); - $this->reflector->expects(self::once()) + $this->mocks[ControllerMethodReflector::class]->expects(self::once()) ->method('hasAnnotationOrAttribute') ->with('NoSameSiteCookieRequired', NoSameSiteCookieRequired::class) ->willReturn(true); - $this->middleware->beforeController(new HasAnnotationController('foo', $this->request), 'foo'); + $this->middleware->beforeController(new HasAnnotationController('foo', $this->mocks[Request::class]), 'foo'); } public function testBeforeControllerIndexNoAnnotationPassingCheck(): void { - $this->request->method('getScriptName') + $this->mocks[Request::class]->method('getScriptName') ->willReturn('/index.php'); - $this->reflector->expects(self::once()) + $this->mocks[ControllerMethodReflector::class]->expects(self::once()) ->method('hasAnnotationOrAttribute') ->with('NoSameSiteCookieRequired', NoSameSiteCookieRequired::class) ->willReturn(false); - $this->request->method('passesLaxCookieCheck') + $this->mocks[Request::class]->method('passesLaxCookieCheck') ->willReturn(true); - $this->middleware->beforeController(new NoAnnotationController('foo', $this->request), 'foo'); + $this->middleware->beforeController(new NoAnnotationController('foo', $this->mocks[Request::class]), 'foo'); } public function testBeforeControllerIndexNoAnnotationFailingCheck(): void { $this->expectException(LaxSameSiteCookieFailedException::class); - $this->request->method('getScriptName') + $this->mocks[Request::class]->method('getScriptName') ->willReturn('/index.php'); - $this->reflector->expects(self::once()) + $this->mocks[ControllerMethodReflector::class]->expects(self::once()) ->method('hasAnnotationOrAttribute') ->with('NoSameSiteCookieRequired', NoSameSiteCookieRequired::class) ->willReturn(false); - $this->request->method('passesLaxCookieCheck') + $this->mocks[Request::class]->method('passesLaxCookieCheck') ->willReturn(false); - $this->middleware->beforeController(new NoAnnotationController('foo', $this->request), 'foo'); + $this->middleware->beforeController(new NoAnnotationController('foo', $this->mocks[Request::class]), 'foo'); } public function testAfterExceptionNoLaxCookie(): void { $ex = new SecurityException(); try { - $this->middleware->afterException(new NoAnnotationController('foo', $this->request), 'foo', $ex); + $this->middleware->afterException(new NoAnnotationController('foo', $this->mocks[Request::class]), 'foo', $ex); $this->fail(); } catch (\Exception $e) { $this->assertSame($ex, $e); @@ -115,18 +110,18 @@ public function testAfterExceptionNoLaxCookie(): void { public function testAfterExceptionLaxCookie(): void { $ex = new LaxSameSiteCookieFailedException(); - $this->request->method('getRequestUri') + $this->mocks[Request::class]->method('getRequestUri') ->willReturn('/myrequri'); $middleware = $this->getMockBuilder(SameSiteCookieMiddleware::class) - ->setConstructorArgs([$this->request, $this->reflector]) + ->setConstructorArgs([$this->mocks[Request::class], $this->mocks[ControllerMethodReflector::class]]) ->onlyMethods(['setSameSiteCookie']) ->getMock(); $middleware->expects($this->once()) ->method('setSameSiteCookie'); - $resp = $middleware->afterException(new NoAnnotationController('foo', $this->request), 'foo', $ex); + $resp = $middleware->afterException(new NoAnnotationController('foo', $this->mocks[Request::class]), 'foo', $ex); $this->assertSame(Http::STATUS_FOUND, $resp->getStatus()); diff --git a/tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php b/tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php index 288aa44883141..e345d0fd8909a 100644 --- a/tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php +++ b/tests/lib/Authentication/Listeners/RemoteWipeActivityListenerTest.php @@ -18,16 +18,9 @@ use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; use Test\TestCase; class RemoteWipeActivityListenerTest extends TestCase { - /** @var IActivityManager|MockObject */ - private $activityManager; - - /** @var LoggerInterface|MockObject */ - private $logger; - /** @var IEventListener */ private $listener; @@ -35,13 +28,7 @@ class RemoteWipeActivityListenerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->activityManager = $this->createMock(IActivityManager::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->listener = new RemoteWipeActivityListener( - $this->activityManager, - $this->logger - ); + $this->listener = $this->createInstanceWithMocks(RemoteWipeActivityListener::class); } public function testHandleUnrelated(): void { @@ -57,7 +44,7 @@ public function testHandleRemoteWipeStarted(): void { $token = $this->createMock(IToken::class); $event = new RemoteWipeStarted($token); $activityEvent = $this->createMock(IActivityEvent::class); - $this->activityManager->expects($this->once()) + $this->mocks[IActivityManager::class]->expects($this->once()) ->method('generateEvent') ->willReturn($activityEvent); $activityEvent->expects($this->once()) @@ -82,7 +69,7 @@ public function testHandleRemoteWipeStarted(): void { ->method('setSubject') ->with('remote_wipe_start', ['name' => 'Token 1']) ->willReturnSelf(); - $this->activityManager->expects($this->once()) + $this->mocks[IActivityManager::class]->expects($this->once()) ->method('publish'); $this->listener->handle($event); @@ -91,9 +78,9 @@ public function testHandleRemoteWipeStarted(): void { public function testHandleRemoteWipeStartedCanNotPublish(): void { $token = $this->createMock(IToken::class); $event = new RemoteWipeStarted($token); - $this->activityManager->expects($this->once()) + $this->mocks[IActivityManager::class]->expects($this->once()) ->method('generateEvent'); - $this->activityManager->expects($this->once()) + $this->mocks[IActivityManager::class]->expects($this->once()) ->method('publish') ->willThrowException(new \BadMethodCallException()); @@ -105,7 +92,7 @@ public function testHandleRemoteWipeFinished(): void { $token = $this->createMock(IToken::class); $event = new RemoteWipeFinished($token); $activityEvent = $this->createMock(IActivityEvent::class); - $this->activityManager->expects($this->once()) + $this->mocks[IActivityManager::class]->expects($this->once()) ->method('generateEvent') ->willReturn($activityEvent); $activityEvent->expects($this->once()) @@ -130,7 +117,7 @@ public function testHandleRemoteWipeFinished(): void { ->method('setSubject') ->with('remote_wipe_finish', ['name' => 'Token 1']) ->willReturnSelf(); - $this->activityManager->expects($this->once()) + $this->mocks[IActivityManager::class]->expects($this->once()) ->method('publish'); $this->listener->handle($event); diff --git a/tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php b/tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php index aa268151178e3..db3d3c84a4218 100644 --- a/tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php +++ b/tests/lib/Authentication/Listeners/RemoteWipeEmailListenerTest.php @@ -27,48 +27,25 @@ use Test\TestCase; class RemoteWipeEmailListenerTest extends TestCase { - /** @var IMailer|MockObject */ - private $mailer; - - /** @var IUserManager|MockObject */ - private $userManager; - - /** @var IFactory|MockObject */ - private $l10nFactory; - /** @var IL10N|MockObject */ private $l10n; - /** @var LoggerInterface|MockObject */ - private $logger; - /** @var IEventListener */ private $listener; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->mailer = $this->createMock(IMailer::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->l10nFactory = $this->createMock(IFactory::class); $this->l10n = $this->createMock(IL10N::class); - $this->logger = $this->createMock(LoggerInterface::class); + $this->listener = $this->createInstanceWithMocks(RemoteWipeEmailListener::class); - $this->l10nFactory->method('get')->with('core')->willReturn($this->l10n); + $this->mocks[IFactory::class]->method('get')->with('core')->willReturn($this->l10n); $this->l10n->method('t')->willReturnArgument(0); - - $this->listener = new RemoteWipeEmailListener( - $this->mailer, - $this->userManager, - $this->l10nFactory, - $this->logger - ); } public function testHandleUnrelated(): void { $event = new Event(); - $this->mailer->expects($this->never())->method('send'); + $this->mocks[IMailer::class]->expects($this->never())->method('send'); $this->listener->handle($event); } @@ -78,11 +55,11 @@ public function testHandleRemoteWipeStartedInvalidUser(): void { $token = $this->createMock(IToken::class); $event = new RemoteWipeStarted($token); $token->method('getUID')->willReturn('nope'); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn(null); - $this->mailer->expects($this->never())->method('send'); + $this->mocks[IMailer::class]->expects($this->never())->method('send'); $this->listener->handle($event); } @@ -93,12 +70,12 @@ public function testHandleRemoteWipeStartedNoEmailSet(): void { $event = new RemoteWipeStarted($token); $token->method('getUID')->willReturn('nope'); $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn($user); $user->method('getEMailAddress')->willReturn(null); - $this->mailer->expects($this->never())->method('send'); + $this->mocks[IMailer::class]->expects($this->never())->method('send'); $this->listener->handle($event); } @@ -109,15 +86,15 @@ public function testHandleRemoteWipeStartedTransmissionError(): void { $event = new RemoteWipeStarted($token); $token->method('getUID')->willReturn('nope'); $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn($user); $user->method('getEMailAddress')->willReturn('user@domain.org'); - $this->mailer->expects($this->once()) + $this->mocks[IMailer::class]->expects($this->once()) ->method('send') ->willThrowException(new Exception()); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('error'); $this->listener->handle($event); @@ -129,19 +106,19 @@ public function testHandleRemoteWipeStarted(): void { $event = new RemoteWipeStarted($token); $token->method('getUID')->willReturn('nope'); $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn($user); $user->method('getEMailAddress')->willReturn('user@domain.org'); $message = $this->createMock(IMessage::class); - $this->mailer->expects($this->once()) + $this->mocks[IMailer::class]->expects($this->once()) ->method('createMessage') ->willReturn($message); $message->expects($this->once()) ->method('setTo') ->with($this->equalTo(['user@domain.org'])); - $this->mailer->expects($this->once()) + $this->mocks[IMailer::class]->expects($this->once()) ->method('send') ->with($message); @@ -153,11 +130,11 @@ public function testHandleRemoteWipeFinishedInvalidUser(): void { $token = $this->createMock(IToken::class); $event = new RemoteWipeFinished($token); $token->method('getUID')->willReturn('nope'); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn(null); - $this->mailer->expects($this->never())->method('send'); + $this->mocks[IMailer::class]->expects($this->never())->method('send'); $this->listener->handle($event); } @@ -168,12 +145,12 @@ public function testHandleRemoteWipeFinishedNoEmailSet(): void { $event = new RemoteWipeFinished($token); $token->method('getUID')->willReturn('nope'); $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn($user); $user->method('getEMailAddress')->willReturn(null); - $this->mailer->expects($this->never())->method('send'); + $this->mocks[IMailer::class]->expects($this->never())->method('send'); $this->listener->handle($event); } @@ -184,15 +161,15 @@ public function testHandleRemoteWipeFinishedTransmissionError(): void { $event = new RemoteWipeFinished($token); $token->method('getUID')->willReturn('nope'); $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn($user); $user->method('getEMailAddress')->willReturn('user@domain.org'); - $this->mailer->expects($this->once()) + $this->mocks[IMailer::class]->expects($this->once()) ->method('send') ->willThrowException(new Exception()); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('error'); $this->listener->handle($event); @@ -204,19 +181,19 @@ public function testHandleRemoteWipeFinished(): void { $event = new RemoteWipeFinished($token); $token->method('getUID')->willReturn('nope'); $user = $this->createMock(IUser::class); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('nope') ->willReturn($user); $user->method('getEMailAddress')->willReturn('user@domain.org'); $message = $this->createMock(IMessage::class); - $this->mailer->expects($this->once()) + $this->mocks[IMailer::class]->expects($this->once()) ->method('createMessage') ->willReturn($message); $message->expects($this->once()) ->method('setTo') ->with($this->equalTo(['user@domain.org'])); - $this->mailer->expects($this->once()) + $this->mocks[IMailer::class]->expects($this->once()) ->method('send') ->with($message); diff --git a/tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php b/tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php index bb49fb9bbbd0b..4e3a4ffb5b46f 100644 --- a/tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php +++ b/tests/lib/Authentication/Listeners/RemoteWipeNotificationsListenerTest.php @@ -19,16 +19,9 @@ use OCP\EventDispatcher\IEventListener; use OCP\Notification\IManager as INotificationManager; use OCP\Notification\INotification; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RemoteWipeNotificationsListenerTest extends TestCase { - /** @var INotificationManager|MockObject */ - private $notificationManager; - - /** @var ITimeFactory|MockObject */ - private $timeFactory; - /** @var IEventListener */ private $listener; @@ -36,13 +29,7 @@ class RemoteWipeNotificationsListenerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->notificationManager = $this->createMock(INotificationManager::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); - - $this->listener = new RemoteWipeNotificationsListener( - $this->notificationManager, - $this->timeFactory - ); + $this->listener = $this->createInstanceWithMocks(RemoteWipeNotificationsListener::class); } public function testHandleUnrelated(): void { @@ -57,7 +44,7 @@ public function testHandleRemoteWipeStarted(): void { $token = $this->createMock(IToken::class); $event = new RemoteWipeStarted($token); $notification = $this->createMock(INotification::class); - $this->notificationManager->expects($this->once()) + $this->mocks[INotificationManager::class]->expects($this->once()) ->method('createNotification') ->willReturn($notification); $notification->expects($this->once()) @@ -70,7 +57,7 @@ public function testHandleRemoteWipeStarted(): void { ->with('user123') ->willReturnSelf(); $now = new DateTime(); - $this->timeFactory->method('getDateTime')->willReturn($now); + $this->mocks[ITimeFactory::class]->method('getDateTime')->willReturn($now); $notification->expects($this->once()) ->method('setDateTime') ->with($now) @@ -87,7 +74,7 @@ public function testHandleRemoteWipeStarted(): void { 'name' => 'Token 1' ]) ->willReturnSelf(); - $this->notificationManager->expects($this->once()) + $this->mocks[INotificationManager::class]->expects($this->once()) ->method('notify'); $this->listener->handle($event); @@ -97,7 +84,7 @@ public function testHandleRemoteWipeFinished(): void { $token = $this->createMock(IToken::class); $event = new RemoteWipeFinished($token); $notification = $this->createMock(INotification::class); - $this->notificationManager->expects($this->once()) + $this->mocks[INotificationManager::class]->expects($this->once()) ->method('createNotification') ->willReturn($notification); $notification->expects($this->once()) @@ -110,7 +97,7 @@ public function testHandleRemoteWipeFinished(): void { ->with('user123') ->willReturnSelf(); $now = new DateTime(); - $this->timeFactory->method('getDateTime')->willReturn($now); + $this->mocks[ITimeFactory::class]->method('getDateTime')->willReturn($now); $notification->expects($this->once()) ->method('setDateTime') ->with($now) @@ -127,7 +114,7 @@ public function testHandleRemoteWipeFinished(): void { 'name' => 'Token 1' ]) ->willReturnSelf(); - $this->notificationManager->expects($this->once()) + $this->mocks[INotificationManager::class]->expects($this->once()) ->method('notify'); $this->listener->handle($event); diff --git a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php index 0a84a7faafadf..5f20a3c22e07c 100644 --- a/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php +++ b/tests/lib/Authentication/Listeners/UserDeletedTokenCleanupListenerTest.php @@ -16,17 +16,10 @@ use OCP\EventDispatcher\Event; use OCP\IUser; use OCP\User\Events\UserDeletedEvent; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class UserDeletedTokenCleanupListenerTest extends TestCase { - /** @var Manager|MockObject */ - private $manager; - - /** @var LoggerInterface|MockObject */ - private $logger; - /** @var UserDeletedTokenCleanupListener */ private $listener; @@ -34,19 +27,13 @@ class UserDeletedTokenCleanupListenerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->manager = $this->createMock(Manager::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->listener = new UserDeletedTokenCleanupListener( - $this->manager, - $this->logger - ); + $this->listener = $this->createInstanceWithMocks(UserDeletedTokenCleanupListener::class); } public function testHandleUnrelated(): void { $event = new Event(); - $this->manager->expects($this->never())->method('getTokenByUser'); - $this->logger->expects($this->never())->method('error'); + $this->mocks[Manager::class]->expects($this->never())->method('getTokenByUser'); + $this->mocks[LoggerInterface::class]->expects($this->never())->method('error'); $this->listener->handle($event); } @@ -56,11 +43,11 @@ public function testHandleWithErrors(): void { $user->method('getUID')->willReturn('user123'); $event = new UserDeletedEvent($user); $exception = new Exception('nope'); - $this->manager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getTokenByUser') ->with('user123') ->willThrowException($exception); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('error'); $this->listener->handle($event); @@ -76,7 +63,7 @@ public function testHandle(): void { $token2->method('getId')->willReturn(2); $token3 = $this->createMock(IToken::class); $token3->method('getId')->willReturn(3); - $this->manager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getTokenByUser') ->with('user123') ->willReturn([ @@ -90,13 +77,13 @@ public function testHandle(): void { ['user123', 2], ['user123', 3], ]; - $this->manager->expects($this->exactly(3)) + $this->mocks[Manager::class]->expects($this->exactly(3)) ->method('invalidateTokenById') ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); - $this->logger->expects($this->never()) + $this->mocks[LoggerInterface::class]->expects($this->never()) ->method('error'); $this->listener->handle($event); diff --git a/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php b/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php index c4c3dcf5ca891..a3de986083d3f 100644 --- a/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php +++ b/tests/lib/Authentication/Login/ClearLostPasswordTokensCommandTest.php @@ -11,21 +11,13 @@ use OC\Authentication\Login\ClearLostPasswordTokensCommand; use OCP\IConfig; -use PHPUnit\Framework\MockObject\MockObject; class ClearLostPasswordTokensCommandTest extends ALoginTestCommand { - /** @var IConfig|MockObject */ - private $config; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - - $this->cmd = new ClearLostPasswordTokensCommand( - $this->config - ); + $this->cmd = $this->createInstanceWithMocks(ClearLostPasswordTokensCommand::class); } public function testProcess(): void { @@ -33,7 +25,7 @@ public function testProcess(): void { $this->user->expects($this->once()) ->method('getUID') ->willReturn($this->username); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('deleteUserValue') ->with( $this->username, diff --git a/tests/lib/Authentication/Login/CompleteLoginCommandTest.php b/tests/lib/Authentication/Login/CompleteLoginCommandTest.php index 1457e4763baf2..265497cb06f41 100644 --- a/tests/lib/Authentication/Login/CompleteLoginCommandTest.php +++ b/tests/lib/Authentication/Login/CompleteLoginCommandTest.php @@ -11,26 +11,18 @@ use OC\Authentication\Login\CompleteLoginCommand; use OC\User\Session; -use PHPUnit\Framework\MockObject\MockObject; class CompleteLoginCommandTest extends ALoginTestCommand { - /** @var Session|MockObject */ - private $session; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->session = $this->createMock(Session::class); - - $this->cmd = new CompleteLoginCommand( - $this->session - ); + $this->cmd = $this->createInstanceWithMocks(CompleteLoginCommand::class); } public function testProcess(): void { $data = $this->getLoggedInLoginData(); - $this->session->expects($this->once()) + $this->mocks[Session::class]->expects($this->once()) ->method('completeLogin') ->with( $this->user, diff --git a/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php b/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php index b2c94d105958a..68934480bf095 100644 --- a/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php +++ b/tests/lib/Authentication/Login/CreateSessionTokenCommandTest.php @@ -15,38 +15,22 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; use OCP\IURLGenerator; -use PHPUnit\Framework\MockObject\MockObject; class CreateSessionTokenCommandTest extends ALoginTestCommand { - private IConfig&MockObject $config; - private Session&MockObject $userSession; - private IURLGenerator&MockObject $urlGenerator; - private ITimeFactory&MockObject $timeFactory; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->userSession = $this->createMock(Session::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); - - $this->cmd = new CreateSessionTokenCommand( - $this->config, - $this->userSession, - $this->urlGenerator, - $this->timeFactory, - ); + $this->cmd = $this->createInstanceWithMocks(CreateSessionTokenCommand::class); } public function testProcess(): void { // Just return the route name as path to not return an empty string - $this->urlGenerator->expects(self::once()) + $this->mocks[IURLGenerator::class]->expects(self::once()) ->method('linkToRoute') ->willReturnArgument(0); $data = $this->getLoggedInLoginData(); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueInt') ->with( 'remember_login_cookie_lifetime', @@ -56,7 +40,7 @@ public function testProcess(): void { $this->user->expects($this->any()) ->method('getUID') ->willReturn($this->username); - $this->userSession->expects($this->once()) + $this->mocks[Session::class]->expects($this->once()) ->method('createSessionToken') ->with( $this->request, @@ -66,7 +50,7 @@ public function testProcess(): void { IToken::REMEMBER, null ); - $this->userSession->expects($this->once()) + $this->mocks[Session::class]->expects($this->once()) ->method('updateTokens') ->with( $this->username, @@ -80,11 +64,11 @@ public function testProcess(): void { public function testProcessDoNotRemember(): void { // Just return the route name as path to not return an empty string - $this->urlGenerator->expects(self::once()) + $this->mocks[IURLGenerator::class]->expects(self::once()) ->method('linkToRoute') ->willReturnArgument(0); $data = $this->getLoggedInLoginData(); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueInt') ->with( 'remember_login_cookie_lifetime', @@ -94,7 +78,7 @@ public function testProcessDoNotRemember(): void { $this->user->expects($this->any()) ->method('getUID') ->willReturn($this->username); - $this->userSession->expects($this->once()) + $this->mocks[Session::class]->expects($this->once()) ->method('createSessionToken') ->with( $this->request, @@ -104,7 +88,7 @@ public function testProcessDoNotRemember(): void { IToken::DO_NOT_REMEMBER, null ); - $this->userSession->expects($this->once()) + $this->mocks[Session::class]->expects($this->once()) ->method('updateTokens') ->with( $this->username, @@ -119,15 +103,15 @@ public function testProcessDoNotRemember(): void { public function testLoginFlowEphemeral(): void { $this->redirectUrl = 'EPHEMERAL_ROUTE'; - $this->urlGenerator->expects(self::once()) + $this->mocks[IURLGenerator::class]->expects(self::once()) ->method('linkToRoute') ->willReturn($this->redirectUrl); - $this->timeFactory->expects(self::once()) + $this->mocks[ITimeFactory::class]->expects(self::once()) ->method('getTime') ->willReturn(1000); $data = $this->getLoggedInLoginDataWithRedirectUrl(); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueInt') ->with( 'remember_login_cookie_lifetime', @@ -137,7 +121,7 @@ public function testLoginFlowEphemeral(): void { $this->user->expects($this->any()) ->method('getUID') ->willReturn($this->username); - $this->userSession->expects($this->once()) + $this->mocks[Session::class]->expects($this->once()) ->method('createSessionToken') ->with( $this->request, @@ -147,7 +131,7 @@ public function testLoginFlowEphemeral(): void { IToken::REMEMBER, 1000 + 5 * 60 ); - $this->userSession->expects($this->once()) + $this->mocks[Session::class]->expects($this->once()) ->method('updateTokens') ->with( $this->username, diff --git a/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php b/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php index 1d6c0f3af0996..b82cdabca473b 100644 --- a/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php +++ b/tests/lib/Authentication/Login/FinishRememberedLoginCommandTest.php @@ -12,31 +12,19 @@ use OC\Authentication\Login\FinishRememberedLoginCommand; use OC\User\Session; use OCP\IConfig; -use PHPUnit\Framework\MockObject\MockObject; class FinishRememberedLoginCommandTest extends ALoginTestCommand { - /** @var Session|MockObject */ - private $userSession; - /** @var IConfig|MockObject */ - private $config; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->userSession = $this->createMock(Session::class); - $this->config = $this->createMock(IConfig::class); - - $this->cmd = new FinishRememberedLoginCommand( - $this->userSession, - $this->config - ); + $this->cmd = $this->createInstanceWithMocks(FinishRememberedLoginCommand::class); } public function testProcessNotRememberedLogin(): void { $data = $this->getLoggedInLoginData(); $data->setRememberLogin(false); - $this->userSession->expects($this->never()) + $this->mocks[Session::class]->expects($this->never()) ->method('createRememberMeToken'); $result = $this->cmd->process($data); @@ -46,11 +34,11 @@ public function testProcessNotRememberedLogin(): void { public function testProcess(): void { $data = $this->getLoggedInLoginData(); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueBool') ->with('auto_logout', false) ->willReturn(false); - $this->userSession->expects($this->once()) + $this->mocks[Session::class]->expects($this->once()) ->method('createRememberMeToken') ->with($this->user); @@ -61,11 +49,11 @@ public function testProcess(): void { public function testProcessNotRemeberedLoginWithAutologout(): void { $data = $this->getLoggedInLoginData(); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueBool') ->with('auto_logout', false) ->willReturn(true); - $this->userSession->expects($this->never()) + $this->mocks[Session::class]->expects($this->never()) ->method('createRememberMeToken'); $result = $this->cmd->process($data); diff --git a/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php b/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php index 9c25c15fcc1e9..1c23d99a10f84 100644 --- a/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php +++ b/tests/lib/Authentication/Login/LoggedInCheckCommandTest.php @@ -11,28 +11,14 @@ use OC\Authentication\Login\LoggedInCheckCommand; use OC\Core\Controller\LoginController; -use OCP\EventDispatcher\IEventDispatcher; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; class LoggedInCheckCommandTest extends ALoginTestCommand { - /** @var LoggerInterface|MockObject */ - private $logger; - - /** @var IEventDispatcher|MockObject */ - private $dispatcher; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->logger = $this->createMock(LoggerInterface::class); - $this->dispatcher = $this->createMock(IEventDispatcher::class); - - $this->cmd = new LoggedInCheckCommand( - $this->logger, - $this->dispatcher - ); + $this->cmd = $this->createInstanceWithMocks(LoggedInCheckCommand::class); } public function testProcessSuccessfulLogin(): void { @@ -45,7 +31,7 @@ public function testProcessSuccessfulLogin(): void { public function testProcessFailedLogin(): void { $data = $this->getFailedLoginData(); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('warning'); $result = $this->cmd->process($data); diff --git a/tests/lib/Authentication/Login/PreLoginHookCommandTest.php b/tests/lib/Authentication/Login/PreLoginHookCommandTest.php index 91c1187da7d47..25bbbcc1b9f39 100644 --- a/tests/lib/Authentication/Login/PreLoginHookCommandTest.php +++ b/tests/lib/Authentication/Login/PreLoginHookCommandTest.php @@ -12,25 +12,18 @@ use OC\Authentication\Login\PreLoginHookCommand; use OCP\EventDispatcher\IEventDispatcher; use OCP\User\Events\BeforeUserLoggedInEvent; -use PHPUnit\Framework\MockObject\MockObject; class PreLoginHookCommandTest extends ALoginTestCommand { - private IEventDispatcher&MockObject $eventDispatcher; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - - $this->cmd = new PreLoginHookCommand( - $this->eventDispatcher, - ); + $this->cmd = $this->createInstanceWithMocks(PreLoginHookCommand::class); } public function testProcess(): void { $data = $this->getBasicLoginData(); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with($this->callback(function (BeforeUserLoggedInEvent $event): bool { $this->assertEquals($this->username, $event->getUsername()); diff --git a/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php b/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php index 5665fca60a099..870b4f6a200e8 100644 --- a/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php +++ b/tests/lib/Authentication/Login/SetUserTimezoneCommandTest.php @@ -12,32 +12,21 @@ use OC\Authentication\Login\SetUserTimezoneCommand; use OCP\IConfig; use OCP\ISession; -use PHPUnit\Framework\MockObject\MockObject; class SetUserTimezoneCommandTest extends ALoginTestCommand { - private IConfig&MockObject $config; - - private ISession&MockObject $session; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->session = $this->createMock(ISession::class); - - $this->cmd = new SetUserTimezoneCommand( - $this->config, - $this->session - ); + $this->cmd = $this->createInstanceWithMocks(SetUserTimezoneCommand::class); } public function testProcessNoTimezoneSet(): void { $data = $this->getLoggedInLoginData(); - $this->config->expects($this->never()) + $this->mocks[IConfig::class]->expects($this->never()) ->method('setUserValue'); - $this->session->expects($this->never()) + $this->mocks[ISession::class]->expects($this->never()) ->method('set'); $result = $this->cmd->process($data); @@ -75,7 +64,7 @@ public function testProcess(?string $timezone): void { $this->user->expects($this->once()) ->method('getUID') ->willReturn($this->username); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getUserValue') ->with( $this->username, @@ -84,7 +73,7 @@ public function testProcess(?string $timezone): void { '' ) ->willReturn(''); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('setUserValue') ->with( $this->username, @@ -92,7 +81,7 @@ public function testProcess(?string $timezone): void { 'timezone', $timezone ); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('set') ->with( 'timezone', @@ -106,9 +95,9 @@ public function testProcess(?string $timezone): void { public function testProcessUnknownTimezone(): void { $data = $this->getLoggedInLoginDataWithTimezone('Mars/Olympus_Mons'); - $this->config->expects($this->never()) + $this->mocks[IConfig::class]->expects($this->never()) ->method('setUserValue'); - $this->session->expects($this->never()) + $this->mocks[ISession::class]->expects($this->never()) ->method('set'); $result = $this->cmd->process($data); @@ -121,7 +110,7 @@ public function testProcessAlreadySet(): void { $this->user->expects($this->once()) ->method('getUID') ->willReturn($this->username); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getUserValue') ->with( $this->username, @@ -130,9 +119,9 @@ public function testProcessAlreadySet(): void { '', ) ->willReturn('Europe/Berlin'); - $this->config->expects($this->never()) + $this->mocks[IConfig::class]->expects($this->never()) ->method('setUserValue'); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('set') ->with( 'timezone', diff --git a/tests/lib/Authentication/Login/TwoFactorCommandTest.php b/tests/lib/Authentication/Login/TwoFactorCommandTest.php index feb139c880de4..779179345a6d9 100644 --- a/tests/lib/Authentication/Login/TwoFactorCommandTest.php +++ b/tests/lib/Authentication/Login/TwoFactorCommandTest.php @@ -16,39 +16,21 @@ use OCP\Authentication\TwoFactorAuth\IActivatableAtLogin; use OCP\Authentication\TwoFactorAuth\IProvider as ITwoFactorAuthProvider; use OCP\IURLGenerator; -use PHPUnit\Framework\MockObject\MockObject; class TwoFactorCommandTest extends ALoginTestCommand { - /** @var Manager|MockObject */ - private $twoFactorManager; - - /** @var MandatoryTwoFactor|MockObject */ - private $mandatoryTwoFactor; - - /** @var IURLGenerator|MockObject */ - private $urlGenerator; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->twoFactorManager = $this->createMock(Manager::class); - $this->mandatoryTwoFactor = $this->createMock(MandatoryTwoFactor::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - - $this->cmd = new TwoFactorCommand( - $this->twoFactorManager, - $this->mandatoryTwoFactor, - $this->urlGenerator - ); + $this->cmd = $this->createInstanceWithMocks(TwoFactorCommand::class); } public function testNotTwoFactorAuthenticated(): void { $data = $this->getLoggedInLoginData(); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(false); - $this->twoFactorManager->expects($this->never()) + $this->mocks[Manager::class]->expects($this->never()) ->method('prepareTwoFactorLogin'); $result = $this->cmd->process($data); @@ -59,7 +41,7 @@ public function testNotTwoFactorAuthenticated(): void { public function testSkippedForVerifiedWebAuthnLogin(): void { $data = $this->getLoggedInLoginData(); $data->setWebAuthnUserVerified(true); - $this->twoFactorManager->expects($this->never()) + $this->mocks[Manager::class]->expects($this->never()) ->method('prepareTwoFactorLogin'); $result = $this->cmd->process($data); @@ -71,18 +53,18 @@ public function testSkippedForVerifiedWebAuthnLogin(): void { public function testNotSkippedForWebAuthnLoginWithoutUserVerification(): void { $data = $this->getLoggedInLoginData(); $data->setWebAuthnUserVerified(false); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(true); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('prepareTwoFactorLogin'); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getProviderSet') ->willReturn(new ProviderSet([], false)); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getLoginSetupProviders') ->willReturn([]); - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->willReturn('two/factor/url'); @@ -93,33 +75,33 @@ public function testNotSkippedForWebAuthnLoginWithoutUserVerification(): void { public function testProcessOneActiveProvider(): void { $data = $this->getLoggedInLoginData(); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(true); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('prepareTwoFactorLogin') ->with( $this->user, $data->isRememberLogin() ); $provider = $this->createMock(ITwoFactorAuthProvider::class); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getProviderSet') ->willReturn(new ProviderSet([ $provider, ], false)); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getLoginSetupProviders') ->with($this->user) ->willReturn([]); - $this->mandatoryTwoFactor->expects($this->any()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->any()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(false); $provider->expects($this->once()) ->method('getId') ->willReturn('test'); - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->with( 'core.TwoFactorChallenge.showChallenge', @@ -137,10 +119,10 @@ public function testProcessOneActiveProvider(): void { public function testProcessMissingProviders(): void { $data = $this->getLoggedInLoginData(); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(true); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('prepareTwoFactorLogin') ->with( $this->user, @@ -150,20 +132,20 @@ public function testProcessMissingProviders(): void { $provider->expects($this->once()) ->method('getId') ->willReturn('test1'); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getProviderSet') ->willReturn(new ProviderSet([ $provider, ], true)); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getLoginSetupProviders') ->with($this->user) ->willReturn([]); - $this->mandatoryTwoFactor->expects($this->any()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->any()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(false); - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->with( 'core.TwoFactorChallenge.selectChallenge' @@ -178,10 +160,10 @@ public function testProcessMissingProviders(): void { public function testProcessTwoActiveProviders(): void { $data = $this->getLoggedInLoginData(); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(true); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('prepareTwoFactorLogin') ->with( $this->user, @@ -195,21 +177,21 @@ public function testProcessTwoActiveProviders(): void { $provider2->expects($this->once()) ->method('getId') ->willReturn('test2'); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getProviderSet') ->willReturn(new ProviderSet([ $provider1, $provider2, ], false)); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getLoginSetupProviders') ->with($this->user) ->willReturn([]); - $this->mandatoryTwoFactor->expects($this->any()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->any()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(false); - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->with( 'core.TwoFactorChallenge.selectChallenge' @@ -224,27 +206,27 @@ public function testProcessTwoActiveProviders(): void { public function testProcessFailingProviderAndEnforcedButNoSetupProviders(): void { $data = $this->getLoggedInLoginData(); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(true); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('prepareTwoFactorLogin') ->with( $this->user, $data->isRememberLogin() ); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getProviderSet') ->willReturn(new ProviderSet([], true)); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getLoginSetupProviders') ->with($this->user) ->willReturn([]); - $this->mandatoryTwoFactor->expects($this->any()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->any()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(true); - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->with( 'core.TwoFactorChallenge.selectChallenge' @@ -259,30 +241,30 @@ public function testProcessFailingProviderAndEnforcedButNoSetupProviders(): void public function testProcessFailingProviderAndEnforced(): void { $data = $this->getLoggedInLoginData(); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(true); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('prepareTwoFactorLogin') ->with( $this->user, $data->isRememberLogin() ); $provider = $this->createMock(IActivatableAtLogin::class); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getProviderSet') ->willReturn(new ProviderSet([ $provider, ], true)); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getLoginSetupProviders') ->with($this->user) ->willReturn([]); - $this->mandatoryTwoFactor->expects($this->any()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->any()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(true); - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->with( 'core.TwoFactorChallenge.selectChallenge' @@ -297,27 +279,27 @@ public function testProcessFailingProviderAndEnforced(): void { public function testProcessNoProvidersButEnforced(): void { $data = $this->getLoggedInLoginData(); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(true); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('prepareTwoFactorLogin') ->with( $this->user, $data->isRememberLogin() ); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getProviderSet') ->willReturn(new ProviderSet([], false)); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getLoginSetupProviders') ->with($this->user) ->willReturn([]); - $this->mandatoryTwoFactor->expects($this->any()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->any()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(true); - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->with( 'core.TwoFactorChallenge.selectChallenge' @@ -332,33 +314,33 @@ public function testProcessNoProvidersButEnforced(): void { public function testProcessWithRedirectUrl(): void { $data = $this->getLoggedInLoginDataWithRedirectUrl(); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('isTwoFactorAuthenticated') ->willReturn(true); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('prepareTwoFactorLogin') ->with( $this->user, $data->isRememberLogin() ); $provider = $this->createMock(ITwoFactorAuthProvider::class); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getProviderSet') ->willReturn(new ProviderSet([ $provider, ], false)); - $this->twoFactorManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('getLoginSetupProviders') ->with($this->user) ->willReturn([]); - $this->mandatoryTwoFactor->expects($this->any()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->any()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(false); $provider->expects($this->once()) ->method('getId') ->willReturn('test'); - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->with( 'core.TwoFactorChallenge.showChallenge', diff --git a/tests/lib/Authentication/Login/UidLoginCommandTest.php b/tests/lib/Authentication/Login/UidLoginCommandTest.php index 1aed795018a6b..90b632c955810 100644 --- a/tests/lib/Authentication/Login/UidLoginCommandTest.php +++ b/tests/lib/Authentication/Login/UidLoginCommandTest.php @@ -11,26 +11,18 @@ use OC\Authentication\Login\UidLoginCommand; use OC\User\Manager; -use PHPUnit\Framework\MockObject\MockObject; class UidLoginCommandTest extends ALoginTestCommand { - /** @var Manager|MockObject */ - private $userManager; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->userManager = $this->createMock(Manager::class); - - $this->cmd = new UidLoginCommand( - $this->userManager - ); + $this->cmd = $this->createInstanceWithMocks(UidLoginCommand::class); } public function testProcessFailingLogin(): void { $data = $this->getBasicLoginData(); - $this->userManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('checkPasswordNoLogging') ->with( $this->username, @@ -46,7 +38,7 @@ public function testProcessFailingLogin(): void { public function testProcess(): void { $data = $this->getBasicLoginData(); - $this->userManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('checkPasswordNoLogging') ->with( $this->username, diff --git a/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php b/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php index ebff6e2e54bdf..086fac7e2c7b8 100644 --- a/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php +++ b/tests/lib/Authentication/Login/UpdateLastPasswordConfirmCommandTest.php @@ -11,21 +11,13 @@ use OC\Authentication\Login\UpdateLastPasswordConfirmCommand; use OCP\ISession; -use PHPUnit\Framework\MockObject\MockObject; class UpdateLastPasswordConfirmCommandTest extends ALoginTestCommand { - /** @var ISession|MockObject */ - private $session; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->session = $this->createMock(ISession::class); - - $this->cmd = new UpdateLastPasswordConfirmCommand( - $this->session - ); + $this->cmd = $this->createInstanceWithMocks(UpdateLastPasswordConfirmCommand::class); } public function testProcess(): void { @@ -33,7 +25,7 @@ public function testProcess(): void { $this->user->expects($this->once()) ->method('getLastLogin') ->willReturn(1234); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('set') ->with( 'last-password-confirm', diff --git a/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php b/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php index 917c64d053395..977fb5a4444ea 100644 --- a/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php +++ b/tests/lib/Authentication/Login/UserDisabledCheckCommandTest.php @@ -12,32 +12,18 @@ use OC\Authentication\Login\UserDisabledCheckCommand; use OC\Core\Controller\LoginController; use OCP\IUserManager; -use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; class UserDisabledCheckCommandTest extends ALoginTestCommand { - /** @var IUserManager|MockObject */ - private $userManager; - - /** @var LoggerInterface|MockObject */ - private $logger; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->userManager = $this->createMock(IUserManager::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->cmd = new UserDisabledCheckCommand( - $this->userManager, - $this->logger - ); + $this->cmd = $this->createInstanceWithMocks(UserDisabledCheckCommand::class); } public function testProcessNonExistingUser(): void { $data = $this->getBasicLoginData(); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with($this->username) ->willReturn(null); @@ -49,7 +35,7 @@ public function testProcessNonExistingUser(): void { public function testProcessDisabledUser(): void { $data = $this->getBasicLoginData(); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with($this->username) ->willReturn($this->user); @@ -65,7 +51,7 @@ public function testProcessDisabledUser(): void { public function testProcess(): void { $data = $this->getBasicLoginData(); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with($this->username) ->willReturn($this->user); diff --git a/tests/lib/Authentication/LoginCredentials/StoreTest.php b/tests/lib/Authentication/LoginCredentials/StoreTest.php index a0695ef1a4bce..449e2ce4861f2 100644 --- a/tests/lib/Authentication/LoginCredentials/StoreTest.php +++ b/tests/lib/Authentication/LoginCredentials/StoreTest.php @@ -22,17 +22,6 @@ use function json_encode; class StoreTest extends TestCase { - /** @var ISession|\PHPUnit\Framework\MockObject\MockObject */ - private $session; - - /** @var IProvider|\PHPUnit\Framework\MockObject\MockObject */ - private $tokenProvider; - - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; - /** @var ICrypto|\PHPUnit\Framework\MockObject\MockObject */ - private $crypto; - /** @var Store */ private $store; @@ -40,12 +29,7 @@ class StoreTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->session = $this->createMock(ISession::class); - $this->tokenProvider = $this->createMock(IProvider::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->crypto = $this->createMock(ICrypto::class); - - $this->store = new Store($this->session, $this->logger, $this->crypto, $this->tokenProvider); + $this->store = $this->createInstanceWithMocks(Store::class); } public function testAuthenticate(): void { @@ -55,10 +39,10 @@ public function testAuthenticate(): void { 'password' => '123456', ]; - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('set') ->with($this->equalTo('login_credentials'), $this->equalTo(json_encode($params))); - $this->crypto->expects($this->once()) + $this->mocks[ICrypto::class]->expects($this->once()) ->method('encrypt') ->willReturn('123456'); @@ -73,7 +57,7 @@ public function testSetSession(): void { } public function testGetLoginCredentialsNoTokenProvider(): void { - $this->store = new Store($this->session, $this->logger, $this->crypto, null); + $this->store = new Store($this->mocks[ISession::class], $this->mocks[LoggerInterface::class], $this->mocks[ICrypto::class], null); $this->expectException(CredentialsUnavailableException::class); @@ -85,10 +69,10 @@ public function testGetLoginCredentials(): void { $user = 'user123'; $password = 'passme'; $token = $this->createMock(IToken::class); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('getId') ->willReturn('sess2233'); - $this->tokenProvider->expects($this->once()) + $this->mocks[IProvider::class]->expects($this->once()) ->method('getToken') ->with('sess2233') ->willReturn($token); @@ -98,7 +82,7 @@ public function testGetLoginCredentials(): void { $token->expects($this->once()) ->method('getLoginName') ->willReturn($user); - $this->tokenProvider->expects($this->once()) + $this->mocks[IProvider::class]->expects($this->once()) ->method('getPassword') ->with($token, 'sess2233') ->willReturn($password); @@ -110,7 +94,7 @@ public function testGetLoginCredentials(): void { } public function testGetLoginCredentialsSessionNotAvailable(): void { - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('getId') ->willThrowException(new SessionNotAvailableException()); $this->expectException(CredentialsUnavailableException::class); @@ -119,10 +103,10 @@ public function testGetLoginCredentialsSessionNotAvailable(): void { } public function testGetLoginCredentialsInvalidToken(): void { - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('getId') ->willReturn('sess2233'); - $this->tokenProvider->expects($this->once()) + $this->mocks[IProvider::class]->expects($this->once()) ->method('getToken') ->with('sess2233') ->willThrowException(new InvalidTokenException()); @@ -136,21 +120,21 @@ public function testGetLoginCredentialsPartialCredentialsAndSessionName(): void $user = 'user987'; $password = '7389374'; - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('getId') ->willReturn('sess2233'); - $this->tokenProvider->expects($this->once()) + $this->mocks[IProvider::class]->expects($this->once()) ->method('getToken') ->with('sess2233') ->willThrowException(new InvalidTokenException()); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('exists') ->with($this->equalTo('login_credentials')) ->willReturn(true); - $this->crypto->expects($this->once()) + $this->mocks[ICrypto::class]->expects($this->once()) ->method('decrypt') ->willReturn($password); - $this->session->expects($this->exactly(2)) + $this->mocks[ISession::class]->expects($this->exactly(2)) ->method('get') ->willReturnMap([ [ @@ -176,21 +160,21 @@ public function testGetLoginCredentialsPartialCredentials(): void { $uid = 'id987'; $password = '7389374'; - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('getId') ->willReturn('sess2233'); - $this->tokenProvider->expects($this->once()) + $this->mocks[IProvider::class]->expects($this->once()) ->method('getToken') ->with('sess2233') ->willThrowException(new InvalidTokenException()); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('exists') ->with($this->equalTo('login_credentials')) ->willReturn(true); - $this->crypto->expects($this->once()) + $this->mocks[ICrypto::class]->expects($this->once()) ->method('decrypt') ->willReturn($password); - $this->session->expects($this->exactly(2)) + $this->mocks[ISession::class]->expects($this->exactly(2)) ->method('get') ->willReturnMap([ [ @@ -217,21 +201,21 @@ public function testGetLoginCredentialsInvalidTokenLoginCredentials(): void { $user = 'user987'; $password = '7389374'; - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('getId') ->willReturn('sess2233'); - $this->tokenProvider->expects($this->once()) + $this->mocks[IProvider::class]->expects($this->once()) ->method('getToken') ->with('sess2233') ->willThrowException(new InvalidTokenException()); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('exists') ->with($this->equalTo('login_credentials')) ->willReturn(true); - $this->crypto->expects($this->once()) + $this->mocks[ICrypto::class]->expects($this->once()) ->method('decrypt') ->willReturn($password); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('get') ->with($this->equalTo('login_credentials')) ->willReturn('{"run":true,"uid":"id987","loginName":"user987","password":"7389374"}'); @@ -243,10 +227,10 @@ public function testGetLoginCredentialsInvalidTokenLoginCredentials(): void { } public function testGetLoginCredentialsPasswordlessToken(): void { - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('getId') ->willReturn('sess2233'); - $this->tokenProvider->expects($this->once()) + $this->mocks[IProvider::class]->expects($this->once()) ->method('getToken') ->with('sess2233') ->willThrowException(new PasswordlessTokenException()); @@ -266,23 +250,23 @@ public function testAuthenticatePasswordlessToken(): void { 'password' => $password, ]; - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('set') ->with($this->equalTo('login_credentials'), $this->equalTo(json_encode($params))); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('getId') ->willReturn('sess2233'); - $this->tokenProvider->expects($this->once()) + $this->mocks[IProvider::class]->expects($this->once()) ->method('getToken') ->with('sess2233') ->willThrowException(new PasswordlessTokenException()); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('exists') ->with($this->equalTo('login_credentials')) ->willReturn(true); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('get') ->with($this->equalTo('login_credentials')) ->willReturn(json_encode($params)); diff --git a/tests/lib/Authentication/Token/ManagerTest.php b/tests/lib/Authentication/Token/ManagerTest.php index 8511ccf578897..d90df43fe1008 100644 --- a/tests/lib/Authentication/Token/ManagerTest.php +++ b/tests/lib/Authentication/Token/ManagerTest.php @@ -19,25 +19,19 @@ use Test\TestCase; class ManagerTest extends TestCase { - /** @var PublicKeyTokenProvider|MockObject */ - private $publicKeyTokenProvider; /** @var Manager */ private $manager; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->publicKeyTokenProvider = $this->createMock(PublicKeyTokenProvider::class); - $this->manager = new Manager( - $this->publicKeyTokenProvider - ); + $this->manager = $this->createInstanceWithMocks(Manager::class); } public function testGenerateToken(): void { $token = new PublicKeyToken(); - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('generateToken') ->with( 'token', @@ -70,7 +64,7 @@ public function testGenerateConflictingToken(): void { $token = new PublicKeyToken(); $token->setUid('uid'); - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('generateToken') ->with( 'token', @@ -81,7 +75,7 @@ public function testGenerateConflictingToken(): void { IToken::TEMPORARY_TOKEN, IToken::REMEMBER )->willThrowException($exception); - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('getToken') ->with('token') ->willReturn($token); @@ -104,7 +98,7 @@ public function testGenerateTokenTooLongName(): void { $token->method('getName') ->willReturn(str_repeat('a', 120) . '…'); - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('generateToken') ->with( 'token', @@ -138,14 +132,14 @@ public static function tokenData(): array { protected function setNoCall(IToken $token) { if (!($token instanceof PublicKeyToken)) { - $this->publicKeyTokenProvider->expects($this->never()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->never()) ->method($this->anything()); } } protected function setCall(IToken $token, string $function, $return = null) { if ($token instanceof PublicKeyToken) { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method($function) ->with($token) ->willReturn($return); @@ -213,7 +207,7 @@ public function testSetPassword(IToken|string $token): void { } public function testInvalidateTokens(): void { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('invalidateToken') ->with('token'); @@ -221,7 +215,7 @@ public function testInvalidateTokens(): void { } public function testInvalidateTokenById(): void { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('invalidateTokenById') ->with('uid', 42); @@ -229,14 +223,14 @@ public function testInvalidateTokenById(): void { } public function testInvalidateOldTokens(): void { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('invalidateOldTokens'); $this->manager->invalidateOldTokens(); } public function testInvalidateLastUsedBefore(): void { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('invalidateLastUsedBefore') ->with('user', 946684800); @@ -247,7 +241,7 @@ public function testGetTokenByUser(): void { $t1 = new PublicKeyToken(); $t2 = new PublicKeyToken(); - $this->publicKeyTokenProvider + $this->mocks[PublicKeyTokenProvider::class] ->method('getTokenByUser') ->willReturn([$t1, $t2]); @@ -257,7 +251,7 @@ public function testGetTokenByUser(): void { } public function testRenewSessionTokenPublicKey(): void { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('renewSessionToken') ->with('oldId', 'newId'); @@ -265,7 +259,7 @@ public function testRenewSessionTokenPublicKey(): void { } public function testRenewSessionInvalid(): void { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('renewSessionToken') ->with('oldId', 'newId') ->willThrowException(new InvalidTokenException()); @@ -277,7 +271,7 @@ public function testRenewSessionInvalid(): void { public function testGetTokenByIdPublicKey(): void { $token = $this->createMock(IToken::class); - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('getTokenById') ->with(42) ->willReturn($token); @@ -286,7 +280,7 @@ public function testGetTokenByIdPublicKey(): void { } public function testGetTokenByIdInvalid(): void { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('getTokenById') ->with(42) ->willThrowException(new InvalidTokenException()); @@ -298,7 +292,7 @@ public function testGetTokenByIdInvalid(): void { public function testGetTokenPublicKey(): void { $token = new PublicKeyToken(); - $this->publicKeyTokenProvider + $this->mocks[PublicKeyTokenProvider::class] ->method('getToken') ->with('tokenId') ->willReturn($token); @@ -307,7 +301,7 @@ public function testGetTokenPublicKey(): void { } public function testGetTokenInvalid(): void { - $this->publicKeyTokenProvider + $this->mocks[PublicKeyTokenProvider::class] ->method('getToken') ->with('tokenId') ->willThrowException(new InvalidTokenException()); @@ -324,7 +318,7 @@ public function testRotateInvalid(): void { public function testRotatePublicKey(): void { $token = new PublicKeyToken(); - $this->publicKeyTokenProvider + $this->mocks[PublicKeyTokenProvider::class] ->method('rotate') ->with($token, 'oldId', 'newId') ->willReturn($token); @@ -335,7 +329,7 @@ public function testRotatePublicKey(): void { public function testMarkPasswordInvalidPublicKey(): void { $token = $this->createMock(PublicKeyToken::class); - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('markPasswordInvalid') ->with($token, 'tokenId'); @@ -349,7 +343,7 @@ public function testMarkPasswordInvalidInvalidToken(): void { } public function testUpdatePasswords(): void { - $this->publicKeyTokenProvider->expects($this->once()) + $this->mocks[PublicKeyTokenProvider::class]->expects($this->once()) ->method('updatePasswords') ->with('uid', 'pass'); @@ -362,7 +356,7 @@ public function testInvalidateTokensOfUserNoClientName(): void { $t1->setId(123); $t2->setId(456); - $this->publicKeyTokenProvider + $this->mocks[PublicKeyTokenProvider::class] ->expects($this->once()) ->method('getTokenByUser') ->with('theUser') @@ -372,7 +366,7 @@ public function testInvalidateTokensOfUserNoClientName(): void { ['theUser', 123], ['theUser', 456], ]; - $this->publicKeyTokenProvider + $this->mocks[PublicKeyTokenProvider::class] ->expects($this->exactly(2)) ->method('invalidateTokenById') ->willReturnCallback(function () use (&$calls): void { @@ -393,12 +387,12 @@ public function testInvalidateTokensOfUserClientNameGiven(): void { $t3->setId(789); $t3->setName('mobile client'); - $this->publicKeyTokenProvider + $this->mocks[PublicKeyTokenProvider::class] ->expects($this->once()) ->method('getTokenByUser') ->with('theUser') ->willReturn([$t1, $t2, $t3]); - $this->publicKeyTokenProvider + $this->mocks[PublicKeyTokenProvider::class] ->expects($this->once()) ->method('invalidateTokenById') ->with('theUser', 456); diff --git a/tests/lib/Authentication/Token/RemoteWipeTest.php b/tests/lib/Authentication/Token/RemoteWipeTest.php index c5031e2527255..c84c7855d1bec 100644 --- a/tests/lib/Authentication/Token/RemoteWipeTest.php +++ b/tests/lib/Authentication/Token/RemoteWipeTest.php @@ -19,19 +19,9 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\IUser; use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; use Test\TestCase; class RemoteWipeTest extends TestCase { - /** @var ITokenProvider|MockObject */ - private $tokenProvider; - - /** @var IEventDispatcher|MockObject */ - private $eventDispatcher; - - /** @var LoggerInterface|MockObject */ - private $logger; - /** @var RemoteWipe */ private $remoteWipe; @@ -39,15 +29,7 @@ class RemoteWipeTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->tokenProvider = $this->createMock(ITokenProvider::class); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->remoteWipe = new RemoteWipe( - $this->tokenProvider, - $this->eventDispatcher, - $this->logger - ); + $this->remoteWipe = $this->createInstanceWithMocks(RemoteWipe::class); } public function testMarkNonWipableTokenForWipe(): void { @@ -61,7 +43,7 @@ public function testMarkTokenForWipe(): void { $token->expects($this->once()) ->method('wipe'); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('updateToken') ->with($token); @@ -75,7 +57,7 @@ public function testMarkAllTokensForWipeNoWipeableToken(): void { $user->method('getUID')->willReturn('user123'); $token1 = $this->createMock(IToken::class); $token2 = $this->createMock(IToken::class); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('getTokenByUser') ->with('user123') ->willReturn([$token1, $token2]); @@ -91,13 +73,13 @@ public function testMarkAllTokensForWipe(): void { $user->method('getUID')->willReturn('user123'); $token1 = $this->createMock(IToken::class); $token2 = $this->createMock(IWipeableToken::class); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('getTokenByUser') ->with('user123') ->willReturn([$token1, $token2]); $token2->expects($this->once()) ->method('wipe'); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('updateToken') ->with($token2); @@ -108,11 +90,11 @@ public function testMarkAllTokensForWipe(): void { public function testStartWipingNotAWipeToken(): void { $token = $this->createMock(IToken::class); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('getToken') ->with('tk1') ->willReturn($token); - $this->eventDispatcher->expects($this->never()) + $this->mocks[IEventDispatcher::class]->expects($this->never()) ->method('dispatch'); $result = $this->remoteWipe->start('tk1'); @@ -122,13 +104,13 @@ public function testStartWipingNotAWipeToken(): void { public function testStartWiping(): void { $token = $this->createMock(IToken::class); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('getToken') ->with('tk1') ->willThrowException(new WipeTokenException($token)); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatch'); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatch') ->with(RemoteWipeStarted::class, $this->equalTo(new RemoteWipeStarted($token))); @@ -139,11 +121,11 @@ public function testStartWiping(): void { public function testFinishWipingNotAWipeToken(): void { $token = $this->createMock(IToken::class); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('getToken') ->with('tk1') ->willReturn($token); - $this->eventDispatcher->expects($this->never()) + $this->mocks[IEventDispatcher::class]->expects($this->never()) ->method('dispatch'); $result = $this->remoteWipe->finish('tk1'); @@ -153,16 +135,16 @@ public function testFinishWipingNotAWipeToken(): void { public function startFinishWiping() { $token = $this->createMock(IToken::class); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('getToken') ->with('tk1') ->willThrowException(new WipeTokenException($token)); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatch'); - $this->tokenProvider->expects($this->once()) + $this->mocks[ITokenProvider::class]->expects($this->once()) ->method('invalidateToken') ->with($token); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatch') ->with(RemoteWipeFinished::class, $this->equalTo(new RemoteWipeFinished($token))); diff --git a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php index 9c751d487c130..85d36113cfeaa 100644 --- a/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/ManagerTest.php @@ -32,18 +32,8 @@ class ManagerTest extends TestCase { private IUser&MockObject $user; - private ProviderLoader&MockObject $providerLoader; - private IRegistry&MockObject $providerRegistry; - private MandatoryTwoFactor&MockObject $mandatoryTwoFactor; - private ISession&MockObject $session; - private IConfig&MockObject $config; - private IManager&MockObject $activityManager; - private LoggerInterface&MockObject $logger; private IProvider&MockObject $fakeProvider; private IProvider&MockObject $backupProvider; - private TokenProvider&MockObject $tokenProvider; - private ITimeFactory&MockObject $timeFactory; - private IEventDispatcher&MockObject $dispatcher; private Manager $manager; @@ -55,29 +45,8 @@ protected function setUp(): void { $this->user->expects($this->any()) ->method('getUID') ->willReturn('user-uid'); - $this->providerLoader = $this->createMock(ProviderLoader::class); - $this->providerRegistry = $this->createMock(IRegistry::class); - $this->mandatoryTwoFactor = $this->createMock(MandatoryTwoFactor::class); - $this->session = $this->createMock(ISession::class); - $this->config = $this->createMock(IConfig::class); - $this->activityManager = $this->createMock(IManager::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->tokenProvider = $this->createMock(TokenProvider::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); - $this->dispatcher = $this->createMock(IEventDispatcher::class); - - $this->manager = new Manager( - $this->providerLoader, - $this->providerRegistry, - $this->mandatoryTwoFactor, - $this->session, - $this->config, - $this->activityManager, - $this->logger, - $this->tokenProvider, - $this->timeFactory, - $this->dispatcher, - ); + + $this->manager = $this->createInstanceWithMocks(Manager::class); $this->fakeProvider = $this->createMock(IProvider::class); $this->fakeProvider->method('getId')->willReturn('email'); @@ -88,26 +57,26 @@ protected function setUp(): void { } private function prepareNoProviders() { - $this->providerLoader->method('getProviders') + $this->mocks[ProviderLoader::class]->method('getProviders') ->with($this->user) ->willReturn([]); } private function prepareProviders() { - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->with($this->user) ->willReturn([ $this->fakeProvider->getId() => true, ]); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($this->user) ->willReturn([$this->fakeProvider]); } private function prepareProvidersWitBackupProvider() { - $this->providerLoader->method('getProviders') + $this->mocks[ProviderLoader::class]->method('getProviders') ->with($this->user) ->willReturn([ $this->fakeProvider, @@ -116,7 +85,7 @@ private function prepareProvidersWitBackupProvider() { } public function testIsTwoFactorAuthenticatedEnforced(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(true); @@ -127,14 +96,14 @@ public function testIsTwoFactorAuthenticatedEnforced(): void { } public function testIsTwoFactorAuthenticatedNoProviders(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(false); - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->willReturn([]); // No providers registered - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->willReturn([]); // No providers loadable @@ -142,11 +111,11 @@ public function testIsTwoFactorAuthenticatedNoProviders(): void { } public function testIsTwoFactorAuthenticatedOnlyBackupCodes(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(false); - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->willReturn([ 'backup_codes' => true, @@ -155,7 +124,7 @@ public function testIsTwoFactorAuthenticatedOnlyBackupCodes(): void { $backupCodesProvider ->method('getId') ->willReturn('backup_codes'); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->willReturn([ $backupCodesProvider, @@ -165,17 +134,17 @@ public function testIsTwoFactorAuthenticatedOnlyBackupCodes(): void { } public function testIsTwoFactorAuthenticatedFailingProviders(): void { - $this->mandatoryTwoFactor->expects($this->once()) + $this->mocks[MandatoryTwoFactor::class]->expects($this->once()) ->method('isEnforcedFor') ->with($this->user) ->willReturn(false); - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->willReturn([ 'twofactor_totp' => true, 'twofactor_u2f' => false, ]); // Two providers registered, but … - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->willReturn([]); // … none of them is able to load, however … @@ -199,10 +168,10 @@ public static function providerStatesFixData(): array { */ #[\PHPUnit\Framework\Attributes\DataProvider('providerStatesFixData')] public function testIsTwoFactorAuthenticatedFixesProviderStates(bool $providerEnabled, bool $expected): void { - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->willReturn([]); // Nothing registered yet - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->willReturn([ $this->fakeProvider @@ -212,14 +181,14 @@ public function testIsTwoFactorAuthenticatedFixesProviderStates(bool $providerEn ->with($this->user) ->willReturn($providerEnabled); if ($providerEnabled) { - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('enableProviderFor') ->with( $this->fakeProvider, $this->user ); } else { - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('disableProviderFor') ->with( $this->fakeProvider, @@ -231,13 +200,13 @@ public function testIsTwoFactorAuthenticatedFixesProviderStates(bool $providerEn } public function testGetProvider(): void { - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->with($this->user) ->willReturn([ $this->fakeProvider->getId() => true, ]); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($this->user) ->willReturn([$this->fakeProvider]); @@ -248,11 +217,11 @@ public function testGetProvider(): void { } public function testGetInvalidProvider(): void { - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->with($this->user) ->willReturn([]); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($this->user) ->willReturn([]); @@ -265,7 +234,7 @@ public function testGetInvalidProvider(): void { public function testGetLoginSetupProviders(): void { $provider1 = $this->createMock(IProvider::class); $provider2 = $this->createMock(IActivatableAtLogin::class); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($this->user) ->willReturn([ @@ -280,13 +249,13 @@ public function testGetLoginSetupProviders(): void { } public function testGetProviders(): void { - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->with($this->user) ->willReturn([ $this->fakeProvider->getId() => true, ]); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($this->user) ->willReturn([$this->fakeProvider]); @@ -302,13 +271,13 @@ public function testGetProviders(): void { } public function testGetProvidersOneMissing(): void { - $this->providerRegistry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('getProviderStates') ->with($this->user) ->willReturn([ $this->fakeProvider->getId() => true, ]); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($this->user) ->willReturn([]); @@ -330,7 +299,7 @@ public function testVerifyChallenge(): void { ->method('verifyChallenge') ->with($this->user, $challenge) ->willReturn(true); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('get') ->with('two_factor_remember_login') ->willReturn(false); @@ -339,19 +308,19 @@ public function testVerifyChallenge(): void { ['two_factor_auth_uid'], ['two_factor_remember_login'], ]; - $this->session->expects($this->exactly(2)) + $this->mocks[ISession::class]->expects($this->exactly(2)) ->method('remove') ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('set') ->with(Manager::SESSION_UID_DONE, $this->user->getUID()); - $this->session->method('getId') + $this->mocks[ISession::class]->method('getId') ->willReturn('mysessionid'); - $this->activityManager->expects($this->once()) + $this->mocks[IManager::class]->expects($this->once()) ->method('generateEvent') ->willReturn($event); $event->expects($this->once()) @@ -380,12 +349,12 @@ public function testVerifyChallenge(): void { ])) ->willReturnSelf(); $token = $this->createMock(IToken::class); - $this->tokenProvider->method('getToken') + $this->mocks[TokenProvider::class]->method('getToken') ->with('mysessionid') ->willReturn($token); $token->method('getId') ->willReturn(42); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('deleteUserValue') ->with($this->user->getUID(), 'login_token_2fa', '42'); @@ -401,7 +370,7 @@ public function testVerifyChallengeInvalidProviderId(): void { $this->fakeProvider->expects($this->never()) ->method('verifyChallenge') ->with($this->user, $challenge); - $this->session->expects($this->never()) + $this->mocks[ISession::class]->expects($this->never()) ->method('remove'); $this->assertFalse($this->manager->verifyChallenge('dontexist', $this->user, $challenge)); @@ -416,9 +385,9 @@ public function testVerifyInvalidChallenge(): void { ->method('verifyChallenge') ->with($this->user, $challenge) ->willReturn(false); - $this->session->expects($this->never()) + $this->mocks[ISession::class]->expects($this->never()) ->method('remove'); - $this->activityManager->expects($this->once()) + $this->mocks[IManager::class]->expects($this->once()) ->method('generateEvent') ->willReturn($event); $event->expects($this->once()) @@ -458,7 +427,7 @@ public function testNeedsSecondFactor(): void { ['two_factor_auth_uid'], [Manager::SESSION_UID_DONE], ]; - $this->session->expects($this->exactly(3)) + $this->mocks[ISession::class]->expects($this->exactly(3)) ->method('exists') ->willReturnCallback(function () use (&$calls) { $expected = array_shift($calls); @@ -466,10 +435,10 @@ public function testNeedsSecondFactor(): void { return false; }); - $this->session->method('getId') + $this->mocks[ISession::class]->method('getId') ->willReturn('mysessionid'); $token = $this->createMock(IToken::class); - $this->tokenProvider->method('getToken') + $this->mocks[TokenProvider::class]->method('getToken') ->with('mysessionid') ->willReturn($token); $token->method('getId') @@ -477,7 +446,7 @@ public function testNeedsSecondFactor(): void { $user->method('getUID') ->willReturn('user'); - $this->config->method('getUserKeys') + $this->mocks[IConfig::class]->method('getUserKeys') ->with('user', 'login_token_2fa') ->willReturn([ '42' @@ -485,16 +454,16 @@ public function testNeedsSecondFactor(): void { $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->providerLoader, - $this->providerRegistry, - $this->mandatoryTwoFactor, - $this->session, - $this->config, - $this->activityManager, - $this->logger, - $this->tokenProvider, - $this->timeFactory, - $this->dispatcher, + $this->mocks[ProviderLoader::class], + $this->mocks[IRegistry::class], + $this->mocks[MandatoryTwoFactor::class], + $this->mocks[ISession::class], + $this->mocks[IConfig::class], + $this->mocks[IManager::class], + $this->mocks[LoggerInterface::class], + $this->mocks[TokenProvider::class], + $this->mocks[ITimeFactory::class], + $this->mocks[IEventDispatcher::class], ]) ->onlyMethods(['isTwoFactorAuthenticated'])// Do not actually load the apps ->getMock(); @@ -508,7 +477,7 @@ public function testNeedsSecondFactor(): void { public function testNeedsSecondFactorUserIsNull(): void { $user = null; - $this->session->expects($this->never()) + $this->mocks[ISession::class]->expects($this->never()) ->method('exists'); $this->assertFalse($this->manager->needsSecondFactor($user)); @@ -518,11 +487,11 @@ public function testNeedsSecondFactorWithNoProviderAvailableAnymore(): void { $this->prepareNoProviders(); $user = null; - $this->session->expects($this->never()) + $this->mocks[ISession::class]->expects($this->never()) ->method('exists') ->with('two_factor_auth_uid') ->willReturn(true); - $this->session->expects($this->never()) + $this->mocks[ISession::class]->expects($this->never()) ->method('remove') ->with('two_factor_auth_uid'); @@ -534,26 +503,26 @@ public function testPrepareTwoFactorLogin(): void { ['two_factor_auth_uid', $this->user->getUID()], ['two_factor_remember_login', true], ]; - $this->session->expects($this->exactly(2)) + $this->mocks[ISession::class]->expects($this->exactly(2)) ->method('set') ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); - $this->session->method('getId') + $this->mocks[ISession::class]->method('getId') ->willReturn('mysessionid'); $token = $this->createMock(IToken::class); - $this->tokenProvider->method('getToken') + $this->mocks[TokenProvider::class]->method('getToken') ->with('mysessionid') ->willReturn($token); $token->method('getId') ->willReturn(42); - $this->timeFactory->method('getTime') + $this->mocks[ITimeFactory::class]->method('getTime') ->willReturn(1337); - $this->config->method('setUserValue') + $this->mocks[IConfig::class]->method('setUserValue') ->with($this->user->getUID(), 'login_token_2fa', '42', '1337'); $this->manager->prepareTwoFactorLogin($this->user, true); @@ -564,26 +533,26 @@ public function testPrepareTwoFactorLoginDontRemember(): void { ['two_factor_auth_uid', $this->user->getUID()], ['two_factor_remember_login', false], ]; - $this->session->expects($this->exactly(2)) + $this->mocks[ISession::class]->expects($this->exactly(2)) ->method('set') ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); $this->assertEquals($expected, func_get_args()); }); - $this->session->method('getId') + $this->mocks[ISession::class]->method('getId') ->willReturn('mysessionid'); $token = $this->createMock(IToken::class); - $this->tokenProvider->method('getToken') + $this->mocks[TokenProvider::class]->method('getToken') ->with('mysessionid') ->willReturn($token); $token->method('getId') ->willReturn(42); - $this->timeFactory->method('getTime') + $this->mocks[ITimeFactory::class]->method('getTime') ->willReturn(1337); - $this->config->method('setUserValue') + $this->mocks[IConfig::class]->method('setUserValue') ->with($this->user->getUID(), 'login_token_2fa', '42', '1337'); $this->manager->prepareTwoFactorLogin($this->user, false); @@ -594,7 +563,7 @@ public function testNeedsSecondFactorSessionAuth(): void { $user->method('getUID') ->willReturn('user'); - $this->session->method('exists') + $this->mocks[ISession::class]->method('exists') ->willReturnCallback(function ($var) { if ($var === Manager::SESSION_UID_KEY) { return false; @@ -605,7 +574,7 @@ public function testNeedsSecondFactorSessionAuth(): void { } return true; }); - $this->session->method('get') + $this->mocks[ISession::class]->method('get') ->willReturnCallback(function ($var) { if ($var === Manager::SESSION_UID_KEY) { return 'user'; @@ -614,7 +583,7 @@ public function testNeedsSecondFactorSessionAuth(): void { } return null; }); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('get') ->willReturnMap([ [Manager::SESSION_UID_DONE, 'user'], @@ -629,26 +598,26 @@ public function testNeedsSecondFactorSessionAuthFailDBPass(): void { $user->method('getUID') ->willReturn('user'); - $this->session->method('exists') + $this->mocks[ISession::class]->method('exists') ->willReturn(false); - $this->session->method('getId') + $this->mocks[ISession::class]->method('getId') ->willReturn('mysessionid'); $token = $this->createMock(IToken::class); $token->method('getId') ->willReturn(40); - $this->tokenProvider->method('getToken') + $this->mocks[TokenProvider::class]->method('getToken') ->with('mysessionid') ->willReturn($token); - $this->config->method('getUserKeys') + $this->mocks[IConfig::class]->method('getUserKeys') ->with('user', 'login_token_2fa') ->willReturn([ '42', '43', '44' ]); - $this->session->expects($this->once()) + $this->mocks[ISession::class]->expects($this->once()) ->method('set') ->with(Manager::SESSION_UID_DONE, 'user'); @@ -662,23 +631,23 @@ public function testNeedsSecondFactorInvalidToken(): void { $user->method('getUID') ->willReturn('user'); - $this->session->method('exists') + $this->mocks[ISession::class]->method('exists') ->willReturn(false); - $this->session->method('getId') + $this->mocks[ISession::class]->method('getId') ->willReturn('mysessionid'); - $this->tokenProvider->method('getToken') + $this->mocks[TokenProvider::class]->method('getToken') ->with('mysessionid') ->willThrowException(new InvalidTokenException()); - $this->config->method('getUserKeys')->willReturn([]); + $this->mocks[IConfig::class]->method('getUserKeys')->willReturn([]); $this->assertFalse($this->manager->needsSecondFactor($user)); } public function testNeedsSecondFactorAppPassword(): void { $user = $this->createMock(IUser::class); - $this->session->method('exists') + $this->mocks[ISession::class]->method('exists') ->willReturnMap([ ['app_password', true], ['app_api', true] @@ -688,7 +657,7 @@ public function testNeedsSecondFactorAppPassword(): void { } public function testClearTwoFactorPending() { - $this->config->method('getUserKeys') + $this->mocks[IConfig::class]->method('getUserKeys') ->with('theUserId', 'login_token_2fa') ->willReturn([ '42', '43', '44' @@ -699,7 +668,7 @@ public function testClearTwoFactorPending() { ['theUserId', 'login_token_2fa', '43'], ['theUserId', 'login_token_2fa', '44'], ]; - $this->config->expects($this->exactly(3)) + $this->mocks[IConfig::class]->expects($this->exactly(3)) ->method('deleteUserValue') ->willReturnCallback(function () use (&$deleteUserValueCalls): void { $expected = array_shift($deleteUserValueCalls); @@ -711,7 +680,7 @@ public function testClearTwoFactorPending() { ['theUserId', 43], ['theUserId', 44], ]; - $this->tokenProvider->expects($this->exactly(3)) + $this->mocks[TokenProvider::class]->expects($this->exactly(3)) ->method('invalidateTokenById') ->willReturnCallback(function () use (&$invalidateCalls): void { $expected = array_shift($invalidateCalls); @@ -722,7 +691,7 @@ public function testClearTwoFactorPending() { } public function testClearTwoFactorPendingTokenDoesNotExist() { - $this->config->method('getUserKeys') + $this->mocks[IConfig::class]->method('getUserKeys') ->with('theUserId', 'login_token_2fa') ->willReturn([ '42', '43', '44' @@ -733,7 +702,7 @@ public function testClearTwoFactorPendingTokenDoesNotExist() { ['theUserId', 'login_token_2fa', '43'], ['theUserId', 'login_token_2fa', '44'], ]; - $this->config->expects($this->exactly(3)) + $this->mocks[IConfig::class]->expects($this->exactly(3)) ->method('deleteUserValue') ->willReturnCallback(function () use (&$deleteUserValueCalls): void { $expected = array_shift($deleteUserValueCalls); @@ -745,7 +714,7 @@ public function testClearTwoFactorPendingTokenDoesNotExist() { ['theUserId', 43], ['theUserId', 44], ]; - $this->tokenProvider->expects($this->exactly(3)) + $this->mocks[TokenProvider::class]->expects($this->exactly(3)) ->method('invalidateTokenById') ->willReturnCallback(function ($user, $tokenId) use (&$invalidateCalls): void { $expected = array_shift($invalidateCalls); diff --git a/tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php b/tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php index 5b24a4a25b1b9..71560614e68cd 100644 --- a/tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/MandatoryTwoFactorTest.php @@ -14,16 +14,9 @@ use OCP\IConfig; use OCP\IGroupManager; use OCP\IUser; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class MandatoryTwoFactorTest extends TestCase { - /** @var IConfig|MockObject */ - private $config; - - /** @var IGroupManager|MockObject */ - private $groupManager; - /** @var MandatoryTwoFactor */ private $mandatoryTwoFactor; @@ -31,14 +24,11 @@ class MandatoryTwoFactorTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->groupManager = $this->createMock(IGroupManager::class); - - $this->mandatoryTwoFactor = new MandatoryTwoFactor($this->config, $this->groupManager); + $this->mandatoryTwoFactor = $this->createInstanceWithMocks(MandatoryTwoFactor::class); } public function testIsNotEnforced(): void { - $this->config + $this->mocks[IConfig::class] ->method('getSystemValue') ->willReturnMap([ ['twofactor_enforced', 'false', 'false'], @@ -52,7 +42,7 @@ public function testIsNotEnforced(): void { } public function testIsEnforced(): void { - $this->config + $this->mocks[IConfig::class] ->method('getSystemValue') ->willReturnMap([ ['twofactor_enforced', 'false', 'true'], @@ -68,7 +58,7 @@ public function testIsEnforced(): void { public function testIsNotEnforcedForAnybody(): void { $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user123'); - $this->config + $this->mocks[IConfig::class] ->method('getSystemValue') ->willReturnMap([ ['twofactor_enforced', 'false', 'false'], @@ -84,14 +74,14 @@ public function testIsNotEnforcedForAnybody(): void { public function testIsEnforcedForAGroupMember(): void { $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user123'); - $this->config + $this->mocks[IConfig::class] ->method('getSystemValue') ->willReturnMap([ ['twofactor_enforced', 'false', 'true'], ['twofactor_enforced_groups', [], ['twofactorers']], ['twofactor_enforced_excluded_groups', [], []], ]); - $this->groupManager->method('isInGroup') + $this->mocks[IGroupManager::class]->method('isInGroup') ->willReturnCallback(function ($user, $group) { return $user === 'user123' && $group === 'twofactorers'; }); @@ -104,14 +94,14 @@ public function testIsEnforcedForAGroupMember(): void { public function testIsEnforcedForOtherGroups(): void { $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user123'); - $this->config + $this->mocks[IConfig::class] ->method('getSystemValue') ->willReturnMap([ ['twofactor_enforced', 'false', 'true'], ['twofactor_enforced_groups', [], ['twofactorers']], ['twofactor_enforced_excluded_groups', [], []], ]); - $this->groupManager->method('isInGroup') + $this->mocks[IGroupManager::class]->method('isInGroup') ->willReturn(false); $isEnforced = $this->mandatoryTwoFactor->isEnforcedFor($user); @@ -122,14 +112,14 @@ public function testIsEnforcedForOtherGroups(): void { public function testIsEnforcedButMemberOfExcludedGroup(): void { $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user123'); - $this->config + $this->mocks[IConfig::class] ->method('getSystemValue') ->willReturnMap([ ['twofactor_enforced', 'false', 'true'], ['twofactor_enforced_groups', [], []], ['twofactor_enforced_excluded_groups', [], ['yoloers']], ]); - $this->groupManager->method('isInGroup') + $this->mocks[IGroupManager::class]->method('isInGroup') ->willReturnCallback(function ($user, $group) { return $user === 'user123' && $group === 'yoloers'; }); @@ -140,7 +130,7 @@ public function testIsEnforcedButMemberOfExcludedGroup(): void { } public function testSetEnforced(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('setSystemValue') ->willReturnMap([ @@ -153,7 +143,7 @@ public function testSetEnforced(): void { } public function testSetEnforcedForGroups(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('setSystemValue') ->willReturnMap([ @@ -166,7 +156,7 @@ public function testSetEnforcedForGroups(): void { } public function testSetNotEnforced(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('setSystemValue') ->willReturnMap([ diff --git a/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php b/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php index 0418e277ada6d..a7b5f2792925f 100644 --- a/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/ProviderManagerTest.php @@ -17,16 +17,9 @@ use OCP\Authentication\TwoFactorAuth\IProvider; use OCP\Authentication\TwoFactorAuth\IRegistry; use OCP\IUser; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ProviderManagerTest extends TestCase { - /** @var ProviderLoader|MockObject */ - private $providerLoader; - - /** @var IRegistry|MockObject */ - private $registry; - /** @var ProviderManager */ private $providerManager; @@ -34,13 +27,7 @@ class ProviderManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->providerLoader = $this->createMock(ProviderLoader::class); - $this->registry = $this->createMock(IRegistry::class); - - $this->providerManager = new ProviderManager( - $this->providerLoader, - $this->registry - ); + $this->providerManager = $this->createInstanceWithMocks(ProviderManager::class); } public function testTryEnableInvalidProvider(): void { @@ -53,13 +40,13 @@ public function testTryEnableInvalidProvider(): void { public function testTryEnableUnsupportedProvider(): void { $user = $this->createMock(IUser::class); $provider = $this->createMock(IProvider::class); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($user) ->willReturn([ 'u2f' => $provider, ]); - $this->registry->expects($this->never()) + $this->mocks[IRegistry::class]->expects($this->never()) ->method('enableProviderFor'); $res = $this->providerManager->tryEnableProviderFor('u2f', $user); @@ -70,7 +57,7 @@ public function testTryEnableUnsupportedProvider(): void { public function testTryEnableProvider(): void { $user = $this->createMock(IUser::class); $provider = $this->createMock(IActivatableByAdmin::class); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($user) ->willReturn([ @@ -79,7 +66,7 @@ public function testTryEnableProvider(): void { $provider->expects($this->once()) ->method('enableFor') ->with($user); - $this->registry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('enableProviderFor') ->with($provider, $user); @@ -98,13 +85,13 @@ public function testTryDisableInvalidProvider(): void { public function testTryDisableUnsupportedProvider(): void { $user = $this->createMock(IUser::class); $provider = $this->createMock(IProvider::class); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($user) ->willReturn([ 'u2f' => $provider, ]); - $this->registry->expects($this->never()) + $this->mocks[IRegistry::class]->expects($this->never()) ->method('disableProviderFor'); $res = $this->providerManager->tryDisableProviderFor('u2f', $user); @@ -115,7 +102,7 @@ public function testTryDisableUnsupportedProvider(): void { public function testTryDisableProvider(): void { $user = $this->createMock(IUser::class); $provider = $this->createMock(IDeactivatableByAdmin::class); - $this->providerLoader->expects($this->once()) + $this->mocks[ProviderLoader::class]->expects($this->once()) ->method('getProviders') ->with($user) ->willReturn([ @@ -124,7 +111,7 @@ public function testTryDisableProvider(): void { $provider->expects($this->once()) ->method('disableFor') ->with($user); - $this->registry->expects($this->once()) + $this->mocks[IRegistry::class]->expects($this->once()) ->method('disableProviderFor') ->with($provider, $user); diff --git a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php index 816b730df103f..1aa2c8408a505 100644 --- a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php @@ -21,22 +21,16 @@ use OCP\Authentication\TwoFactorAuth\TwoFactorProviderUserDeleted; use OCP\EventDispatcher\IEventDispatcher; use OCP\IUser; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RegistryTest extends TestCase { - private ProviderUserAssignmentDao&MockObject $dao; - private IEventDispatcher&MockObject $dispatcher; private Registry $registry; #[\Override] protected function setUp(): void { parent::setUp(); - $this->dao = $this->createMock(ProviderUserAssignmentDao::class); - $this->dispatcher = $this->createMock(IEventDispatcher::class); - - $this->registry = new Registry($this->dao, $this->dispatcher); + $this->registry = $this->createInstanceWithMocks(Registry::class); } public function testGetProviderStates(): void { @@ -45,7 +39,7 @@ public function testGetProviderStates(): void { $state = [ 'twofactor_totp' => true, ]; - $this->dao->expects($this->once())->method('getState')->willReturn($state); + $this->mocks[ProviderUserAssignmentDao::class]->expects($this->once())->method('getState')->willReturn($state); $actual = $this->registry->getProviderStates($user); @@ -57,10 +51,10 @@ public function testEnableProvider(): void { $provider = $this->createMock(IProvider::class); $user->expects($this->once())->method('getUID')->willReturn('user123'); $provider->expects($this->once())->method('getId')->willReturn('p1'); - $this->dao->expects($this->once())->method('persist')->with('p1', 'user123', + $this->mocks[ProviderUserAssignmentDao::class]->expects($this->once())->method('persist')->with('p1', 'user123', true); - $this->dispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatch') ->with( $this->equalTo(IRegistry::EVENT_PROVIDER_ENABLED), @@ -68,7 +62,7 @@ public function testEnableProvider(): void { return $e->getUser() === $user && $e->getProvider() === $provider; }) ); - $this->dispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with(new TwoFactorProviderForUserRegistered( $user, @@ -82,10 +76,10 @@ public function testEnableStatelessProvider(): void { $user = $this->createMock(IUser::class); $provider = $this->createMock(IStatelessProvider::class); - $this->dao->expects($this->never())->method('persist'); + $this->mocks[ProviderUserAssignmentDao::class]->expects($this->never())->method('persist'); - $this->dispatcher->expects($this->never())->method('dispatch'); - $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->mocks[IEventDispatcher::class]->expects($this->never())->method('dispatch'); + $this->mocks[IEventDispatcher::class]->expects($this->never())->method('dispatchTyped'); $this->registry->enableProviderFor($provider, $user); } @@ -95,10 +89,10 @@ public function testDisableProvider(): void { $provider = $this->createMock(IProvider::class); $user->expects($this->once())->method('getUID')->willReturn('user123'); $provider->expects($this->once())->method('getId')->willReturn('p1'); - $this->dao->expects($this->once())->method('persist')->with('p1', 'user123', + $this->mocks[ProviderUserAssignmentDao::class]->expects($this->once())->method('persist')->with('p1', 'user123', false); - $this->dispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatch') ->with( $this->equalTo(IRegistry::EVENT_PROVIDER_DISABLED), @@ -106,7 +100,7 @@ public function testDisableProvider(): void { return $e->getUser() === $user && $e->getProvider() === $provider; }) ); - $this->dispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with(new TwoFactorProviderForUserUnregistered( $user, @@ -120,10 +114,10 @@ public function testDisableStatelessProvider(): void { $user = $this->createMock(IUser::class); $provider = $this->createMock(IStatelessProvider::class); - $this->dao->expects($this->never())->method('persist'); + $this->mocks[ProviderUserAssignmentDao::class]->expects($this->never())->method('persist'); - $this->dispatcher->expects($this->never())->method('dispatch'); - $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->mocks[IEventDispatcher::class]->expects($this->never())->method('dispatch'); + $this->mocks[IEventDispatcher::class]->expects($this->never())->method('dispatchTyped'); $this->registry->disableProviderFor($provider, $user); } @@ -131,7 +125,7 @@ public function testDisableStatelessProvider(): void { public function testDeleteUserData(): void { $user = $this->createMock(IUser::class); $user->expects($this->once())->method('getUID')->willReturn('user123'); - $this->dao->expects($this->once()) + $this->mocks[ProviderUserAssignmentDao::class]->expects($this->once()) ->method('deleteByUser') ->with('user123') ->willReturn([ @@ -144,7 +138,7 @@ public function testDeleteUserData(): void { [new TwoFactorProviderDisabled('twofactor_u2f')], [new TwoFactorProviderUserDeleted($user, 'twofactor_u2f')], ]; - $this->dispatcher->expects($this->exactly(2)) + $this->mocks[IEventDispatcher::class]->expects($this->exactly(2)) ->method('dispatchTyped') ->willReturnCallback(function () use (&$calls): void { $expected = array_shift($calls); @@ -155,7 +149,7 @@ public function testDeleteUserData(): void { } public function testCleanUp(): void { - $this->dao->expects($this->once()) + $this->mocks[ProviderUserAssignmentDao::class]->expects($this->once()) ->method('deleteAll') ->with('twofactor_u2f'); diff --git a/tests/lib/Avatar/AvatarManagerTest.php b/tests/lib/Avatar/AvatarManagerTest.php index 61fabf58d5bf3..70874e80fa721 100644 --- a/tests/lib/Avatar/AvatarManagerTest.php +++ b/tests/lib/Avatar/AvatarManagerTest.php @@ -33,54 +33,14 @@ * Class AvatarManagerTest */ class AvatarManagerTest extends \Test\TestCase { - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; - /** @var Manager|\PHPUnit\Framework\MockObject\MockObject */ - private $userManager; - /** @var IAppData|\PHPUnit\Framework\MockObject\MockObject */ - private $appData; - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ - private $l10n; - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; - /** @var IAccountManager|\PHPUnit\Framework\MockObject\MockObject */ - private $accountManager; /** @var AvatarManager | \PHPUnit\Framework\MockObject\MockObject */ private $avatarManager; - /** @var KnownUserService | \PHPUnit\Framework\MockObject\MockObject */ - private $knownUserService; - private ICloudIdManager&\PHPUnit\Framework\MockObject\MockObject $cloudIdManager; - private IUserConfig&\PHPUnit\Framework\MockObject\MockObject $userConfig; #[\Override] protected function setUp(): void { parent::setUp(); - $this->userSession = $this->createMock(IUserSession::class); - $this->userManager = $this->createMock(Manager::class); - $this->appData = $this->createMock(IAppData::class); - $this->l10n = $this->createMock(IL10N::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->config = $this->createMock(IConfig::class); - $this->accountManager = $this->createMock(IAccountManager::class); - $this->knownUserService = $this->createMock(KnownUserService::class); - $this->cloudIdManager = $this->createMock(ICloudIdManager::class); - $this->userConfig = $this->createMock(IUserConfig::class); - - $this->avatarManager = new AvatarManager( - $this->userSession, - $this->userManager, - $this->appData, - $this->l10n, - $this->logger, - $this->config, - $this->accountManager, - $this->knownUserService, - $this->cloudIdManager, - $this->userConfig, - ); + $this->avatarManager = $this->createInstanceWithMocks(AvatarManager::class); } public function testGetAvatarForSelf(): void { @@ -96,18 +56,18 @@ public function testGetAvatarForSelf(): void { ->willReturn(true); // requesting user - $this->userSession->expects($this->once()) + $this->mocks[IUserSession::class]->expects($this->once()) ->method('getUser') ->willReturn($user); - $this->userManager + $this->mocks[Manager::class] ->expects($this->once()) ->method('get') ->with('valid-user') ->willReturn($user); $account = $this->createMock(IAccount::class); - $this->accountManager->expects($this->once()) + $this->mocks[IAccountManager::class]->expects($this->once()) ->method('getAccount') ->with($user) ->willReturn($account); @@ -122,25 +82,25 @@ public function testGetAvatarForSelf(): void { ->method('getScope') ->willReturn(IAccountManager::SCOPE_PRIVATE); - $this->knownUserService->expects($this->any()) + $this->mocks[KnownUserService::class]->expects($this->any()) ->method('isKnownToUser') ->with('valid-user', 'valid-user') ->willReturn(true); $folder = $this->createMock(ISimpleFolder::class); - $this->appData + $this->mocks[IAppData::class] ->expects($this->once()) ->method('getFolder') ->with('valid-user') ->willReturn($folder); - $expected = new UserAvatar($folder, $this->l10n, $user, $this->logger, $this->config, $this->userConfig); + $expected = new UserAvatar($folder, $this->mocks[IL10N::class], $user, $this->mocks[LoggerInterface::class], $this->mocks[IConfig::class], $this->mocks[IUserConfig::class]); $this->assertEquals($expected, $this->avatarManager->getAvatar('valid-user')); } public function testGetAvatarValidUserDifferentCasing(): void { $user = $this->createMock(User::class); - $this->userManager->expects($this->once()) + $this->mocks[Manager::class]->expects($this->once()) ->method('get') ->with('vaLid-USER') ->willReturn($user); @@ -154,19 +114,19 @@ public function testGetAvatarValidUserDifferentCasing(): void { ->method('isEnabled') ->willReturn(true); - $this->userSession->expects($this->once()) + $this->mocks[IUserSession::class]->expects($this->once()) ->method('getUser') ->willReturn($user); $folder = $this->createMock(ISimpleFolder::class); - $this->appData + $this->mocks[IAppData::class] ->expects($this->once()) ->method('getFolder') ->with('valid-user') ->willReturn($folder); $account = $this->createMock(IAccount::class); - $this->accountManager->expects($this->once()) + $this->mocks[IAccountManager::class]->expects($this->once()) ->method('getAccount') ->with($user) ->willReturn($account); @@ -181,7 +141,7 @@ public function testGetAvatarValidUserDifferentCasing(): void { ->method('getScope') ->willReturn(IAccountManager::SCOPE_FEDERATED); - $expected = new UserAvatar($folder, $this->l10n, $user, $this->logger, $this->config, $this->userConfig); + $expected = new UserAvatar($folder, $this->mocks[IL10N::class], $user, $this->mocks[LoggerInterface::class], $this->mocks[IConfig::class], $this->mocks[IUserConfig::class]); $this->assertEquals($expected, $this->avatarManager->getAvatar('vaLid-USER')); } @@ -212,7 +172,7 @@ public function testGetAvatarScopes($avatarScope, $isPublicCall, $isKnownUser, $ } // requesting user - $this->userSession->expects($this->once()) + $this->mocks[IUserSession::class]->expects($this->once()) ->method('getUser') ->willReturn($requestingUser); @@ -227,14 +187,14 @@ public function testGetAvatarScopes($avatarScope, $isPublicCall, $isKnownUser, $ ->method('isEnabled') ->willReturn(true); - $this->userManager + $this->mocks[Manager::class] ->expects($this->once()) ->method('get') ->with('valid-user') ->willReturn($user); $account = $this->createMock(IAccount::class); - $this->accountManager->expects($this->once()) + $this->mocks[IAccountManager::class]->expects($this->once()) ->method('getAccount') ->with($user) ->willReturn($account); @@ -250,26 +210,26 @@ public function testGetAvatarScopes($avatarScope, $isPublicCall, $isKnownUser, $ ->willReturn($avatarScope); $folder = $this->createMock(ISimpleFolder::class); - $this->appData + $this->mocks[IAppData::class] ->expects($this->once()) ->method('getFolder') ->with('valid-user') ->willReturn($folder); if (!$isPublicCall) { - $this->knownUserService->expects($this->any()) + $this->mocks[KnownUserService::class]->expects($this->any()) ->method('isKnownToUser') ->with('requesting-user', 'valid-user') ->willReturn($isKnownUser); } else { - $this->knownUserService->expects($this->never()) + $this->mocks[KnownUserService::class]->expects($this->never()) ->method('isKnownToUser'); } if ($expectedPlaceholder) { - $expected = new PlaceholderAvatar($folder, $user, $this->config, $this->logger, $this->userConfig); + $expected = new PlaceholderAvatar($folder, $user, $this->mocks[IConfig::class], $this->mocks[LoggerInterface::class], $this->mocks[IUserConfig::class]); } else { - $expected = new UserAvatar($folder, $this->l10n, $user, $this->logger, $this->config, $this->userConfig); + $expected = new UserAvatar($folder, $this->mocks[IL10N::class], $user, $this->mocks[LoggerInterface::class], $this->mocks[IConfig::class], $this->mocks[IUserConfig::class]); } $this->assertEquals($expected, $this->avatarManager->getAvatar('valid-user')); } @@ -288,19 +248,19 @@ public function testCanCacheAvatarLongTerm(string $scope, bool $enabled, bool $e $user = $this->createMock(User::class); $user->method('getUID')->willReturn('valid-user'); $user->method('isEnabled')->willReturn($enabled); - $this->userManager->method('get')->with('valid-user')->willReturn($user); + $this->mocks[Manager::class]->method('get')->with('valid-user')->willReturn($user); $property = $this->createMock(IAccountProperty::class); $property->method('getScope')->willReturn($scope); $account = $this->createMock(IAccount::class); $account->method('getProperty')->with(IAccountManager::PROPERTY_AVATAR)->willReturn($property); - $this->accountManager->method('getAccount')->with($user)->willReturn($account); + $this->mocks[IAccountManager::class]->method('getAccount')->with($user)->willReturn($account); $this->assertEquals($expected, $this->avatarManager->canCacheAvatarLongTerm('valid-user')); } public function testCannotCacheAnAvatarForAnUnknownUser(): void { - $this->userManager->method('get')->with('nobody')->willReturn(null); + $this->mocks[Manager::class]->method('get')->with('nobody')->willReturn(null); $this->assertFalse($this->avatarManager->canCacheAvatarLongTerm('nobody')); } @@ -309,7 +269,7 @@ public function testGetAvatarInvalidUser(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('user does not exist'); - $this->userManager + $this->mocks[Manager::class] ->expects($this->once()) ->method('get') ->with('invalidUser') @@ -321,7 +281,7 @@ public function testGetAvatarInvalidUser(): void { public function testGetAvatarForRemoteUser(): void { $cloudId = 'user@https://remote.example.com'; - $this->userManager + $this->mocks[Manager::class] ->expects($this->once()) ->method('get') ->willReturn(null); @@ -331,17 +291,17 @@ public function testGetAvatarForRemoteUser(): void { $resolvedCloudId->method('getRemote')->willReturn('https://remote.example.com'); $resolvedCloudId->method('getDisplayId')->willReturn('user@remote.example.com'); - $this->cloudIdManager->expects($this->once()) + $this->mocks[ICloudIdManager::class]->expects($this->once()) ->method('isValidCloudId') ->with($cloudId) ->willReturn(true); - $this->cloudIdManager->method('resolveCloudId') + $this->mocks[ICloudIdManager::class]->method('resolveCloudId') ->with($cloudId) ->willReturn($resolvedCloudId); - $this->overwriteService(ICloudIdManager::class, $this->cloudIdManager); + $this->overwriteService(ICloudIdManager::class, $this->mocks[ICloudIdManager::class]); - $this->appData->expects($this->once())->method('getFolder'); - $this->accountManager->expects($this->never())->method('getAccount'); + $this->mocks[IAppData::class]->expects($this->once())->method('getFolder'); + $this->mocks[IAccountManager::class]->expects($this->never())->method('getAccount'); $avatar = $this->avatarManager->getAvatar($cloudId); @@ -355,13 +315,13 @@ public function testGetAvatarThrowsForUnknownUserThatIsNotACloudId(): void { $this->expectException(\Exception::class); $this->expectExceptionMessage('user does not exist'); - $this->userManager + $this->mocks[Manager::class] ->expects($this->once()) ->method('get') ->with('invalidUser') ->willReturn(null); - $this->cloudIdManager->expects($this->once()) + $this->mocks[ICloudIdManager::class]->expects($this->once()) ->method('isValidCloudId') ->with('invalidUser') ->willReturn(false); diff --git a/tests/lib/Calendar/ManagerTest.php b/tests/lib/Calendar/ManagerTest.php index ba527b7209749..ae16d8c4dc943 100644 --- a/tests/lib/Calendar/ManagerTest.php +++ b/tests/lib/Calendar/ManagerTest.php @@ -49,28 +49,9 @@ interface ITestCalendarWithoutImip extends ICreateFromString, ICalendarIsWritabl } class ManagerTest extends TestCase { - /** @var Coordinator&MockObject */ - private $coordinator; - - /** @var ContainerInterface&MockObject */ - private $container; - - /** @var LoggerInterface&MockObject */ - private $logger; - /** @var Manager */ private $manager; - /** @var ITimeFactory&MockObject */ - private $time; - - /** @var ISecureRandom&MockObject */ - private ISecureRandom $secureRandom; - - private IUserManager&MockObject $userManager; - private ServerFactory&MockObject $serverFactory; - private PropertyMapper&MockObject $propertyMapper; - private VCalendar $vCalendar1a; private VCalendar $vCalendar2a; private VCalendar $vCalendar3a; @@ -79,25 +60,7 @@ class ManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->coordinator = $this->createMock(Coordinator::class); - $this->container = $this->createMock(ContainerInterface::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->time = $this->createMock(ITimeFactory::class); - $this->secureRandom = $this->createMock(ISecureRandom::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->serverFactory = $this->createMock(ServerFactory::class); - $this->propertyMapper = $this->createMock(PropertyMapper::class); - - $this->manager = new Manager( - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, - ); + $this->manager = $this->createInstanceWithMocks(Manager::class); // construct calendar with a 1 hour event and same start/end time zones $this->vCalendar1a = new VCalendar(); @@ -333,14 +296,14 @@ public function testHandleImipWithNoCalendars(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -348,7 +311,7 @@ public function testHandleImipWithNoCalendars(): void { ->method('getCalendarsForPrincipal') ->willReturn([]); // construct logger returns - $this->logger->expects(self::once())->method('warning') + $this->mocks[LoggerInterface::class]->expects(self::once())->method('warning') ->with('iMip message could not be processed because user has no calendar that can process iMip messages'); // construct parameters $userId = 'attendee1'; @@ -373,14 +336,14 @@ public function testHandleImipWithNoEvent(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -388,7 +351,7 @@ public function testHandleImipWithNoEvent(): void { ->method('getCalendarsForPrincipal') ->willReturn([$userCalendar]); // construct logger returns - $this->logger->expects(self::once())->method('warning') + $this->mocks[LoggerInterface::class]->expects(self::once())->method('warning') ->with('iMip message does not contain any event(s)'); // construct parameters $userId = 'attendee1'; @@ -417,14 +380,14 @@ public function testHandleImipMissingOrganizerWithRecipient(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -456,14 +419,14 @@ public function testHandleImipMissingOrganizerNoRecipient(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -476,7 +439,7 @@ public function testHandleImipMissingOrganizerNoRecipient(): void { $calendar->add('METHOD', 'REQUEST'); $calendar->VEVENT->remove('ORGANIZER'); // Logger expects warning - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('warning') ->with('iMip message event does not contain an organizer and no recipient was provided'); @@ -496,14 +459,14 @@ public function testHandleImipWithNoUid(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -511,7 +474,7 @@ public function testHandleImipWithNoUid(): void { ->method('getCalendarsForPrincipal') ->willReturn([$userCalendar]); // construct logger returns - $this->logger->expects(self::once())->method('warning') + $this->mocks[LoggerInterface::class]->expects(self::once())->method('warning') ->with('iMip message event does not contains a UID'); // construct parameters $userId = 'attendee1'; @@ -540,14 +503,14 @@ public function testHandleImipWithNoMatch(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -555,7 +518,7 @@ public function testHandleImipWithNoMatch(): void { ->method('getCalendarsForPrincipal') ->willReturn([$userCalendar]); // construct logger returns - $this->logger->expects(self::once())->method('warning') + $this->mocks[LoggerInterface::class]->expects(self::once())->method('warning') ->with('iMip message could not be processed because no corresponding event was found in any calendar'); // construct parameters $userId = 'attendee1'; @@ -576,14 +539,14 @@ public function testHandleImipWithCalendarUnableToHandleImip(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -591,7 +554,7 @@ public function testHandleImipWithCalendarUnableToHandleImip(): void { ->method('getCalendarsForPrincipal') ->willReturn([$userCalendar]); // construct logger returns - $this->logger->expects(self::once())->method('warning') + $this->mocks[LoggerInterface::class]->expects(self::once())->method('warning') ->with('iMip message could not be processed because user has no calendar that can process iMip messages'); // construct parameters $userId = 'attendee1'; @@ -619,14 +582,14 @@ public function testHandleImip(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -660,14 +623,14 @@ public function testHandleImipWithAbsentCreateOption(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal', 'getPrimaryCalendar']) ->getMock(); @@ -712,14 +675,14 @@ public function testHandleImipWithAbsentIgnoreOption(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal']) ->getMock(); @@ -727,7 +690,7 @@ public function testHandleImipWithAbsentIgnoreOption(): void { ->method('getCalendarsForPrincipal') ->willReturn([$userCalendar]); // construct logger returns - should log warning since event not found and absent=ignore - $this->logger->expects(self::once())->method('warning') + $this->mocks[LoggerInterface::class]->expects(self::once())->method('warning') ->with('iMip message could not be processed because no corresponding event was found in any calendar'); // construct parameters $userId = 'attendee1'; @@ -753,14 +716,14 @@ public function testHandleImipWithAbsentCreateNoWritableCalendar(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal', 'getPrimaryCalendar']) ->getMock(); @@ -770,7 +733,7 @@ public function testHandleImipWithAbsentCreateNoWritableCalendar(): void { $manager->expects(self::never()) ->method('getPrimaryCalendar'); // construct logger returns - $this->logger->expects(self::once())->method('warning') + $this->mocks[LoggerInterface::class]->expects(self::once())->method('warning') ->with('iMip message could not be processed because user has no calendar that can process iMip messages'); // construct parameters $userId = 'attendee1'; @@ -809,14 +772,14 @@ public function testHandleImipWithAbsentCreateUsesPrimaryCalendar(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal', 'getPrimaryCalendar']) ->getMock(); @@ -861,14 +824,14 @@ public function testHandleImipWithAbsentCreateOverwritesExistingStatus(): void { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['getCalendarsForPrincipal', 'getPrimaryCalendar']) ->getMock(); @@ -904,7 +867,7 @@ public function testhandleIMipRequestWithInvalidPrincipal() { $recipient = 'recipient@example.com'; $calendarData = $this->vCalendar1a->serialize(); - $this->logger->expects(self::once()) + $this->mocks[LoggerInterface::class]->expects(self::once()) ->method('error') ->with('Invalid principal URI provided for iMip request'); @@ -921,14 +884,14 @@ public function testhandleIMipRequest() { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['handleIMip']) ->getMock(); @@ -947,7 +910,7 @@ public function testhandleIMipReplyWithInvalidPrincipal() { $recipient = 'recipient@example.com'; $calendarData = $this->vCalendar2a->serialize(); - $this->logger->expects(self::once()) + $this->mocks[LoggerInterface::class]->expects(self::once()) ->method('error') ->with('Invalid principal URI provided for iMip reply'); @@ -964,14 +927,14 @@ public function testhandleIMipReply() { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['handleIMip']) ->getMock(); @@ -991,7 +954,7 @@ public function testhandleIMipCancelWithInvalidPrincipal() { $recipient = 'recipient@example.com'; $calendarData = $this->vCalendar3a->serialize(); - $this->logger->expects(self::once()) + $this->mocks[LoggerInterface::class]->expects(self::once()) ->method('error') ->with('Invalid principal URI provided for iMip cancel'); @@ -1009,14 +972,14 @@ public function testhandleIMipCancel() { /** @var Manager&MockObject $manager */ $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->coordinator, - $this->container, - $this->logger, - $this->time, - $this->secureRandom, - $this->userManager, - $this->serverFactory, - $this->propertyMapper, + $this->mocks[Coordinator::class], + $this->mocks[ContainerInterface::class], + $this->mocks[LoggerInterface::class], + $this->mocks[ITimeFactory::class], + $this->mocks[ISecureRandom::class], + $this->mocks[IUserManager::class], + $this->mocks[ServerFactory::class], + $this->mocks[PropertyMapper::class], ]) ->onlyMethods(['handleIMip']) ->getMock(); @@ -1122,7 +1085,7 @@ public function testCheckAvailability(): void { $user1 = $this->createMock(IUser::class); $user2 = $this->createMock(IUser::class); - $this->userManager->expects(self::exactly(3)) + $this->mocks[IUserManager::class]->expects(self::exactly(3)) ->method('getByEmail') ->willReturnMap([ ['user@imap.localhost', [$user1]], @@ -1158,7 +1121,7 @@ public function testCheckAvailability(): void { $response->setBody($this->getFreeBusyResponse()); }); - $this->serverFactory->expects(self::once()) + $this->mocks[ServerFactory::class]->expects(self::once()) ->method('createAttendeeAvailabilityServer') ->willReturn($server); @@ -1189,7 +1152,7 @@ public function testCheckAvailabilityWithMailtoPrefix(): void { $user1 = $this->createMock(IUser::class); $user2 = $this->createMock(IUser::class); - $this->userManager->expects(self::exactly(3)) + $this->mocks[IUserManager::class]->expects(self::exactly(3)) ->method('getByEmail') ->willReturnMap([ ['user@imap.localhost', [$user1]], @@ -1225,7 +1188,7 @@ public function testCheckAvailabilityWithMailtoPrefix(): void { $response->setBody($this->getFreeBusyResponse()); }); - $this->serverFactory->expects(self::once()) + $this->mocks[ServerFactory::class]->expects(self::once()) ->method('createAttendeeAvailabilityServer') ->willReturn($server); diff --git a/tests/lib/Calendar/Resource/ManagerTest.php b/tests/lib/Calendar/Resource/ManagerTest.php index c274e4c2b6f48..eeeda8a5b68a8 100644 --- a/tests/lib/Calendar/Resource/ManagerTest.php +++ b/tests/lib/Calendar/Resource/ManagerTest.php @@ -15,29 +15,17 @@ use OC\Calendar\Resource\Manager; use OC\Calendar\ResourcesRoomsUpdater; use OCP\Calendar\Resource\IBackend; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; use Test\TestCase; class ManagerTest extends TestCase { - private Coordinator&MockObject $coordinator; - private ContainerInterface&MockObject $server; - private ResourcesRoomsUpdater&MockObject $resourcesRoomsUpdater; private Manager $manager; #[\Override] protected function setUp(): void { parent::setUp(); - $this->coordinator = $this->createMock(Coordinator::class); - $this->server = $this->createMock(ContainerInterface::class); - $this->resourcesRoomsUpdater = $this->createMock(ResourcesRoomsUpdater::class); - - $this->manager = new Manager( - $this->coordinator, - $this->server, - $this->resourcesRoomsUpdater, - ); + $this->manager = $this->createInstanceWithMocks(Manager::class); } public function testGetBackendFromBootstrapRegistration(): void { @@ -45,7 +33,7 @@ public function testGetBackendFromBootstrapRegistration(): void { $backend = $this->createMock(IBackend::class); $backend->method('getBackendIdentifier')->willReturn('from_bootstrap'); $context = $this->createMock(RegistrationContext::class); - $this->coordinator->expects(self::once()) + $this->mocks[Coordinator::class]->expects(self::once()) ->method('getRegistrationContext') ->willReturn($context); $context->expects(self::once()) @@ -53,7 +41,7 @@ public function testGetBackendFromBootstrapRegistration(): void { ->willReturn([ new ServiceRegistration('calendar_resource_foo', $backendClass) ]); - $this->server->expects(self::once()) + $this->mocks[ContainerInterface::class]->expects(self::once()) ->method('get') ->with($backendClass) ->willReturn($backend); @@ -62,7 +50,7 @@ public function testGetBackendFromBootstrapRegistration(): void { } public function testUpdate(): void { - $this->resourcesRoomsUpdater->expects(self::once()) + $this->mocks[ResourcesRoomsUpdater::class]->expects(self::once()) ->method('updateResources'); $this->manager->update(); diff --git a/tests/lib/Calendar/Room/ManagerTest.php b/tests/lib/Calendar/Room/ManagerTest.php index 4937dd2cef0b4..80abbc6d89b8a 100644 --- a/tests/lib/Calendar/Room/ManagerTest.php +++ b/tests/lib/Calendar/Room/ManagerTest.php @@ -15,29 +15,17 @@ use OC\Calendar\ResourcesRoomsUpdater; use OC\Calendar\Room\Manager; use OCP\Calendar\Room\IBackend; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; use Test\TestCase; class ManagerTest extends TestCase { - private Coordinator&MockObject $coordinator; - private ContainerInterface&MockObject $server; - private ResourcesRoomsUpdater&MockObject $resourcesRoomsUpdater; private Manager $manager; #[\Override] protected function setUp(): void { parent::setUp(); - $this->coordinator = $this->createMock(Coordinator::class); - $this->server = $this->createMock(ContainerInterface::class); - $this->resourcesRoomsUpdater = $this->createMock(ResourcesRoomsUpdater::class); - - $this->manager = new Manager( - $this->coordinator, - $this->server, - $this->resourcesRoomsUpdater, - ); + $this->manager = $this->createInstanceWithMocks(Manager::class); } public function testGetBackendFromBootstrapRegistration(): void { @@ -45,7 +33,7 @@ public function testGetBackendFromBootstrapRegistration(): void { $backend = $this->createMock(IBackend::class); $backend->method('getBackendIdentifier')->willReturn('from_bootstrap'); $context = $this->createMock(RegistrationContext::class); - $this->coordinator->expects(self::once()) + $this->mocks[Coordinator::class]->expects(self::once()) ->method('getRegistrationContext') ->willReturn($context); $context->expects(self::once()) @@ -53,7 +41,7 @@ public function testGetBackendFromBootstrapRegistration(): void { ->willReturn([ new ServiceRegistration('calendar_room_foo', $backendClass) ]); - $this->server->expects(self::once()) + $this->mocks[ContainerInterface::class]->expects(self::once()) ->method('get') ->with($backendClass) ->willReturn($backend); @@ -62,7 +50,7 @@ public function testGetBackendFromBootstrapRegistration(): void { } public function testUpdate(): void { - $this->resourcesRoomsUpdater->expects(self::once()) + $this->mocks[ResourcesRoomsUpdater::class]->expects(self::once()) ->method('updateRooms'); $this->manager->update(); diff --git a/tests/lib/Collaboration/Collaborators/SearchTest.php b/tests/lib/Collaboration/Collaborators/SearchTest.php index c8e91949356bf..9516fb363dcbb 100644 --- a/tests/lib/Collaboration/Collaborators/SearchTest.php +++ b/tests/lib/Collaboration/Collaborators/SearchTest.php @@ -14,25 +14,18 @@ use OCP\Collaboration\Collaborators\ISearchPlugin; use OCP\Collaboration\Collaborators\ISearchResult; use OCP\Collaboration\Collaborators\SearchResultType; -use OCP\EventDispatcher\IEventDispatcher; use OCP\IContainer; use OCP\Share\IShare; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class SearchTest extends TestCase { - protected IContainer&MockObject $container; - protected IEventDispatcher&MockObject $eventDispatcher; protected Search $search; #[\Override] protected function setUp(): void { parent::setUp(); - $this->container = $this->createMock(IContainer::class); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - - $this->search = new Search($this->container, $this->eventDispatcher); + $this->search = $this->createInstanceWithMocks(Search::class); } #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchSharees')] @@ -91,7 +84,7 @@ public function testSearch( return $expectedMoreResults; }); - $this->container->expects($this->any()) + $this->mocks[IContainer::class]->expects($this->any()) ->method('get') ->willReturnCallback(function ($class) use ($userPlugin, $groupPlugin, $remotePlugin, $mailPlugin) { if ($class === 'user') { diff --git a/tests/lib/Command/Integrity/SignAppTest.php b/tests/lib/Command/Integrity/SignAppTest.php index a98cea6374f8c..070ff15f3cd89 100644 --- a/tests/lib/Command/Integrity/SignAppTest.php +++ b/tests/lib/Command/Integrity/SignAppTest.php @@ -11,32 +11,18 @@ use OC\Core\Command\Integrity\SignApp; use OC\IntegrityCheck\Checker; use OC\IntegrityCheck\Helpers\FileAccessHelper; -use OCP\IURLGenerator; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Test\TestCase; class SignAppTest extends TestCase { - /** @var Checker|\PHPUnit\Framework\MockObject\MockObject */ - private $checker; /** @var SignApp */ private $signApp; - /** @var FileAccessHelper|\PHPUnit\Framework\MockObject\MockObject */ - private $fileAccessHelper; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; #[\Override] protected function setUp(): void { parent::setUp(); - $this->checker = $this->createMock(Checker::class); - $this->fileAccessHelper = $this->createMock(FileAccessHelper::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - $this->signApp = new SignApp( - $this->checker, - $this->fileAccessHelper, - $this->urlGenerator - ); + $this->signApp = $this->createInstanceWithMocks(SignApp::class); } public function testExecuteWithMissingPath(): void { @@ -151,7 +137,7 @@ public function testExecuteWithNotExistingPrivateKey(): void { ['certificate', 'certificate'], ]); - $this->fileAccessHelper + $this->mocks[FileAccessHelper::class] ->expects($this->any()) ->method('file_get_contents') ->willReturnMap([ @@ -181,7 +167,7 @@ public function testExecuteWithNotExistingCertificate(): void { ['certificate', 'certificate'], ]); - $this->fileAccessHelper + $this->mocks[FileAccessHelper::class] ->expects($this->any()) ->method('file_get_contents') ->willReturnMap([ @@ -212,7 +198,7 @@ public function testExecuteWithException(): void { ['certificate', 'certificate'], ]); - $this->fileAccessHelper + $this->mocks[FileAccessHelper::class] ->expects($this->any()) ->method('file_get_contents') ->willReturnMap([ @@ -220,7 +206,7 @@ public function testExecuteWithException(): void { ['certificate', \OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'], ]); - $this->checker + $this->mocks[Checker::class] ->expects($this->once()) ->method('writeAppSignature') ->willThrowException(new \Exception('My error message')); @@ -248,7 +234,7 @@ public function testExecute(): void { ['certificate', 'certificate'], ]); - $this->fileAccessHelper + $this->mocks[FileAccessHelper::class] ->expects($this->any()) ->method('file_get_contents') ->willReturnMap([ @@ -256,7 +242,7 @@ public function testExecute(): void { ['certificate', \OC::$SERVERROOT . '/tests/data/integritycheck/core.crt'], ]); - $this->checker + $this->mocks[Checker::class] ->expects($this->once()) ->method('writeAppSignature'); diff --git a/tests/lib/Command/Integrity/SignCoreTest.php b/tests/lib/Command/Integrity/SignCoreTest.php index 563e3ef81b5e1..a768a5f3cd4fa 100644 --- a/tests/lib/Command/Integrity/SignCoreTest.php +++ b/tests/lib/Command/Integrity/SignCoreTest.php @@ -16,22 +16,13 @@ use Test\TestCase; class SignCoreTest extends TestCase { - /** @var Checker|\PHPUnit\Framework\MockObject\MockObject */ - private $checker; - /** @var FileAccessHelper|\PHPUnit\Framework\MockObject\MockObject */ - private $fileAccessHelper; /** @var SignCore */ private $signCore; #[\Override] protected function setUp(): void { parent::setUp(); - $this->checker = $this->createMock(Checker::class); - $this->fileAccessHelper = $this->createMock(FileAccessHelper::class); - $this->signCore = new SignCore( - $this->checker, - $this->fileAccessHelper - ); + $this->signCore = $this->createInstanceWithMocks(SignCore::class); } public function testExecuteWithMissingPrivateKey(): void { @@ -93,7 +84,7 @@ public function testExecuteWithNotExistingPrivateKey(): void { ['path', 'certificate'], ]); - $this->fileAccessHelper + $this->mocks[FileAccessHelper::class] ->method('file_get_contents') ->willReturnMap([ ['privateKey', false], @@ -122,7 +113,7 @@ public function testExecuteWithNotExistingCertificate(): void { ['path', 'certificate'], ]); - $this->fileAccessHelper + $this->mocks[FileAccessHelper::class] ->expects($this->any()) ->method('file_get_contents') ->willReturnMap([ @@ -153,7 +144,7 @@ public function testExecuteWithException(): void { ['path', 'certificate'], ]); - $this->fileAccessHelper + $this->mocks[FileAccessHelper::class] ->expects($this->any()) ->method('file_get_contents') ->willReturnMap([ @@ -161,7 +152,7 @@ public function testExecuteWithException(): void { ['certificate', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt')], ]); - $this->checker + $this->mocks[Checker::class] ->expects($this->once()) ->method('writeCoreSignature') ->willThrowException(new \Exception('My exception message')); @@ -189,7 +180,7 @@ public function testExecute(): void { ['path', 'certificate'], ]); - $this->fileAccessHelper + $this->mocks[FileAccessHelper::class] ->expects($this->any()) ->method('file_get_contents') ->willReturnMap([ @@ -197,7 +188,7 @@ public function testExecute(): void { ['certificate', file_get_contents(\OC::$SERVERROOT . '/tests/data/integritycheck/core.crt')], ]); - $this->checker + $this->mocks[Checker::class] ->expects($this->once()) ->method('writeCoreSignature'); diff --git a/tests/lib/Contacts/ContactsMenu/ManagerTest.php b/tests/lib/Contacts/ContactsMenu/ManagerTest.php index 0d66cea061860..6e42a9c3b9071 100644 --- a/tests/lib/Contacts/ContactsMenu/ManagerTest.php +++ b/tests/lib/Contacts/ContactsMenu/ManagerTest.php @@ -16,34 +16,16 @@ use OCP\Contacts\ContactsMenu\IProvider; use OCP\IConfig; use OCP\IUser; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ManagerTest extends TestCase { - /** @var ContactsStore|MockObject */ - private $contactsStore; - - /** @var IAppManager|MockObject */ - private $appManager; - - /** @var IConfig|MockObject */ - private $config; - - /** @var ActionProviderStore|MockObject */ - private $actionProviderStore; - private Manager $manager; #[\Override] protected function setUp(): void { parent::setUp(); - $this->contactsStore = $this->createMock(ContactsStore::class); - $this->actionProviderStore = $this->createMock(ActionProviderStore::class); - $this->appManager = $this->createMock(IAppManager::class); - $this->config = $this->createMock(IConfig::class); - - $this->manager = new Manager($this->contactsStore, $this->actionProviderStore, $this->appManager, $this->config); + $this->manager = $this->createInstanceWithMocks(Manager::class); } private function generateTestEntries(): array { @@ -64,23 +46,23 @@ public function testGetFilteredEntries(): void { $entries = $this->generateTestEntries(); $provider = $this->createMock(IProvider::class); - $this->config->expects($this->exactly(2)) + $this->mocks[IConfig::class]->expects($this->exactly(2)) ->method('getSystemValueInt') ->willReturnMap([ ['sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT, 25], ['sharing.minSearchStringLength', 0, 0], ]); - $this->contactsStore->expects($this->once()) + $this->mocks[ContactsStore::class]->expects($this->once()) ->method('getContacts') ->with($user, $filter) ->willReturn($entries); - $this->actionProviderStore->expects($this->once()) + $this->mocks[ActionProviderStore::class]->expects($this->once()) ->method('getProviders') ->with($user) ->willReturn([$provider]); $provider->expects($this->exactly(25)) ->method('process'); - $this->appManager->expects($this->once()) + $this->mocks[IAppManager::class]->expects($this->once()) ->method('isEnabledForUser') ->with($this->equalTo('contacts'), $user) ->willReturn(false); @@ -100,23 +82,23 @@ public function testGetFilteredEntriesLimit(): void { $entries = $this->generateTestEntries(); $provider = $this->createMock(IProvider::class); - $this->config->expects($this->exactly(2)) + $this->mocks[IConfig::class]->expects($this->exactly(2)) ->method('getSystemValueInt') ->willReturnMap([ ['sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT, 3], ['sharing.minSearchStringLength', 0, 0], ]); - $this->contactsStore->expects($this->once()) + $this->mocks[ContactsStore::class]->expects($this->once()) ->method('getContacts') ->with($user, $filter) ->willReturn($entries); - $this->actionProviderStore->expects($this->once()) + $this->mocks[ActionProviderStore::class]->expects($this->once()) ->method('getProviders') ->with($user) ->willReturn([$provider]); $provider->expects($this->exactly(3)) ->method('process'); - $this->appManager->expects($this->once()) + $this->mocks[IAppManager::class]->expects($this->once()) ->method('isEnabledForUser') ->with($this->equalTo('contacts'), $user) ->willReturn(false); @@ -135,13 +117,13 @@ public function testGetFilteredEntriesMinSearchStringLength(): void { $user = $this->createMock(IUser::class); $provider = $this->createMock(IProvider::class); - $this->config->expects($this->exactly(2)) + $this->mocks[IConfig::class]->expects($this->exactly(2)) ->method('getSystemValueInt') ->willReturnMap([ ['sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT, 3], ['sharing.minSearchStringLength', 0, 4], ]); - $this->appManager->expects($this->once()) + $this->mocks[IAppManager::class]->expects($this->once()) ->method('isEnabledForUser') ->with($this->equalTo('contacts'), $user) ->willReturn(false); @@ -162,11 +144,11 @@ public function testFindOne(): void { $user = $this->createMock(IUser::class); $entry = current($this->generateTestEntries()); $provider = $this->createMock(IProvider::class); - $this->contactsStore->expects($this->once()) + $this->mocks[ContactsStore::class]->expects($this->once()) ->method('findOne') ->with($user, $shareTypeFilter, $shareWithFilter) ->willReturn($entry); - $this->actionProviderStore->expects($this->once()) + $this->mocks[ActionProviderStore::class]->expects($this->once()) ->method('getProviders') ->with($user) ->willReturn([$provider]); @@ -184,11 +166,11 @@ public function testFindOne404(): void { $user = $this->createMock(IUser::class); $provider = $this->createMock(IProvider::class); - $this->contactsStore->expects($this->once()) + $this->mocks[ContactsStore::class]->expects($this->once()) ->method('findOne') ->with($user, $shareTypeFilter, $shareWithFilter) ->willReturn(null); - $this->actionProviderStore->expects($this->never()) + $this->mocks[ActionProviderStore::class]->expects($this->never()) ->method('getProviders') ->with($user) ->willReturn([$provider]); diff --git a/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php b/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php index e595af8e03555..b1b3ebc561e55 100644 --- a/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php +++ b/tests/lib/Contacts/ContactsMenu/Providers/LocalTimeProviderTest.php @@ -27,24 +27,13 @@ class LocalTimeProviderTest extends TestCase { - private IActionFactory&MockObject $actionFactory; private IL10N&MockObject $l; - private IL10NFactory&MockObject $l10nFactory; - private IURLGenerator&MockObject $urlGenerator; - private IUserManager&MockObject $userManager; - private ITimeFactory&MockObject $timeFactory; - private IUserSession&MockObject $userSession; - private IDateTimeFormatter&MockObject $dateTimeFormatter; - private IConfig&MockObject $config; private LocalTimeProvider $provider; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->actionFactory = $this->createMock(IActionFactory::class); - $this->l10nFactory = $this->createMock(IL10NFactory::class); $this->l = $this->createMock(IL10N::class); $this->l->expects($this->any()) ->method('t') @@ -57,23 +46,8 @@ protected function setUp(): void { $formatted = str_replace('%n', (string)$n, $n === 1 ? $text : $textPlural); return vsprintf($formatted, $parameters); }); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); - $this->dateTimeFormatter = $this->createMock(IDateTimeFormatter::class); - $this->config = $this->createMock(IConfig::class); - $this->userSession = $this->createMock(IUserSession::class); - - $this->provider = new LocalTimeProvider( - $this->actionFactory, - $this->l10nFactory, - $this->urlGenerator, - $this->userManager, - $this->timeFactory, - $this->dateTimeFormatter, - $this->config, - $this->userSession, - ); + + $this->provider = $this->createInstanceWithMocks(LocalTimeProvider::class); } public static function dataTestProcess(): array { @@ -122,19 +96,19 @@ public function testProcess(bool $hasCurrentUser, ?string $currentUserTZ, ?strin $user = $this->createMock(IUser::class); $user->method('getUID') ->willReturn('user1'); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('get') ->with('user1') ->willReturn($user); - $this->l10nFactory->method('get') + $this->mocks[IL10NFactory::class]->method('get') ->with('lib') ->willReturn($this->l); - $this->config->method('getSystemValueString') + $this->mocks[IConfig::class]->method('getSystemValueString') ->with('default_timezone', 'UTC') ->willReturn('UTC'); - $this->config + $this->mocks[IConfig::class] ->method('getUserValue') ->willReturnMap([ ['user1', 'core', 'timezone', '', $targetUserTZ], @@ -145,24 +119,24 @@ public function testProcess(bool $hasCurrentUser, ?string $currentUserTZ, ?strin $currentUser = $this->createMock(IUser::class); $currentUser->method('getUID') ->willReturn('currentUser'); - $this->userSession->method('getUser') + $this->mocks[IUserSession::class]->method('getUser') ->willReturn($currentUser); } - $this->timeFactory->method('getDateTime') + $this->mocks[ITimeFactory::class]->method('getDateTime') ->willReturnCallback(fn ($time, $tz) => (new \DateTime('2023-01-04 10:24:43', new \DateTimeZone('UTC')))->setTimezone($tz)); - $this->dateTimeFormatter->method('formatTime') + $this->mocks[IDateTimeFormatter::class]->method('formatTime') ->willReturnCallback(fn (\DateTime $time) => $time->format('H:i')); - $this->urlGenerator->method('imagePath') + $this->mocks[IURLGenerator::class]->method('imagePath') ->willReturn('actions/recent.svg'); - $this->urlGenerator->method('getAbsoluteURL') + $this->mocks[IURLGenerator::class]->method('getAbsoluteURL') ->with('actions/recent.svg') ->willReturn('https://localhost/actions/recent.svg'); $action = $this->createMock(ILinkAction::class); - $this->actionFactory->expects($this->once()) + $this->mocks[IActionFactory::class]->expects($this->once()) ->method('newLinkAction') ->with( 'https://localhost/actions/recent.svg', diff --git a/tests/lib/EmojiHelperTest.php b/tests/lib/EmojiHelperTest.php index 27f731325f81c..42b2c931c56af 100644 --- a/tests/lib/EmojiHelperTest.php +++ b/tests/lib/EmojiHelperTest.php @@ -13,17 +13,12 @@ use OCP\IEmojiHelper; class EmojiHelperTest extends TestCase { - /** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */ - private $db; - private IEmojiHelper $helper; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->db = $this->createMock(IDBConnection::class); - $this->helper = new EmojiHelper($this->db); + $this->helper = $this->createInstanceWithMocks(EmojiHelper::class); } /** @@ -32,7 +27,7 @@ protected function setUp(): void { */ #[\PHPUnit\Framework\Attributes\DataProvider('doesPlatformSupportEmojiDataProvider')] public function testDoesPlatformSupportEmoji(bool $supports4ByteText, bool $expected): void { - $this->db->expects($this->once()) + $this->mocks[IDBConnection::class]->expects($this->once()) ->method('supports4ByteText') ->willReturn($supports4ByteText); diff --git a/tests/lib/Encryption/EncryptionWrapperTest.php b/tests/lib/Encryption/EncryptionWrapperTest.php index 20485c97fc083..219dbfd2e5739 100644 --- a/tests/lib/Encryption/EncryptionWrapperTest.php +++ b/tests/lib/Encryption/EncryptionWrapperTest.php @@ -9,37 +9,21 @@ namespace Test\Encryption; use OC\Encryption\EncryptionWrapper; -use OC\Encryption\Manager; use OC\Files\Storage\Wrapper\Encryption; -use OC\Memcache\ArrayCache; use OCA\Files_Trashbin\Storage; use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IDisableEncryptionStorage; -use Psr\Log\LoggerInterface; use Test\TestCase; class EncryptionWrapperTest extends TestCase { /** @var EncryptionWrapper */ private $instance; - /** @var \PHPUnit\Framework\MockObject\MockObject | LoggerInterface */ - private $logger; - - /** @var \PHPUnit\Framework\MockObject\MockObject | \OC\Encryption\Manager */ - private $manager; - - /** @var \PHPUnit\Framework\MockObject\MockObject|ArrayCache */ - private $arrayCache; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->arrayCache = $this->createMock(ArrayCache::class); - $this->manager = $this->createMock(Manager::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->instance = new EncryptionWrapper($this->arrayCache, $this->manager, $this->logger); + $this->instance = $this->createInstanceWithMocks(EncryptionWrapper::class); } #[\PHPUnit\Framework\Attributes\DataProvider('provideWrapStorage')] diff --git a/tests/lib/Encryption/ManagerTest.php b/tests/lib/Encryption/ManagerTest.php index fb7aec3a1c833..669c55b73b4d9 100644 --- a/tests/lib/Encryption/ManagerTest.php +++ b/tests/lib/Encryption/ManagerTest.php @@ -11,49 +11,20 @@ use OC\Encryption\Exceptions\ModuleAlreadyExistsException; use OC\Encryption\Exceptions\ModuleDoesNotExistsException; use OC\Encryption\Manager; -use OC\Encryption\Util; -use OC\Files\View; -use OC\Memcache\ArrayCache; use OCP\Encryption\IEncryptionModule; use OCP\IAppConfig; use OCP\IConfig; -use OCP\IL10N; use OCP\Server; -use Psr\Log\LoggerInterface; use Test\TestCase; class ManagerTest extends TestCase { /** @var Manager */ private $manager; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; - - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; - - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ - private $l10n; - - /** @var View|\PHPUnit\Framework\MockObject\MockObject */ - private $view; - - /** @var Util|\PHPUnit\Framework\MockObject\MockObject */ - private $util; - - /** @var ArrayCache|\PHPUnit\Framework\MockObject\MockObject */ - private $arrayCache; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->l10n = $this->createMock(IL10N::class); - $this->view = $this->createMock(View::class); - $this->util = $this->createMock(Util::class); - $this->arrayCache = $this->createMock(ArrayCache::class); - $this->manager = new Manager($this->config, $this->logger, $this->l10n, $this->view, $this->util, $this->arrayCache); + $this->manager = $this->createInstanceWithMocks(Manager::class); } public function testManagerIsDisabled(): void { @@ -61,12 +32,12 @@ public function testManagerIsDisabled(): void { } public function testManagerIsDisabledIfEnabledButNoModules(): void { - $this->config->expects($this->any())->method('getAppValue')->willReturn(true); + $this->mocks[IConfig::class]->expects($this->any())->method('getAppValue')->willReturn(true); $this->assertFalse($this->manager->isEnabled()); } public function testManagerIsDisabledIfDisabledButModules(): void { - $this->config->expects($this->any())->method('getAppValue')->willReturn(false); + $this->mocks[IConfig::class]->expects($this->any())->method('getAppValue')->willReturn(false); $em = $this->createMock(IEncryptionModule::class); $em->expects($this->any())->method('getId')->willReturn('id'); $em->expects($this->any())->method('getDisplayName')->willReturn('TestDummyModule0'); @@ -81,7 +52,7 @@ public function testManagerIsEnabled(): void { $appConfig = Server::get(IAppConfig::class); $appConfig->setValueBool('core', 'encryption_enabled', true); - $this->config->expects($this->any())->method('getSystemValueBool')->willReturn(true); + $this->mocks[IConfig::class]->expects($this->any())->method('getSystemValueBool')->willReturn(true); $result = $this->manager->isEnabled(); $appConfig->deleteKey('core', 'encryption_enabled'); @@ -89,7 +60,7 @@ public function testManagerIsEnabled(): void { } public function testModuleRegistration() { - $this->config->expects($this->any())->method('getAppValue')->willReturn('yes'); + $this->mocks[IConfig::class]->expects($this->any())->method('getAppValue')->willReturn('yes'); $this->addNewEncryptionModule($this->manager, 0); $this->assertCount(1, $this->manager->getEncryptionModules()); @@ -106,7 +77,7 @@ public function testModuleReRegistration($manager): void { } public function testModuleUnRegistration(): void { - $this->config->expects($this->any())->method('getAppValue')->willReturn(true); + $this->mocks[IConfig::class]->expects($this->any())->method('getAppValue')->willReturn(true); $this->addNewEncryptionModule($this->manager, 0); $this->assertCount(1, $this->manager->getEncryptionModules()); @@ -118,7 +89,7 @@ public function testGetEncryptionModuleUnknown(): void { $this->expectException(ModuleDoesNotExistsException::class); $this->expectExceptionMessage('Module with ID: unknown does not exist.'); - $this->config->expects($this->any())->method('getAppValue')->willReturn(true); + $this->mocks[IConfig::class]->expects($this->any())->method('getAppValue')->willReturn(true); $this->addNewEncryptionModule($this->manager, 0); $this->assertCount(1, $this->manager->getEncryptionModules()); $this->manager->getEncryptionModule('unknown'); @@ -128,7 +99,7 @@ public function testGetEncryptionModuleEmpty(): void { global $defaultId; $defaultId = null; - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getAppValue') ->with('core', 'default_encryption_module') ->willReturnCallback(function () { @@ -152,7 +123,7 @@ public function testGetEncryptionModule(): void { global $defaultId; $defaultId = null; - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getAppValue') ->with('core', 'default_encryption_module') ->willReturnCallback(function () { @@ -177,7 +148,7 @@ public function testSetDefaultEncryptionModule(): void { global $defaultId; $defaultId = null; - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getAppValue') ->with('core', 'default_encryption_module') ->willReturnCallback(function () { @@ -195,7 +166,7 @@ public function testSetDefaultEncryptionModule(): void { $this->assertEquals('ID0', $this->manager->getDefaultEncryptionModuleId()); // Set to an existing module - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('setAppValue') ->with('core', 'default_encryption_module', 'ID1'); $this->assertTrue($this->manager->setDefaultEncryptionModule('ID1')); diff --git a/tests/lib/ErrorHandlerTest.php b/tests/lib/ErrorHandlerTest.php index 5229df71a9c37..4312be3f80d31 100644 --- a/tests/lib/ErrorHandlerTest.php +++ b/tests/lib/ErrorHandlerTest.php @@ -12,22 +12,16 @@ use OC\Log\ErrorHandler; use OCP\ILogger; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; class ErrorHandlerTest extends TestCase { - private LoggerInterface&MockObject $logger; private ErrorHandler $errorHandler; private int $errorReporting; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->logger = $this->createMock(LoggerInterface::class); - $this->errorHandler = new ErrorHandler( - $this->logger - ); + $this->errorHandler = $this->createInstanceWithMocks(ErrorHandler::class); $this->errorReporting = error_reporting(E_ALL); } @@ -64,7 +58,7 @@ public static function passwordProvider(): array { public function testRemovePasswordFromError($username, $password): void { $url = 'http://' . $username . ':' . $password . '@owncloud.org'; $expectedResult = 'http://xxx:xxx@owncloud.org'; - $this->logger->expects(self::once()) + $this->mocks[LoggerInterface::class]->expects(self::once()) ->method('log') ->with( ILogger::ERROR, diff --git a/tests/lib/Files/AppData/FactoryTest.php b/tests/lib/Files/AppData/FactoryTest.php index 0d157c5a22ea7..ca14e66ff6063 100644 --- a/tests/lib/Files/AppData/FactoryTest.php +++ b/tests/lib/Files/AppData/FactoryTest.php @@ -12,28 +12,19 @@ use OCP\Files\IRootFolder; class FactoryTest extends \Test\TestCase { - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; - - /** @var SystemConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $systemConfig; - /** @var Factory */ private $factory; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->rootFolder = $this->createMock(IRootFolder::class); - $this->systemConfig = $this->createMock(SystemConfig::class); - $this->factory = new Factory($this->rootFolder, $this->systemConfig); + $this->factory = $this->createInstanceWithMocks(Factory::class); } public function testGet(): void { - $this->rootFolder->expects($this->never()) + $this->mocks[IRootFolder::class]->expects($this->never()) ->method($this->anything()); - $this->systemConfig->expects($this->never()) + $this->mocks[SystemConfig::class]->expects($this->never()) ->method($this->anything()); $this->factory->get('foo'); diff --git a/tests/lib/Files/Cache/SearchBuilderTest.php b/tests/lib/Files/Cache/SearchBuilderTest.php index a8eea342e7d5b..b3deedc4d33c9 100644 --- a/tests/lib/Files/Cache/SearchBuilderTest.php +++ b/tests/lib/Files/Cache/SearchBuilderTest.php @@ -16,7 +16,6 @@ use OCP\Files\Search\ISearchBinaryOperator; use OCP\Files\Search\ISearchComparison; use OCP\Files\Search\ISearchOperator; -use OCP\FilesMetadata\IFilesMetadataManager; use OCP\IDBConnection; use OCP\Server; use Test\TestCase; @@ -26,12 +25,6 @@ class SearchBuilderTest extends TestCase { /** @var IQueryBuilder */ private $builder; - /** @var IMimeTypeLoader&\PHPUnit\Framework\MockObject\MockObject */ - private $mimetypeLoader; - - /** @var IFilesMetadataManager&\PHPUnit\Framework\MockObject\MockObject */ - private $filesMetadataManager; - /** @var SearchBuilder */ private $searchBuilder; @@ -42,10 +35,9 @@ class SearchBuilderTest extends TestCase { protected function setUp(): void { parent::setUp(); $this->builder = Server::get(IDBConnection::class)->getQueryBuilder(); - $this->mimetypeLoader = $this->createMock(IMimeTypeLoader::class); - $this->filesMetadataManager = $this->createMock(IFilesMetadataManager::class); + $this->searchBuilder = $this->createInstanceWithMocks(SearchBuilder::class); - $this->mimetypeLoader->expects($this->any()) + $this->mocks[IMimeTypeLoader::class]->expects($this->any()) ->method('getId') ->willReturnMap([ ['text', 1], @@ -56,7 +48,7 @@ protected function setUp(): void { ['image', 6], ]); - $this->mimetypeLoader->expects($this->any()) + $this->mocks[IMimeTypeLoader::class]->expects($this->any()) ->method('getMimetypeById') ->willReturnMap([ [1, 'text'], @@ -66,8 +58,6 @@ protected function setUp(): void { [5, 'image/png'], [6, 'image'] ]); - - $this->searchBuilder = new SearchBuilder($this->mimetypeLoader, $this->filesMetadataManager); $this->numericStorageId = 10000; $this->builder->select(['fileid']) @@ -105,8 +95,8 @@ private function addCacheEntry(array $data) { $data['parent'] = -1; if (isset($data['mimetype'])) { [$mimepart,] = explode('/', $data['mimetype']); - $data['mimepart'] = $this->mimetypeLoader->getId($mimepart); - $data['mimetype'] = $this->mimetypeLoader->getId($data['mimetype']); + $data['mimepart'] = $this->mocks[IMimeTypeLoader::class]->getId($mimepart); + $data['mimetype'] = $this->mocks[IMimeTypeLoader::class]->getId($data['mimetype']); } else { $data['mimepart'] = 1; $data['mimetype'] = 1; diff --git a/tests/lib/Files/ObjectStore/PrimaryObjectStoreConfigTest.php b/tests/lib/Files/ObjectStore/PrimaryObjectStoreConfigTest.php index 3f1bc633e9592..8acb9fdd14eaf 100644 --- a/tests/lib/Files/ObjectStore/PrimaryObjectStoreConfigTest.php +++ b/tests/lib/Files/ObjectStore/PrimaryObjectStoreConfigTest.php @@ -10,17 +10,13 @@ use OC\Files\ObjectStore\PrimaryObjectStoreConfig; use OC\Files\ObjectStore\StorageObjectStore; -use OCP\App\IAppManager; use OCP\IConfig; use OCP\IUser; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class PrimaryObjectStoreConfigTest extends TestCase { private array $systemConfig = []; private array $userConfig = []; - private IConfig&MockObject $config; - private IAppManager&MockObject $appManager; private PrimaryObjectStoreConfig $objectStoreConfig; #[\Override] @@ -28,9 +24,8 @@ protected function setUp(): void { parent::setUp(); $this->systemConfig = []; - $this->config = $this->createMock(IConfig::class); - $this->appManager = $this->createMock(IAppManager::class); - $this->config->method('getSystemValue') + $this->objectStoreConfig = $this->createInstanceWithMocks(PrimaryObjectStoreConfig::class); + $this->mocks[IConfig::class]->method('getSystemValue') ->willReturnCallback(function ($key, $default = '') { if (isset($this->systemConfig[$key])) { return $this->systemConfig[$key]; @@ -38,7 +33,7 @@ protected function setUp(): void { return $default; } }); - $this->config->method('getUserValue') + $this->mocks[IConfig::class]->method('getUserValue') ->willReturnCallback(function ($userId, $appName, $key, $default = '') { if (isset($this->userConfig[$userId][$appName][$key])) { return $this->userConfig[$userId][$appName][$key]; @@ -46,12 +41,10 @@ protected function setUp(): void { return $default; } }); - $this->config->method('setUserValue') + $this->mocks[IConfig::class]->method('setUserValue') ->willReturnCallback(function ($userId, $appName, $key, $value): void { $this->userConfig[$userId][$appName][$key] = $value; }); - - $this->objectStoreConfig = new PrimaryObjectStoreConfig($this->config, $this->appManager); } private function getUser(string $uid): IUser { @@ -79,7 +72,7 @@ public function testNewUserGetsDefault() { $result = $this->objectStoreConfig->getObjectStoreConfigForUser($this->getUser('test')); $this->assertEquals('server1', $result['arguments']['host']); - $this->assertEquals('server1', $this->config->getUserValue('test', 'homeobjectstore', 'objectstore', null)); + $this->assertEquals('server1', $this->mocks[IConfig::class]->getUserValue('test', 'homeobjectstore', 'objectstore', null)); } public function testExistingUserKeepsStorage() { @@ -107,7 +100,7 @@ public function testExistingUserKeepsStorage() { $result = $this->objectStoreConfig->getObjectStoreConfigForUser($this->getUser('test')); $this->assertEquals('server1', $result['arguments']['host']); - $this->assertEquals('server1', $this->config->getUserValue('test', 'homeobjectstore', 'objectstore', null)); + $this->assertEquals('server1', $this->mocks[IConfig::class]->getUserValue('test', 'homeobjectstore', 'objectstore', null)); $result = $this->objectStoreConfig->getObjectStoreConfigForUser($this->getUser('other-user')); $this->assertEquals('server2', $result['arguments']['host']); diff --git a/tests/lib/Files/SimpleFS/SimpleFileTest.php b/tests/lib/Files/SimpleFS/SimpleFileTest.php index 6f6746e7cda5a..1c9f0c292aa81 100644 --- a/tests/lib/Files/SimpleFS/SimpleFileTest.php +++ b/tests/lib/Files/SimpleFS/SimpleFileTest.php @@ -13,22 +13,17 @@ use OCP\Files\NotFoundException; class SimpleFileTest extends \Test\TestCase { - /** @var File|\PHPUnit\Framework\MockObject\MockObject */ - private $file; - /** @var SimpleFile */ private $simpleFile; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->file = $this->createMock(File::class); - $this->simpleFile = new SimpleFile($this->file); + $this->simpleFile = $this->createInstanceWithMocks(SimpleFile::class); } public function testGetName(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('getName') ->willReturn('myname'); @@ -36,7 +31,7 @@ public function testGetName(): void { } public function testGetSize(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('getSize') ->willReturn(42); @@ -44,7 +39,7 @@ public function testGetSize(): void { } public function testGetETag(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('getETag') ->willReturn('etag'); @@ -52,7 +47,7 @@ public function testGetETag(): void { } public function testGetMTime(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('getMTime') ->willReturn(101); @@ -60,7 +55,7 @@ public function testGetMTime(): void { } public function testGetContent(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('getContent') ->willReturn('foo'); @@ -68,7 +63,7 @@ public function testGetContent(): void { } public function testPutContent(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('putContent') ->with($this->equalTo('bar')); @@ -76,14 +71,14 @@ public function testPutContent(): void { } public function testDelete(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('delete'); $this->simpleFile->delete(); } public function testGetMimeType(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('getMimeType') ->willReturn('app/awesome'); @@ -91,9 +86,9 @@ public function testGetMimeType(): void { } public function testGetContentInvalidAppData(): void { - $this->file->method('getContent') + $this->mocks[File::class]->method('getContent') ->willReturn(false); - $this->file->method('stat')->willReturn(false); + $this->mocks[File::class]->method('stat')->willReturn(false); $parent = $this->createMock(Folder::class); $parent->method('stat')->willReturn(false); @@ -101,7 +96,7 @@ public function testGetContentInvalidAppData(): void { $root = $this->createMock(Folder::class); $root->method('stat')->willReturn([]); - $this->file->method('getParent')->willReturn($parent); + $this->mocks[File::class]->method('getParent')->willReturn($parent); $parent->method('getParent')->willReturn($root); $this->expectException(NotFoundException::class); @@ -110,7 +105,7 @@ public function testGetContentInvalidAppData(): void { } public function testRead(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('fopen') ->with('r'); @@ -118,7 +113,7 @@ public function testRead(): void { } public function testWrite(): void { - $this->file->expects($this->once()) + $this->mocks[File::class]->expects($this->once()) ->method('fopen') ->with('w'); diff --git a/tests/lib/Http/Client/ClientTest.php b/tests/lib/Http/Client/ClientTest.php index b2cecfdb0fff7..810ce47b7b75c 100644 --- a/tests/lib/Http/Client/ClientTest.php +++ b/tests/lib/Http/Client/ClientTest.php @@ -12,58 +12,32 @@ use GuzzleHttp\Psr7\Response; use OC\Http\Client\Client; -use OC\Security\CertificateManager; use OCP\Http\Client\LocalServerException; use OCP\ICertificateManager; use OCP\IConfig; use OCP\Security\IRemoteHostValidator; use OCP\ServerVersion; use PHPUnit\Framework\Attributes\DataProvider; -use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; use function parse_url; /** * Class ClientTest */ class ClientTest extends \Test\TestCase { - /** @var \GuzzleHttp\Client|MockObject */ - private $guzzleClient; - /** @var CertificateManager|MockObject */ - private $certificateManager; /** @var Client */ private $client; - /** @var IConfig|MockObject */ - private $config; - /** @var IRemoteHostValidator|MockObject */ - private IRemoteHostValidator $remoteHostValidator; - private LoggerInterface $logger; - private ServerVersion $serverVersion; /** @var array */ private $defaultRequestOptions; #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->guzzleClient = $this->createMock(\GuzzleHttp\Client::class); - $this->certificateManager = $this->createMock(ICertificateManager::class); - $this->remoteHostValidator = $this->createMock(IRemoteHostValidator::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->serverVersion = $this->createMock(ServerVersion::class); - - $this->client = new Client( - $this->config, - $this->certificateManager, - $this->guzzleClient, - $this->remoteHostValidator, - $this->logger, - $this->serverVersion, - ); + + $this->client = $this->createInstanceWithMocks(Client::class); } public function testGetProxyUri(): void { - $this->config + $this->mocks[IConfig::class] ->method('getSystemValueString') ->with('proxy', '') ->willReturn(''); @@ -71,13 +45,13 @@ public function testGetProxyUri(): void { } public function testGetProxyUriProxyHostEmptyPassword(): void { - $this->config + $this->mocks[IConfig::class] ->method('getSystemValue') ->willReturnMap([ ['proxyexclude', [], []], ]); - $this->config + $this->mocks[IConfig::class] ->method('getSystemValueString') ->willReturnMap([ ['proxy', '', 'foo'], @@ -91,12 +65,12 @@ public function testGetProxyUriProxyHostEmptyPassword(): void { } public function testGetProxyUriProxyHostWithPassword(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->once()) ->method('getSystemValue') ->with('proxyexclude', []) ->willReturn([]); - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueString') ->willReturnMap([ @@ -110,12 +84,12 @@ public function testGetProxyUriProxyHostWithPassword(): void { } public function testGetProxyUriProxyHostWithPasswordAndExclude(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->once()) ->method('getSystemValue') ->with('proxyexclude', []) ->willReturn(['bar']); - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueString') ->willReturnMap([ @@ -162,7 +136,7 @@ public static function dataPreventLocalAddress(): array { */ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')] public function testPreventLocalAddressDisabledByGlobalConfig(string $uri): void { - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueBool') ->with('allow_local_remote_servers', false) ->willReturn(true); @@ -175,7 +149,7 @@ public function testPreventLocalAddressDisabledByGlobalConfig(string $uri): void */ #[\PHPUnit\Framework\Attributes\DataProvider('dataPreventLocalAddress')] public function testPreventLocalAddressDisabledByOption(string $uri): void { - $this->config->expects($this->never()) + $this->mocks[IConfig::class]->expects($this->never()) ->method('getSystemValueBool'); self::invokePrivate($this->client, 'preventLocalAddress', [$uri, [ @@ -190,7 +164,7 @@ public function testPreventLocalAddressDisabledByOption(string $uri): void { public function testPreventLocalAddressOnGet(string $uri): void { $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->remoteHostValidator + $this->mocks[IRemoteHostValidator::class] ->method('isValid') ->with($host) ->willReturn(false); @@ -205,7 +179,7 @@ public function testPreventLocalAddressOnGet(string $uri): void { public function testPreventLocalAddressOnHead(string $uri): void { $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->remoteHostValidator + $this->mocks[IRemoteHostValidator::class] ->method('isValid') ->with($host) ->willReturn(false); @@ -220,7 +194,7 @@ public function testPreventLocalAddressOnHead(string $uri): void { public function testPreventLocalAddressOnPost(string $uri): void { $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->remoteHostValidator + $this->mocks[IRemoteHostValidator::class] ->method('isValid') ->with($host) ->willReturn(false); @@ -235,7 +209,7 @@ public function testPreventLocalAddressOnPost(string $uri): void { public function testPreventLocalAddressOnPut(string $uri): void { $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->remoteHostValidator + $this->mocks[IRemoteHostValidator::class] ->method('isValid') ->with($host) ->willReturn(false); @@ -250,7 +224,7 @@ public function testPreventLocalAddressOnPut(string $uri): void { public function testPreventLocalAddressOnDelete(string $uri): void { $host = parse_url($uri, PHP_URL_HOST); $this->expectException(LocalServerException::class); - $this->remoteHostValidator + $this->mocks[IRemoteHostValidator::class] ->method('isValid') ->with($host) ->willReturn(false); @@ -259,19 +233,19 @@ public function testPreventLocalAddressOnDelete(string $uri): void { } private function setUpDefaultRequestOptions(): void { - $this->config + $this->mocks[IConfig::class] ->method('getSystemValue') ->willReturnMap([ ['proxyexclude', [], []], ]); - $this->config + $this->mocks[IConfig::class] ->method('getSystemValueString') ->willReturnMap([ ['proxy', '', 'foo'], ['proxyuserpwd', '', ''], ['overwrite.cli.url', '', ''] ]); - $this->config + $this->mocks[IConfig::class] ->method('getSystemValueBool') ->willReturnMap([ ['installed', false, true], @@ -279,13 +253,13 @@ private function setUpDefaultRequestOptions(): void { ['http_client_add_user_agent_url', false, false] ]); - $this->certificateManager + $this->mocks[ICertificateManager::class] ->expects($this->once()) ->method('getAbsoluteBundlePath') ->with() ->willReturn('/my/path.crt'); - $this->serverVersion->method('getVersionString') + $this->mocks[ServerVersion::class]->method('getVersionString') ->willReturn('123.45.6'); $acceptEnc = (((curl_version()['features'] ?? 0) & CURL_VERSION_BROTLI) === CURL_VERSION_BROTLI) ? 'br, gzip' : 'gzip'; @@ -313,7 +287,7 @@ private function setUpDefaultRequestOptions(): void { public function testGet(): void { $this->setUpDefaultRequestOptions(); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('get', 'http://localhost/', $this->defaultRequestOptions) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->get('http://localhost/', [])->getStatusCode()); @@ -330,7 +304,7 @@ public function testGetWithOptions(): void { ], ]); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('get', 'http://localhost/', $options) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->get('http://localhost/', $options)->getStatusCode()); @@ -339,7 +313,7 @@ public function testGetWithOptions(): void { public function testPost(): void { $this->setUpDefaultRequestOptions(); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('post', 'http://localhost/', $this->defaultRequestOptions) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->post('http://localhost/', [])->getStatusCode()); @@ -356,7 +330,7 @@ public function testPostWithOptions(): void { ], ]); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('post', 'http://localhost/', $options) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->post('http://localhost/', $options)->getStatusCode()); @@ -365,7 +339,7 @@ public function testPostWithOptions(): void { public function testPut(): void { $this->setUpDefaultRequestOptions(); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('put', 'http://localhost/', $this->defaultRequestOptions) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->put('http://localhost/', [])->getStatusCode()); @@ -382,7 +356,7 @@ public function testPutWithOptions(): void { ], ]); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('put', 'http://localhost/', $options) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->put('http://localhost/', $options)->getStatusCode()); @@ -391,7 +365,7 @@ public function testPutWithOptions(): void { public function testDelete(): void { $this->setUpDefaultRequestOptions(); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('delete', 'http://localhost/', $this->defaultRequestOptions) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->delete('http://localhost/', [])->getStatusCode()); @@ -408,7 +382,7 @@ public function testDeleteWithOptions(): void { ], ]); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('delete', 'http://localhost/', $options) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->delete('http://localhost/', $options)->getStatusCode()); @@ -417,7 +391,7 @@ public function testDeleteWithOptions(): void { public function testOptions(): void { $this->setUpDefaultRequestOptions(); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('options', 'http://localhost/', $this->defaultRequestOptions) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->options('http://localhost/', [])->getStatusCode()); @@ -434,7 +408,7 @@ public function testOptionsWithOptions(): void { ], ]); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('options', 'http://localhost/', $options) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->options('http://localhost/', $options)->getStatusCode()); @@ -443,7 +417,7 @@ public function testOptionsWithOptions(): void { public function testHead(): void { $this->setUpDefaultRequestOptions(); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('head', 'http://localhost/', $this->defaultRequestOptions) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->head('http://localhost/', [])->getStatusCode()); @@ -460,14 +434,14 @@ public function testHeadWithOptions(): void { ], ]); - $this->guzzleClient->method('request') + $this->mocks[\GuzzleHttp\Client::class]->method('request') ->with('head', 'http://localhost/', $options) ->willReturn(new Response(418)); $this->assertEquals(418, $this->client->head('http://localhost/', $options)->getStatusCode()); } public function testSetDefaultOptionsWithNotInstalled(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('getSystemValueBool') ->willReturnMap([ @@ -475,22 +449,22 @@ public function testSetDefaultOptionsWithNotInstalled(): void { ['allow_local_remote_servers', false, false], ['http_client_add_user_agent_url', false, false], ]); - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueString') ->willReturnMap([ ['proxy', '', ''], ['overwrite.cli.url', '', ''], ]); - $this->certificateManager + $this->mocks[ICertificateManager::class] ->expects($this->never()) ->method('listCertificates'); - $this->certificateManager + $this->mocks[ICertificateManager::class] ->expects($this->once()) ->method('getDefaultCertificatesBundlePath') ->willReturn(\OC::$SERVERROOT . '/resources/config/ca-bundle.crt'); - $this->serverVersion->method('getVersionString') + $this->mocks[ServerVersion::class]->method('getVersionString') ->willReturn('123.45.6'); $acceptEnc = (((curl_version()['features'] ?? 0) & CURL_VERSION_BROTLI) === CURL_VERSION_BROTLI) ? 'br, gzip' : 'gzip'; @@ -521,7 +495,7 @@ public function testSetDefaultOptionsWithNotInstalled(): void { } public function testSetDefaultOptionsWithProxy(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('getSystemValueBool') ->willReturnMap([ @@ -529,12 +503,12 @@ public function testSetDefaultOptionsWithProxy(): void { ['allow_local_remote_servers', false, false], ['http_client_add_user_agent_url', false, false], ]); - $this->config + $this->mocks[IConfig::class] ->expects($this->once()) ->method('getSystemValue') ->with('proxyexclude', []) ->willReturn([]); - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('getSystemValueString') ->willReturnMap([ @@ -542,13 +516,13 @@ public function testSetDefaultOptionsWithProxy(): void { ['proxyuserpwd', '', ''], ['overwrite.cli.url', '', ''], ]); - $this->certificateManager + $this->mocks[ICertificateManager::class] ->expects($this->once()) ->method('getAbsoluteBundlePath') ->with() ->willReturn('/my/path.crt'); - $this->serverVersion->method('getVersionString') + $this->mocks[ServerVersion::class]->method('getVersionString') ->willReturn('123.45.6'); $acceptEnc = (((curl_version()['features'] ?? 0) & CURL_VERSION_BROTLI) === CURL_VERSION_BROTLI) ? 'br, gzip' : 'gzip'; @@ -583,7 +557,7 @@ public function testSetDefaultOptionsWithProxy(): void { } public function testSetDefaultOptionsWithProxyAndExclude(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('getSystemValueBool') ->willReturnMap([ @@ -591,12 +565,12 @@ public function testSetDefaultOptionsWithProxyAndExclude(): void { ['allow_local_remote_servers', false, false], ['http_client_add_user_agent_url', false, false], ]); - $this->config + $this->mocks[IConfig::class] ->expects($this->once()) ->method('getSystemValue') ->with('proxyexclude', []) ->willReturn(['bar']); - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('getSystemValueString') ->willReturnMap([ @@ -604,13 +578,13 @@ public function testSetDefaultOptionsWithProxyAndExclude(): void { ['proxyuserpwd', '', ''], ['overwrite.cli.url', '', ''], ]); - $this->certificateManager + $this->mocks[ICertificateManager::class] ->expects($this->once()) ->method('getAbsoluteBundlePath') ->with() ->willReturn('/my/path.crt'); - $this->serverVersion->method('getVersionString') + $this->mocks[ServerVersion::class]->method('getVersionString') ->willReturn('123.45.6'); $acceptEnc = (((curl_version()['features'] ?? 0) & CURL_VERSION_BROTLI) === CURL_VERSION_BROTLI) ? 'br, gzip' : 'gzip'; @@ -654,7 +628,7 @@ public static function dataForTestSetServerUrlInUserAgent(): array { #[DataProvider('dataForTestSetServerUrlInUserAgent')] public function testSetServerUrlInUserAgent(string $url, string $userAgent): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(3)) ->method('getSystemValueBool') ->willReturnMap([ @@ -662,20 +636,20 @@ public function testSetServerUrlInUserAgent(string $url, string $userAgent): voi ['allow_local_remote_servers', false, false], ['http_client_add_user_agent_url', false, true], ]); - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueString') ->willReturnMap([ ['proxy', '', ''], ['overwrite.cli.url', '', $url], ]); - $this->certificateManager + $this->mocks[ICertificateManager::class] ->expects($this->once()) ->method('getAbsoluteBundlePath') ->with() ->willReturn('/my/path.crt'); - $this->serverVersion->method('getVersionString') + $this->mocks[ServerVersion::class]->method('getVersionString') ->willReturn('123.45.6'); $acceptEnc = (((curl_version()['features'] ?? 0) & CURL_VERSION_BROTLI) === CURL_VERSION_BROTLI) ? 'br, gzip' : 'gzip'; diff --git a/tests/lib/Http/Client/NegativeDnsCacheTest.php b/tests/lib/Http/Client/NegativeDnsCacheTest.php index 35d8de75152c0..c8c386c3ad831 100644 --- a/tests/lib/Http/Client/NegativeDnsCacheTest.php +++ b/tests/lib/Http/Client/NegativeDnsCacheTest.php @@ -16,8 +16,6 @@ class NegativeDnsCacheTest extends \Test\TestCase { /** @var ICache */ private $cache; - /** @var ICacheFactory */ - private $cacheFactory; /** @var NegativeDnsCache */ private $negativeDnsCache; @@ -26,13 +24,12 @@ protected function setUp(): void { parent::setUp(); $this->cache = $this->createMock(ICache::class); - $this->cacheFactory = $this->createMock(ICacheFactory::class); - $this->cacheFactory + + $this->negativeDnsCache = $this->createInstanceWithMocks(NegativeDnsCache::class); + $this->mocks[ICacheFactory::class] ->method('createLocal') ->with('NegativeDnsCache') ->willReturn($this->cache); - - $this->negativeDnsCache = new NegativeDnsCache($this->cacheFactory); } public function testSetNegativeCacheForDnsType() : void { diff --git a/tests/lib/Http/WellKnown/RequestManagerTest.php b/tests/lib/Http/WellKnown/RequestManagerTest.php index fc6e721a6166f..6ab586f4f5b96 100644 --- a/tests/lib/Http/WellKnown/RequestManagerTest.php +++ b/tests/lib/Http/WellKnown/RequestManagerTest.php @@ -19,7 +19,6 @@ use OCP\Http\WellKnown\IResponse; use OCP\Http\WellKnown\JrdResponse; use OCP\IRequest; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; use RuntimeException; @@ -27,24 +26,13 @@ use function get_class; class RequestManagerTest extends TestCase { - private Coordinator&MockObject $coordinator; - private ContainerInterface&MockObject $container; - private LoggerInterface&MockObject $logger; private RequestManager $manager; #[\Override] protected function setUp(): void { parent::setUp(); - $this->coordinator = $this->createMock(Coordinator::class); - $this->container = $this->createMock(ContainerInterface::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->manager = new RequestManager( - $this->coordinator, - $this->container, - $this->logger, - ); + $this->manager = $this->createInstanceWithMocks(RequestManager::class); } public function testProcessAppsNotRegistered(): void { @@ -57,7 +45,7 @@ public function testProcessAppsNotRegistered(): void { public function testProcessNoHandlersRegistered(): void { $request = $this->createMock(IRequest::class); $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects(self::once()) + $this->mocks[Coordinator::class]->expects(self::once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $registrationContext->expects(self::once()) @@ -72,7 +60,7 @@ public function testProcessNoHandlersRegistered(): void { public function testProcessHandlerNotLoadable(): void { $request = $this->createMock(IRequest::class); $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects(self::once()) + $this->mocks[Coordinator::class]->expects(self::once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $handler = new class { @@ -82,11 +70,11 @@ public function testProcessHandlerNotLoadable(): void { ->willReturn([ new ServiceRegistration('test', get_class($handler)), ]); - $this->container->expects(self::once()) + $this->mocks[ContainerInterface::class]->expects(self::once()) ->method('get') ->with(get_class($handler)) ->willThrowException(new QueryException('')); - $this->logger->expects(self::once()) + $this->mocks[LoggerInterface::class]->expects(self::once()) ->method('error'); $response = $this->manager->process('webfinger', $request); @@ -97,7 +85,7 @@ public function testProcessHandlerNotLoadable(): void { public function testProcessHandlerOfWrongType(): void { $request = $this->createMock(IRequest::class); $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects(self::once()) + $this->mocks[Coordinator::class]->expects(self::once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $handler = new class { @@ -107,11 +95,11 @@ public function testProcessHandlerOfWrongType(): void { ->willReturn([ new ServiceRegistration('test', get_class($handler)), ]); - $this->container->expects(self::once()) + $this->mocks[ContainerInterface::class]->expects(self::once()) ->method('get') ->with(get_class($handler)) ->willReturn($handler); - $this->logger->expects(self::once()) + $this->mocks[LoggerInterface::class]->expects(self::once()) ->method('error'); $response = $this->manager->process('webfinger', $request); @@ -122,7 +110,7 @@ public function testProcessHandlerOfWrongType(): void { public function testProcess(): void { $request = $this->createMock(IRequest::class); $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects(self::once()) + $this->mocks[Coordinator::class]->expects(self::once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $handler = new class implements IHandler { @@ -136,7 +124,7 @@ public function handle(string $service, IRequestContext $context, ?IResponse $pr ->willReturn([ new ServiceRegistration('test', get_class($handler)), ]); - $this->container->expects(self::once()) + $this->mocks[ContainerInterface::class]->expects(self::once()) ->method('get') ->with(get_class($handler)) ->willReturn($handler); diff --git a/tests/lib/L10N/LanguageIteratorTest.php b/tests/lib/L10N/LanguageIteratorTest.php index d01d656fbcce3..930ce370042ba 100644 --- a/tests/lib/L10N/LanguageIteratorTest.php +++ b/tests/lib/L10N/LanguageIteratorTest.php @@ -9,14 +9,9 @@ use OC\L10N\LanguageIterator; use OCP\IConfig; -use OCP\IUser; use Test\TestCase; class LanguageIteratorTest extends TestCase { - /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */ - protected $user; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - protected $config; /** @var LanguageIterator */ protected $iterator; @@ -24,10 +19,7 @@ class LanguageIteratorTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->user = $this->createMock(IUser::class); - $this->config = $this->createMock(IConfig::class); - - $this->iterator = new LanguageIterator($this->user, $this->config); + $this->iterator = $this->createInstanceWithMocks(LanguageIterator::class); } public static function languageSettingsProvider(): array { @@ -60,17 +52,17 @@ public static function languageSettingsProvider(): array { #[\PHPUnit\Framework\Attributes\DataProvider('languageSettingsProvider')] public function testIterator($forcedLang, $userLang, $sysLang, $expectedValues): void { - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValue') ->willReturnMap([ ['force_language', false, $forcedLang], ]); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->willReturnMap([ ['default_language', 'en', $sysLang], ]); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getUserValue') ->willReturn($userLang); diff --git a/tests/lib/Log/PsrLoggerAdapterTest.php b/tests/lib/Log/PsrLoggerAdapterTest.php index 3e1d5bcb164ef..10eb752489b6d 100644 --- a/tests/lib/Log/PsrLoggerAdapterTest.php +++ b/tests/lib/Log/PsrLoggerAdapterTest.php @@ -12,26 +12,22 @@ use OC\Log; use OC\Log\PsrLoggerAdapter; use OCP\ILogger; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\InvalidArgumentException; use Psr\Log\LogLevel; use Test\TestCase; class PsrLoggerAdapterTest extends TestCase { - protected Log&MockObject $logger; protected PsrLoggerAdapter $loggerAdapter; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->logger = $this->createMock(Log::class); - $this->loggerAdapter = new PsrLoggerAdapter($this->logger); + $this->loggerAdapter = $this->createInstanceWithMocks(PsrLoggerAdapter::class); } #[\PHPUnit\Framework\Attributes\DataProvider('dataPsrLoggingLevels')] public function testLoggingWithPsrLogLevels(string $level, int $expectedLevel): void { - $this->logger->expects(self::once()) + $this->mocks[Log::class]->expects(self::once()) ->method('log') ->with($expectedLevel, 'test message', ['app' => 'test']); $this->loggerAdapter->log($level, 'test message', ['app' => 'test']); @@ -57,7 +53,7 @@ public static function dataPsrLoggingLevels(): array { #[\PHPUnit\Framework\Attributes\DataProvider('dataInvalidLoggingLevel')] public function testInvalidLoggingLevel($level): void { - $this->logger->expects(self::never()) + $this->mocks[Log::class]->expects(self::never()) ->method('log'); $this->expectException(InvalidArgumentException::class); diff --git a/tests/lib/Mail/EmailValidatorTest.php b/tests/lib/Mail/EmailValidatorTest.php index 497c7007a68d1..0a711a2e361a5 100644 --- a/tests/lib/Mail/EmailValidatorTest.php +++ b/tests/lib/Mail/EmailValidatorTest.php @@ -12,19 +12,15 @@ use OC\Mail\EmailValidator; use OCP\IAppConfig; use PHPUnit\Framework\Attributes\DataProvider; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class EmailValidatorTest extends TestCase { - private IAppConfig&MockObject $appConfig; private EmailValidator $emailValidator; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->appConfig = $this->createMock(IAppConfig::class); - $this->emailValidator = new EmailValidator($this->appConfig); + $this->emailValidator = $this->createInstanceWithMocks(EmailValidator::class); } public static function mailAddressProvider(): array { @@ -43,7 +39,7 @@ public static function mailAddressProvider(): array { #[DataProvider('mailAddressProvider')] public function testIsValid($email, $expected, $strict): void { - $this->appConfig + $this->mocks[IAppConfig::class] ->expects($this->atMost(1)) ->method('getValueString') ->with('core', 'enforce_strict_email_check', 'yes') diff --git a/tests/lib/Memcache/KeyValueCacheFactoryTest.php b/tests/lib/Memcache/KeyValueCacheFactoryTest.php index 4c65863cc162f..7077a69b9910d 100644 --- a/tests/lib/Memcache/KeyValueCacheFactoryTest.php +++ b/tests/lib/Memcache/KeyValueCacheFactoryTest.php @@ -11,8 +11,6 @@ use OC\Memcache\KeyValueCacheFactory; use OC\SystemConfig; -use OCP\Diagnostics\IEventLogger; -use PHPUnit\Framework\MockObject\MockObject; use Predis\Client; use Predis\Connection\Cluster\ClusterInterface; use Predis\Connection\NodeConnectionInterface; @@ -27,16 +25,11 @@ * mapping in {@see KeyValueCacheFactory::buildConnectionConfig()} is pure. */ class KeyValueCacheFactoryTest extends TestCase { - private SystemConfig&MockObject $config; - private IEventLogger&MockObject $eventLogger; private KeyValueCacheFactory $factory; protected function setUp(): void { parent::setUp(); - - $this->config = $this->createMock(SystemConfig::class); - $this->eventLogger = $this->createMock(IEventLogger::class); - $this->factory = new KeyValueCacheFactory($this->config, $this->eventLogger); + $this->factory = $this->createInstanceWithMocks(KeyValueCacheFactory::class); } public function testSingleServerTcp(): void { @@ -220,24 +213,24 @@ public function testSentinelMissingSeedsThrows(): void { } public function testIsAvailableWithoutConfig(): void { - $this->config->method('getValue')->with('memcache.kvstore', [])->willReturn([]); + $this->mocks[SystemConfig::class]->method('getValue')->with('memcache.kvstore', [])->willReturn([]); $this->assertFalse($this->factory->isAvailable()); } public function testIsAvailableWithConfig(): void { - $this->config->method('getValue')->with('memcache.kvstore', []) + $this->mocks[SystemConfig::class]->method('getValue')->with('memcache.kvstore', []) ->willReturn(['server' => ['host' => 'localhost']]); $this->assertTrue($this->factory->isAvailable()); } public function testGetInstanceThrowsWhenUnavailable(): void { - $this->config->method('getValue')->with('memcache.kvstore', [])->willReturn([]); + $this->mocks[SystemConfig::class]->method('getValue')->with('memcache.kvstore', [])->willReturn([]); $this->expectException(\RuntimeException::class); $this->factory->getInstance(); } public function testGetInstanceSingleServer(): void { - $this->config->method('getValue')->with('memcache.kvstore', []) + $this->mocks[SystemConfig::class]->method('getValue')->with('memcache.kvstore', []) ->willReturn(['server' => ['host' => 'localhost', 'port' => 6379]]); $client = $this->factory->getInstance(); @@ -246,7 +239,7 @@ public function testGetInstanceSingleServer(): void { } public function testGetInstanceCluster(): void { - $this->config->method('getValue')->with('memcache.kvstore', []) + $this->mocks[SystemConfig::class]->method('getValue')->with('memcache.kvstore', []) ->willReturn(['seeds' => [['host' => 'localhost', 'port' => 7000]]]); $client = $this->factory->getInstance(); @@ -254,7 +247,7 @@ public function testGetInstanceCluster(): void { } public function testGetInstanceSentinel(): void { - $this->config->method('getValue')->with('memcache.kvstore', []) + $this->mocks[SystemConfig::class]->method('getValue')->with('memcache.kvstore', []) ->willReturn([ 'sentinel' => [ 'service' => 'mymaster', @@ -267,7 +260,7 @@ public function testGetInstanceSentinel(): void { } public function testGetInstanceIsMemoized(): void { - $this->config->method('getValue')->with('memcache.kvstore', []) + $this->mocks[SystemConfig::class]->method('getValue')->with('memcache.kvstore', []) ->willReturn(['server' => ['host' => 'localhost']]); $this->assertSame($this->factory->getInstance(), $this->factory->getInstance()); diff --git a/tests/lib/NavigationManagerTest.php b/tests/lib/NavigationManagerTest.php index fc84c7b51a7f8..9d9432f057e95 100644 --- a/tests/lib/NavigationManagerTest.php +++ b/tests/lib/NavigationManagerTest.php @@ -13,7 +13,6 @@ use OC\NavigationManager; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; -use OCP\IGroupManager; use OCP\IL10N; use OCP\INavigationManager; use OCP\IURLGenerator; @@ -21,43 +20,14 @@ use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Navigation\Events\LoadAdditionalEntriesEvent; -use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; class NavigationManagerTest extends TestCase { - private AppManager&MockObject $appManager; - private IURLGenerator&MockObject $urlGenerator; - private IFactory&MockObject $l10nFac; - private IUserSession&MockObject $userSession; - private IGroupManager&MockObject $groupManager; - private IConfig&MockObject $config; - private IEventDispatcher&MockObject $dispatcher; - private LoggerInterface&MockObject $logger; - private NavigationManager $navigationManager; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->appManager = $this->createMock(AppManager::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - $this->l10nFac = $this->createMock(IFactory::class); - $this->userSession = $this->createMock(IUserSession::class); - $this->groupManager = $this->createMock(Manager::class); - $this->config = $this->createMock(IConfig::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->dispatcher = $this->createMock(IEventDispatcher::class); - $this->navigationManager = new NavigationManager( - $this->appManager, - $this->urlGenerator, - $this->l10nFac, - $this->userSession, - $this->groupManager, - $this->config, - $this->logger, - $this->dispatcher, - ); + $this->navigationManager = $this->createInstanceWithMocks(NavigationManager::class); $this->navigationManager->clear(false); } @@ -295,33 +265,33 @@ public function testWithAppManager($expected, $navigation, $isAdmin = false): vo }); /* Return default value */ - $this->config->method('getUserValue') + $this->mocks[IConfig::class]->method('getUserValue') ->willReturnArgument(3); - $this->appManager->expects($this->any()) + $this->mocks[AppManager::class]->expects($this->any()) ->method('isEnabledForUser') ->with('theming') ->willReturn(true); - $this->appManager->expects($this->once()) + $this->mocks[AppManager::class]->expects($this->once()) ->method('getAppInfo') ->with('test') ->willReturn($navigation); - $this->appManager->expects($this->any()) + $this->mocks[AppManager::class]->expects($this->any()) ->method('isAppLoaded') ->willReturnMap([ ['test', true], ['files', true], ]); - $this->urlGenerator->expects($this->any()) + $this->mocks[IURLGenerator::class]->expects($this->any()) ->method('imagePath') ->willReturnCallback(function ($appName, $file) { return "/apps/$appName/img/$file"; }); - $this->appManager->expects($this->any()) + $this->mocks[AppManager::class]->expects($this->any()) ->method('getAppIcon') ->willReturnCallback(fn (string $appName) => "/apps/$appName/img/app.svg"); - $this->l10nFac->expects($this->any())->method('get')->willReturn($l); - $this->urlGenerator->expects($this->any())->method('linkToRoute')->willReturnCallback(function ($route) { + $this->mocks[IFactory::class]->expects($this->any())->method('get')->willReturn($l); + $this->mocks[IURLGenerator::class]->expects($this->any())->method('linkToRoute')->willReturnCallback(function ($route) { if ($route === 'core.login.logout') { return 'https://example.com/logout'; } @@ -329,16 +299,16 @@ public function testWithAppManager($expected, $navigation, $isAdmin = false): vo }); $user = $this->createMock(IUser::class); $user->expects($this->any())->method('getUID')->willReturn('user001'); - $this->userSession->expects($this->any())->method('getUser')->willReturn($user); - $this->userSession->expects($this->any())->method('isLoggedIn')->willReturn(true); - $this->appManager->expects($this->any()) + $this->mocks[IUserSession::class]->expects($this->any())->method('getUser')->willReturn($user); + $this->mocks[IUserSession::class]->expects($this->any())->method('isLoggedIn')->willReturn(true); + $this->mocks[AppManager::class]->expects($this->any()) ->method('getEnabledAppsForUser') ->with($user) ->willReturn(['test']); - $this->groupManager->expects($this->any())->method('isAdmin')->willReturn($isAdmin); + $this->mocks[Manager::class]->expects($this->any())->method('isAdmin')->willReturn($isAdmin); $this->navigationManager->clear(); - $this->dispatcher->expects($this->atLeastOnce()) + $this->mocks[IEventDispatcher::class]->expects($this->atLeastOnce()) ->method('dispatchTyped') ->willReturnCallback(function ($event): void { $this->assertInstanceOf(LoadAdditionalEntriesEvent::class, $event); @@ -492,7 +462,7 @@ public function testWithAppManagerAndApporder(): void { ], ]]; - $this->config->method('getUserValue') + $this->mocks[IConfig::class]->method('getUserValue') ->willReturnCallback( function (string $userId, string $appName, string $key, mixed $default = '') use ($testOrder) { $this->assertEquals('user001', $userId); @@ -503,29 +473,29 @@ function (string $userId, string $appName, string $key, mixed $default = '') use } ); - $this->appManager->expects($this->any()) + $this->mocks[AppManager::class]->expects($this->any()) ->method('isEnabledForUser') ->with('theming') ->willReturn(true); - $this->appManager->expects($this->once()) + $this->mocks[AppManager::class]->expects($this->once()) ->method('getAppIcon') ->with('test') ->willReturn('/apps/test/img/app.svg'); - $this->appManager->expects($this->once()) + $this->mocks[AppManager::class]->expects($this->once()) ->method('getAppInfo') ->with('test') ->willReturn($navigation); - $this->appManager->expects($this->atLeastOnce()) + $this->mocks[AppManager::class]->expects($this->atLeastOnce()) ->method('isAppLoaded') ->willReturnMap([ ['test', true], ['files', true], ]); - $this->l10nFac->expects($this->any())->method('get')->willReturn($l); - $this->urlGenerator->expects($this->any())->method('imagePath')->willReturnCallback(function ($appName, $file) { + $this->mocks[IFactory::class]->expects($this->any())->method('get')->willReturn($l); + $this->mocks[IURLGenerator::class]->expects($this->any())->method('imagePath')->willReturnCallback(function ($appName, $file) { return "/apps/$appName/img/$file"; }); - $this->urlGenerator->expects($this->any())->method('linkToRoute')->willReturnCallback(function ($route) { + $this->mocks[IURLGenerator::class]->expects($this->any())->method('linkToRoute')->willReturnCallback(function ($route) { if ($route === 'core.login.logout') { return 'https://example.com/logout'; } @@ -533,16 +503,16 @@ function (string $userId, string $appName, string $key, mixed $default = '') use }); $user = $this->createMock(IUser::class); $user->expects($this->any())->method('getUID')->willReturn('user001'); - $this->userSession->expects($this->any())->method('getUser')->willReturn($user); - $this->userSession->expects($this->any())->method('isLoggedIn')->willReturn(true); - $this->appManager->expects($this->any()) + $this->mocks[IUserSession::class]->expects($this->any())->method('getUser')->willReturn($user); + $this->mocks[IUserSession::class]->expects($this->any())->method('isLoggedIn')->willReturn(true); + $this->mocks[AppManager::class]->expects($this->any()) ->method('getEnabledAppsForUser') ->with($user) ->willReturn(['test']); - $this->groupManager->expects($this->any())->method('isAdmin')->willReturn(false); + $this->mocks[Manager::class]->expects($this->any())->method('isAdmin')->willReturn(false); $this->navigationManager->clear(); - $this->dispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->willReturnCallback(function ($event): void { $this->assertInstanceOf(LoadAdditionalEntriesEvent::class, $event); @@ -556,9 +526,9 @@ function (string $userId, string $appName, string $key, mixed $default = '') use * Known apps get a default order, all other apps keep the order from their info.xml. */ public function testDefaultAppOrder(): void { - $this->userSession->method('isLoggedIn')->willReturn(false); - $this->appManager->method('getEnabledApps')->willReturn([]); - $this->appManager->method('isEnabledForUser')->willReturn(true); + $this->mocks[IUserSession::class]->method('isLoggedIn')->willReturn(false); + $this->mocks[AppManager::class]->method('getEnabledApps')->willReturn([]); + $this->mocks[AppManager::class]->method('isEnabledForUser')->willReturn(true); // order as shipped by the apps themselves $apps = ['circles' => 80, 'activity' => 1, 'other' => 2, 'spreed' => -5, 'files' => 0, 'dashboard' => -10]; @@ -578,12 +548,12 @@ public function testDefaultAppOrder(): void { public function testDefaultAppOrderIsSkippedForCustomOrder(): void { $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user001'); - $this->userSession->method('getUser')->willReturn($user); - $this->userSession->method('isLoggedIn')->willReturn(true); - $this->appManager->method('getEnabledAppsForUser')->willReturn([]); - $this->appManager->method('isEnabledForUser')->willReturn(true); - $this->groupManager->expects($this->any())->method('isAdmin')->willReturn(false); - $this->config->method('getUserValue') + $this->mocks[IUserSession::class]->method('getUser')->willReturn($user); + $this->mocks[IUserSession::class]->method('isLoggedIn')->willReturn(true); + $this->mocks[AppManager::class]->method('getEnabledAppsForUser')->willReturn([]); + $this->mocks[AppManager::class]->method('isEnabledForUser')->willReturn(true); + $this->mocks[Manager::class]->expects($this->any())->method('isAdmin')->willReturn(false); + $this->mocks[IConfig::class]->method('getUserValue') ->willReturnCallback(static function (string $userId, string $appName, string $key, mixed $default = '') { return $key === 'apporder' ? json_encode(['other' => ['app' => 'other', 'order' => 0]]) : $default; }); @@ -605,22 +575,22 @@ public function testDefaultAppOrderIsSkippedForCustomOrder(): void { */ public function testResolveOnlyLoadedApps(): void { /* Return default value */ - $this->config->method('getUserValue')->willReturnArgument(3); + $this->mocks[IConfig::class]->method('getUserValue')->willReturnArgument(3); $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user001'); - $this->userSession->method('getUser')->willReturn($user); - $this->userSession->method('isLoggedIn')->willReturn(true); - $this->appManager->method('getEnabledAppsForUser')->with($user)->willReturn(['test']); - $this->groupManager->expects($this->any())->method('isAdmin')->willReturn(false); + $this->mocks[IUserSession::class]->method('getUser')->willReturn($user); + $this->mocks[IUserSession::class]->method('isLoggedIn')->willReturn(true); + $this->mocks[AppManager::class]->method('getEnabledAppsForUser')->with($user)->willReturn(['test']); + $this->mocks[Manager::class]->expects($this->any())->method('isAdmin')->willReturn(false); // The app is enabled but not booted yet ... - $this->appManager->expects($this->atLeastOnce()) + $this->mocks[AppManager::class]->expects($this->atLeastOnce()) ->method('isAppLoaded') ->with('test') ->willReturn(false); // ... so its info.xml navigation entries must never be read - $this->appManager->expects($this->never())->method('getAppInfo'); + $this->mocks[AppManager::class]->expects($this->never())->method('getAppInfo'); $this->navigationManager->clear(); $this->assertEquals([], $this->navigationManager->getAll('all')); @@ -630,10 +600,10 @@ public function testResolveOnlyLoadedApps(): void { * The LoadAdditionalEntriesEvent is only dispatched by setup(), not by getAll(). */ public function testGetAllDoesNotDispatchAdditionalEntries(): void { - $this->userSession->method('isLoggedIn')->willReturn(false); - $this->appManager->method('getEnabledApps')->willReturn([]); + $this->mocks[IUserSession::class]->method('isLoggedIn')->willReturn(false); + $this->mocks[AppManager::class]->method('getEnabledApps')->willReturn([]); - $this->dispatcher->expects($this->never())->method('dispatchTyped'); + $this->mocks[IEventDispatcher::class]->expects($this->never())->method('dispatchTyped'); $this->navigationManager->clear(); $this->assertEquals([], $this->navigationManager->getAll('all')); @@ -644,18 +614,18 @@ public function testGetAllDoesNotDispatchAdditionalEntries(): void { * and even when the app does not provide any navigation entries. */ public function testAppInfoResolvedOnlyOnce(): void { - $this->config->method('getUserValue')->willReturnArgument(3); + $this->mocks[IConfig::class]->method('getUserValue')->willReturnArgument(3); $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user001'); - $this->userSession->method('getUser')->willReturn($user); - $this->userSession->method('isLoggedIn')->willReturn(true); - $this->appManager->method('getEnabledAppsForUser')->with($user)->willReturn(['test']); - $this->appManager->method('isAppLoaded')->with('test')->willReturn(true); - $this->groupManager->expects($this->any())->method('isAdmin')->willReturn(false); + $this->mocks[IUserSession::class]->method('getUser')->willReturn($user); + $this->mocks[IUserSession::class]->method('isLoggedIn')->willReturn(true); + $this->mocks[AppManager::class]->method('getEnabledAppsForUser')->with($user)->willReturn(['test']); + $this->mocks[AppManager::class]->method('isAppLoaded')->with('test')->willReturn(true); + $this->mocks[Manager::class]->expects($this->any())->method('isAdmin')->willReturn(false); // App has no navigation entries; info.xml must only be read once - $this->appManager->expects($this->once()) + $this->mocks[AppManager::class]->expects($this->once()) ->method('getAppInfo') ->with('test') ->willReturn(['navigations' => []]); @@ -670,18 +640,18 @@ public function testAppInfoResolvedOnlyOnce(): void { * clear(true) resets it, forcing a fresh resolve. */ public function testClearResetsResolvedStateOnlyWhenRequested(): void { - $this->config->method('getUserValue')->willReturnArgument(3); + $this->mocks[IConfig::class]->method('getUserValue')->willReturnArgument(3); $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user001'); - $this->userSession->method('getUser')->willReturn($user); - $this->userSession->method('isLoggedIn')->willReturn(true); - $this->appManager->method('getEnabledAppsForUser')->with($user)->willReturn(['test']); - $this->appManager->method('isAppLoaded')->with('test')->willReturn(true); - $this->groupManager->expects($this->any())->method('isAdmin')->willReturn(false); + $this->mocks[IUserSession::class]->method('getUser')->willReturn($user); + $this->mocks[IUserSession::class]->method('isLoggedIn')->willReturn(true); + $this->mocks[AppManager::class]->method('getEnabledAppsForUser')->with($user)->willReturn(['test']); + $this->mocks[AppManager::class]->method('isAppLoaded')->with('test')->willReturn(true); + $this->mocks[Manager::class]->expects($this->any())->method('isAdmin')->willReturn(false); // Resolved once for the initial getAll(), then again after clear(true) resets the state - $this->appManager->expects($this->exactly(2)) + $this->mocks[AppManager::class]->expects($this->exactly(2)) ->method('getAppInfo') ->with('test') ->willReturn(['navigations' => []]); @@ -869,9 +839,9 @@ public function testGetDefaultEntryIdForUser(string $defaultApps, string $userDe ]; }); - $this->appManager->method('getEnabledApps')->willReturn(['files']); - $this->appManager->method('getEnabledAppsForUser')->willReturn(['files']); - $this->appManager->expects($this->atLeastOnce()) + $this->mocks[AppManager::class]->method('getEnabledApps')->willReturn(['files']); + $this->mocks[AppManager::class]->method('getEnabledAppsForUser')->willReturn(['files']); + $this->mocks[AppManager::class]->expects($this->atLeastOnce()) ->method('isAppLoaded') ->willReturnMap([ ['test', true], @@ -881,45 +851,45 @@ public function testGetDefaultEntryIdForUser(string $defaultApps, string $userDe $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user1'); - $this->userSession->expects($this->atLeastOnce()) + $this->mocks[IUserSession::class]->expects($this->atLeastOnce()) ->method('getUser') ->willReturn($user); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('getSystemValueString') ->with('defaultapp', $this->anything()) ->willReturn($defaultApps); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('getUserValue') ->willReturnMap([ ['user1', 'core', 'defaultapp', '', $userDefaultApps], ['user1', 'core', 'apporder', '[]', $userApporder], ]); - $this->groupManager->expects($this->any())->method('isAdmin')->willReturn(false); + $this->mocks[Manager::class]->expects($this->any())->method('isAdmin')->willReturn(false); $this->navigationManager->setup(); $this->assertEquals($expectedApp, $this->navigationManager->getDefaultEntryIdForUser(null, $withFallbacks)); } public function testDefaultEntryUpdated(): void { - $this->appManager->method('getEnabledApps')->willReturn([]); - $this->appManager->method('getEnabledAppsForUser')->willReturn([]); - $this->groupManager->expects($this->any())->method('isAdmin')->willReturn(false); + $this->mocks[AppManager::class]->method('getEnabledApps')->willReturn([]); + $this->mocks[AppManager::class]->method('getEnabledAppsForUser')->willReturn([]); + $this->mocks[Manager::class]->expects($this->any())->method('isAdmin')->willReturn(false); $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('user1'); - $this->userSession + $this->mocks[IUserSession::class] ->method('getUser') ->willReturn($user); - $this->config + $this->mocks[IConfig::class] ->method('getSystemValueString') ->with('defaultapp', $this->anything()) ->willReturn('app4,app3,app2,app1'); - $this->config + $this->mocks[IConfig::class] ->method('getUserValue') ->willReturnMap([ ['user1', 'core', 'defaultapp', '', ''], diff --git a/tests/lib/Notification/ManagerTest.php b/tests/lib/Notification/ManagerTest.php index bf6629afec4b9..424b8f5b68615 100644 --- a/tests/lib/Notification/ManagerTest.php +++ b/tests/lib/Notification/ManagerTest.php @@ -28,54 +28,23 @@ class ManagerTest extends TestCase { /** @var IManager */ protected $manager; - - protected IValidator&MockObject $validator; - protected IRichTextFormatter&MockObject $richTextFormatter; - /** @var IUserManager|MockObject */ - protected $userManager; - /** @var ICacheFactory|MockObject */ - protected $cacheFactory; /** @var ICache|MockObject */ protected $cache; - /** @var IRegistry|MockObject */ - protected $subscriptionRegistry; - /** @var LoggerInterface|MockObject */ - protected $logger; - /** @var Coordinator|MockObject */ - protected $coordinator; /** @var RegistrationContext|MockObject */ protected $registrationContext; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->validator = $this->createMock(IValidator::class); - $this->richTextFormatter = $this->createMock(IRichTextFormatter::class); - $this->userManager = $this->createMock(IUserManager::class); $this->cache = $this->createMock(ICache::class); - $this->subscriptionRegistry = $this->createMock(IRegistry::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->cacheFactory = $this->createMock(ICacheFactory::class); - $this->cacheFactory->method('createDistributed') + $this->manager = $this->createInstanceWithMocks(Manager::class); + $this->mocks[ICacheFactory::class]->method('createDistributed') ->with('notifications') ->willReturn($this->cache); $this->registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator = $this->createMock(Coordinator::class); - $this->coordinator->method('getRegistrationContext') + $this->mocks[Coordinator::class]->method('getRegistrationContext') ->willReturn($this->registrationContext); - - $this->manager = new Manager( - $this->validator, - $this->userManager, - $this->cacheFactory, - $this->subscriptionRegistry, - $this->logger, - $this->coordinator, - $this->richTextFormatter, - ); } public function testRegisterApp(): void { @@ -94,7 +63,7 @@ public function testRegisterApp(): void { public function testRegisterAppInvalid(): void { $this->manager->registerApp(DummyNotifier::class); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('error'); self::invokePrivate($this->manager, 'getApps'); } @@ -125,7 +94,7 @@ public function testRegisterNotifierBootstrap(): void { public function testRegisterNotifierInvalid(): void { $this->manager->registerNotifierService(DummyApp::class); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('error'); self::invokePrivate($this->manager, 'getNotifiers'); } @@ -146,13 +115,13 @@ public function testNotify(): void { $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->validator, - $this->userManager, - $this->cacheFactory, - $this->subscriptionRegistry, - $this->logger, - $this->coordinator, - $this->richTextFormatter, + $this->mocks[IValidator::class], + $this->mocks[IUserManager::class], + $this->mocks[ICacheFactory::class], + $this->mocks[IRegistry::class], + $this->mocks[LoggerInterface::class], + $this->mocks[Coordinator::class], + $this->mocks[IRichTextFormatter::class], ]) ->onlyMethods(['getApps']) ->getMock(); @@ -177,13 +146,13 @@ public function testNotifyInvalid(): void { $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->validator, - $this->userManager, - $this->cacheFactory, - $this->subscriptionRegistry, - $this->logger, - $this->coordinator, - $this->richTextFormatter, + $this->mocks[IValidator::class], + $this->mocks[IUserManager::class], + $this->mocks[ICacheFactory::class], + $this->mocks[IRegistry::class], + $this->mocks[LoggerInterface::class], + $this->mocks[Coordinator::class], + $this->mocks[IRichTextFormatter::class], ]) ->onlyMethods(['getApps']) ->getMock(); @@ -202,13 +171,13 @@ public function testMarkProcessed(): void { $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->validator, - $this->userManager, - $this->cacheFactory, - $this->subscriptionRegistry, - $this->logger, - $this->coordinator, - $this->richTextFormatter, + $this->mocks[IValidator::class], + $this->mocks[IUserManager::class], + $this->mocks[ICacheFactory::class], + $this->mocks[IRegistry::class], + $this->mocks[LoggerInterface::class], + $this->mocks[Coordinator::class], + $this->mocks[IRichTextFormatter::class], ]) ->onlyMethods(['getApps']) ->getMock(); @@ -228,13 +197,13 @@ public function testGetCount(): void { $manager = $this->getMockBuilder(Manager::class) ->setConstructorArgs([ - $this->validator, - $this->userManager, - $this->cacheFactory, - $this->subscriptionRegistry, - $this->logger, - $this->coordinator, - $this->richTextFormatter, + $this->mocks[IValidator::class], + $this->mocks[IUserManager::class], + $this->mocks[ICacheFactory::class], + $this->mocks[IRegistry::class], + $this->mocks[LoggerInterface::class], + $this->mocks[Coordinator::class], + $this->mocks[IRichTextFormatter::class], ]) ->onlyMethods(['getApps']) ->getMock(); @@ -262,10 +231,10 @@ public static function dataIsFairUseOfFreePushService(): array { */ #[\PHPUnit\Framework\Attributes\DataProvider('dataIsFairUseOfFreePushService')] public function testIsFairUseOfFreePushService(bool $hasValidSubscription, int $userCount, bool $isFair): void { - $this->subscriptionRegistry->method('delegateHasValidSubscription') + $this->mocks[IRegistry::class]->method('delegateHasValidSubscription') ->willReturn($hasValidSubscription); - $this->userManager->method('countSeenUsers') + $this->mocks[IUserManager::class]->method('countSeenUsers') ->willReturn($userCount); $this->assertSame($isFair, $this->manager->isFairUseOfFreePushService()); diff --git a/tests/lib/Notification/NotificationTest.php b/tests/lib/Notification/NotificationTest.php index d684f3876f8a0..63486a7b3c075 100644 --- a/tests/lib/Notification/NotificationTest.php +++ b/tests/lib/Notification/NotificationTest.php @@ -14,21 +14,16 @@ use OCP\Notification\INotification; use OCP\RichObjectStrings\IRichTextFormatter; use OCP\RichObjectStrings\IValidator; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class NotificationTest extends TestCase { /** @var INotification */ protected $notification; - protected IValidator&MockObject $validator; - protected IRichTextFormatter&MockObject $richTextFormatter; #[\Override] protected function setUp(): void { parent::setUp(); - $this->validator = $this->createMock(IValidator::class); - $this->richTextFormatter = $this->createMock(IRichTextFormatter::class); - $this->notification = new Notification($this->validator, $this->richTextFormatter); + $this->notification = $this->createInstanceWithMocks(Notification::class); } protected static function dataValidString($maxLength): array { @@ -539,7 +534,7 @@ public function testIsValid($isValidCommon, $subject, $expected): void { 'getSubject', 'getParsedSubject', ]) - ->setConstructorArgs([$this->validator, $this->richTextFormatter]) + ->setConstructorArgs([$this->mocks[IValidator::class], $this->mocks[IRichTextFormatter::class]]) ->getMock(); $notification->expects($this->once()) @@ -572,7 +567,7 @@ public function testIsParsedValid($isValidCommon, $subject, $expected): void { 'getParsedSubject', 'getSubject', ]) - ->setConstructorArgs([$this->validator, $this->richTextFormatter]) + ->setConstructorArgs([$this->mocks[IValidator::class], $this->mocks[IRichTextFormatter::class]]) ->getMock(); $notification->expects($this->once()) @@ -621,7 +616,7 @@ public function testIsValidCommon($app, $user, $timestamp, $objectType, $objectI 'getObjectType', 'getObjectId', ]) - ->setConstructorArgs([$this->validator, $this->richTextFormatter]) + ->setConstructorArgs([$this->mocks[IValidator::class], $this->mocks[IRichTextFormatter::class]]) ->getMock(); $notification->expects($this->any()) diff --git a/tests/lib/OCM/Rfc9421SignatoryManagerTest.php b/tests/lib/OCM/Rfc9421SignatoryManagerTest.php index 4bdda7379672f..a5cf9ef8c58cf 100644 --- a/tests/lib/OCM/Rfc9421SignatoryManagerTest.php +++ b/tests/lib/OCM/Rfc9421SignatoryManagerTest.php @@ -14,22 +14,19 @@ use OC\OCM\Rfc9421SignatoryManager; use OCP\Security\Signature\Exceptions\IdentityNotFoundException; use OCP\Security\Signature\Model\Signatory; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class Rfc9421SignatoryManagerTest extends TestCase { - private OCMSignatoryManager&MockObject $delegate; private Rfc9421SignatoryManager $wrapper; #[\Override] protected function setUp(): void { parent::setUp(); - $this->delegate = $this->createMock(OCMSignatoryManager::class); - $this->wrapper = new Rfc9421SignatoryManager($this->delegate); + $this->wrapper = $this->createInstanceWithMocks(Rfc9421SignatoryManager::class); } public function testGetOptionsForcesRfc9421Format(): void { - $this->delegate->method('getOptions')->willReturn([ + $this->mocks[OCMSignatoryManager::class]->method('getOptions')->willReturn([ 'algorithm' => 'rsa-sha512', 'rfc9421.format' => false, ]); @@ -41,26 +38,26 @@ public function testGetOptionsForcesRfc9421Format(): void { public function testGetLocalSignatoryReturnsJwksKey(): void { $signatory = $this->createMock(Signatory::class); - $this->delegate->method('getLocalJwksSignatory')->willReturn($signatory); + $this->mocks[OCMSignatoryManager::class]->method('getLocalJwksSignatory')->willReturn($signatory); $this->assertSame($signatory, $this->wrapper->getLocalSignatory()); } public function testGetLocalSignatoryThrowsWhenJwksKeyUnavailable(): void { - $this->delegate->method('getLocalJwksSignatory')->willReturn(null); + $this->mocks[OCMSignatoryManager::class]->method('getLocalJwksSignatory')->willReturn(null); $this->expectException(IdentityNotFoundException::class); $this->wrapper->getLocalSignatory(); } public function testProviderIdDelegated(): void { - $this->delegate->method('getProviderId')->willReturn('ocm'); + $this->mocks[OCMSignatoryManager::class]->method('getProviderId')->willReturn('ocm'); $this->assertSame('ocm', $this->wrapper->getProviderId()); } public function testRemoteSignatoryDelegated(): void { $signatory = $this->createMock(Signatory::class); - $this->delegate->expects($this->once()) + $this->mocks[OCMSignatoryManager::class]->expects($this->once()) ->method('getRemoteSignatory') ->with('sender.example.org') ->willReturn($signatory); @@ -69,7 +66,7 @@ public function testRemoteSignatoryDelegated(): void { public function testRemoteKeyDelegated(): void { $key = $this->createMock(Key::class); - $this->delegate->expects($this->once()) + $this->mocks[OCMSignatoryManager::class]->expects($this->once()) ->method('getRemoteKey') ->with('sender.example.org', 'kid-1') ->willReturn($key); diff --git a/tests/lib/Preview/GeneratorTest.php b/tests/lib/Preview/GeneratorTest.php index 9024d2d0b6887..f1978495185cf 100644 --- a/tests/lib/Preview/GeneratorTest.php +++ b/tests/lib/Preview/GeneratorTest.php @@ -27,8 +27,6 @@ use OCP\Preview\IVersionedPreviewFile; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; -use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; use Test\TestCase; abstract class VersionedPreviewFile implements IVersionedPreviewFile, File { @@ -36,42 +34,13 @@ abstract class VersionedPreviewFile implements IVersionedPreviewFile, File { } class GeneratorTest extends TestCase { - private IConfig&MockObject $config; - private IAppConfig&MockObject $appConfig; - private IPreview&MockObject $previewManager; - private GeneratorHelper&MockObject $helper; - private IEventDispatcher&MockObject $eventDispatcher; private Generator $generator; - private LoggerInterface&MockObject $logger; - private StorageFactory&MockObject $storageFactory; - private PreviewMapper&MockObject $previewMapper; - private PreviewMigrationService&MockObject $migrationService; #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->appConfig = $this->createMock(IAppConfig::class); - $this->previewManager = $this->createMock(IPreview::class); - $this->helper = $this->createMock(GeneratorHelper::class); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->previewMapper = $this->createMock(PreviewMapper::class); - $this->storageFactory = $this->createMock(StorageFactory::class); - $this->migrationService = $this->createMock(PreviewMigrationService::class); - - $this->generator = new Generator( - $this->config, - $this->appConfig, - $this->previewManager, - $this->helper, - $this->eventDispatcher, - $this->logger, - $this->previewMapper, - $this->storageFactory, - $this->migrationService, - ); + $this->generator = $this->createInstanceWithMocks(Generator::class); } private function getFile(int $fileId, string $mimeType, bool $hasVersion = false): File { @@ -99,7 +68,7 @@ private function getFile(int $fileId, string $mimeType, bool $hasVersion = false public function testGetCachedPreview(bool $hasPreview): void { $file = $this->getFile(42, 'myMimeType', $hasPreview); - $this->previewManager->method('isMimeSupported') + $this->mocks[IPreview::class]->method('isMimeSupported') ->with($this->equalTo('myMimeType')) ->willReturn(true); @@ -123,14 +92,14 @@ public function testGetCachedPreview(bool $hasPreview): void { $previewFile->setStorageId(1); $previewFile->setMimeType('image/png'); - $this->previewMapper->method('getAvailablePreviews') + $this->mocks[PreviewMapper::class]->method('getAvailablePreviews') ->with($this->equalTo([42])) ->willReturn([42 => [ $maxPreview, $previewFile, ]]); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null)); @@ -144,20 +113,20 @@ public function testGetCachedPreview(bool $hasPreview): void { public function testGetNewPreview(bool $hasVersion): void { $file = $this->getFile(42, 'myMimeType', $hasVersion); - $this->previewManager->method('isMimeSupported') + $this->mocks[IPreview::class]->method('isMimeSupported') ->with($this->equalTo('myMimeType')) ->willReturn(true); - $this->previewMapper->method('getAvailablePreviews') + $this->mocks[PreviewMapper::class]->method('getAvailablePreviews') ->with($this->equalTo([42])) ->willReturn([42 => []]); - $this->config->method('getSystemValueString') + $this->mocks[IConfig::class]->method('getSystemValueString') ->willReturnCallback(function ($key, $default) { return $default; }); - $this->config->method('getSystemValueInt') + $this->mocks[IConfig::class]->method('getSystemValueInt') ->willReturnCallback(function ($key, $default) { return $default; }); @@ -173,13 +142,13 @@ public function testGetNewPreview(bool $hasVersion): void { ->with($file) ->willReturn(true); - $this->previewManager->method('getProviders') + $this->mocks[IPreview::class]->method('getProviders') ->willReturn([ '/image\/png/' => ['wrongProvider'], '/myMimeType/' => ['brokenProvider', 'invalidProvider', 'unavailableProvider', 'validProvider'], ]); - $this->helper->method('getProvider') + $this->mocks[GeneratorHelper::class]->method('getProvider') ->willReturnCallback(function ($provider) use ($invalidProvider, $validProvider, $unavailableProvider) { if ($provider === 'wrongProvider') { $this->fail('Wrongprovider should not be constructed!'); @@ -201,7 +170,7 @@ public function testGetNewPreview(bool $hasVersion): void { $image->method('valid')->willReturn(true); $image->method('dataMimeType')->willReturn('image/png'); - $this->helper->method('getThumbnail') + $this->mocks[GeneratorHelper::class]->method('getThumbnail') ->willReturnCallback(function ($provider, $file, $x, $y) use ($invalidProvider, $validProvider, $image): false|IImage { if ($provider === $validProvider) { return $image; @@ -213,13 +182,13 @@ public function testGetNewPreview(bool $hasVersion): void { $image->method('data') ->willReturn('my data'); - $this->previewMapper->method('insert') + $this->mocks[PreviewMapper::class]->method('insert') ->willReturnCallback(fn (Preview $preview): Preview => $preview); - $this->previewMapper->method('update') + $this->mocks[PreviewMapper::class]->method('update') ->willReturnCallback(fn (Preview $preview): Preview => $preview); - $this->storageFactory->method('writePreview') + $this->mocks[StorageFactory::class]->method('writePreview') ->willReturnCallback(function (Preview $preview, mixed $data) use ($hasVersion): int { $data = stream_get_contents($data); if ($hasVersion) { @@ -245,10 +214,10 @@ public function testGetNewPreview(bool $hasVersion): void { }); $image = $this->getMockImage(2048, 2048, 'my resized data'); - $this->helper->method('getImage') + $this->mocks[GeneratorHelper::class]->method('getImage') ->willReturn($image); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null)); @@ -280,31 +249,31 @@ public function testMigrateOldPreview(): void { $previewFile->setStorageId(1); $previewFile->setMimeType('image/png'); - $this->previewManager->method('isMimeSupported') + $this->mocks[IPreview::class]->method('isMimeSupported') ->with($this->equalTo('myMimeType')) ->willReturn(true); - $this->previewMapper->method('getAvailablePreviews') + $this->mocks[PreviewMapper::class]->method('getAvailablePreviews') ->with($this->equalTo([42])) ->willReturn([42 => []]); - $this->config->method('getSystemValueString') + $this->mocks[IConfig::class]->method('getSystemValueString') ->willReturnCallback(function ($key, $default) { return $default; }); - $this->config->method('getSystemValueInt') + $this->mocks[IConfig::class]->method('getSystemValueInt') ->willReturnCallback(function ($key, $default) { return $default; }); - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->willReturnCallback(fn ($app, $key, $default) => match ($key) { ConfigLexicon::ON_DEMAND_PREVIEW_MIGRATION => true, 'previewMovedDone' => false, }); - $this->migrationService->expects($this->exactly(1)) + $this->mocks[PreviewMigrationService::class]->expects($this->exactly(1)) ->method('migrateFileId') ->willReturn([$maxPreview, $previewFile]); @@ -318,7 +287,7 @@ public function testInvalidMimeType(): void { $file = $this->getFile(42, 'invalidType'); - $this->previewManager->method('isMimeSupported') + $this->mocks[IPreview::class]->method('isMimeSupported') ->with('invalidType') ->willReturn(false); @@ -330,13 +299,13 @@ public function testInvalidMimeType(): void { $maxPreview->setVersion(null); $maxPreview->setMimetype('image/png'); - $this->previewMapper->method('getAvailablePreviews') + $this->mocks[PreviewMapper::class]->method('getAvailablePreviews') ->with($this->equalTo([42])) ->willReturn([42 => [ $maxPreview, ]]); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with(new BeforePreviewFetchedEvent($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType')); @@ -363,17 +332,17 @@ public function testReturnCachedPreviewsWithoutCheckingSupportedMimetype(): void $previewFile->setVersion(null); $previewFile->setMimeType('image/png'); - $this->previewMapper->method('getAvailablePreviews') + $this->mocks[PreviewMapper::class]->method('getAvailablePreviews') ->with($this->equalTo([42])) ->willReturn([42 => [ $maxPreview, $previewFile, ]]); - $this->previewManager->expects($this->never()) + $this->mocks[IPreview::class]->expects($this->never()) ->method('isMimeSupported'); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with(new BeforePreviewFetchedEvent($file, 1024, 512, true, IPreview::MODE_COVER, 'invalidType')); @@ -384,14 +353,14 @@ public function testReturnCachedPreviewsWithoutCheckingSupportedMimetype(): void public function testNoProvider(): void { $file = $this->getFile(42, 'myMimeType'); - $this->previewMapper->method('getAvailablePreviews') + $this->mocks[PreviewMapper::class]->method('getAvailablePreviews') ->with($this->equalTo([42])) ->willReturn([42 => []]); - $this->previewManager->method('getProviders') + $this->mocks[IPreview::class]->method('getProviders') ->willReturn([]); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with(new BeforePreviewFetchedEvent($file, 100, 100, false, IPreview::MODE_FILL, null)); @@ -459,7 +428,7 @@ public static function dataSize(): array { public function testCorrectSize(int $maxX, int $maxY, int $reqX, int $reqY, bool $crop, string $mode, int $expectedX, int $expectedY): void { $file = $this->getFile(42, 'myMimeType'); - $this->previewManager->method('isMimeSupported') + $this->mocks[IPreview::class]->method('isMimeSupported') ->with($this->equalTo('myMimeType')) ->willReturn(true); @@ -474,7 +443,7 @@ public function testCorrectSize(int $maxX, int $maxY, int $reqX, int $reqY, bool $this->assertSame($maxPreview->getName(), $maxX . '-' . $maxY . '-max.png'); $this->assertSame($maxPreview->getMimeType(), 'image/png'); - $this->previewMapper->method('getAvailablePreviews') + $this->mocks[PreviewMapper::class]->method('getAvailablePreviews') ->with($this->equalTo([42])) ->willReturn([42 => [ $maxPreview, @@ -487,22 +456,22 @@ public function testCorrectSize(int $maxX, int $maxY, int $reqX, int $reqY, bool $filename .= '.png'; $image = $this->getMockImage($maxX, $maxY); - $this->helper->method('getImage') + $this->mocks[GeneratorHelper::class]->method('getImage') ->willReturn($image); - $this->previewMapper->method('insert') + $this->mocks[PreviewMapper::class]->method('insert') ->willReturnCallback(function (Preview $preview) use ($filename): Preview { $this->assertSame($preview->getName(), $filename); return $preview; }); - $this->previewMapper->method('update') + $this->mocks[PreviewMapper::class]->method('update') ->willReturnCallback(fn (Preview $preview): Preview => $preview); - $this->storageFactory->method('writePreview') + $this->mocks[StorageFactory::class]->method('writePreview') ->willReturn(1000); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with(new BeforePreviewFetchedEvent($file, $reqX, $reqY, $crop, $mode, null)); diff --git a/tests/lib/Preview/Storage/LocalPreviewStorageTest.php b/tests/lib/Preview/Storage/LocalPreviewStorageTest.php index c46b3c3620308..3fd669dabd250 100644 --- a/tests/lib/Preview/Storage/LocalPreviewStorageTest.php +++ b/tests/lib/Preview/Storage/LocalPreviewStorageTest.php @@ -26,17 +26,8 @@ use OCP\IDBConnection; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; class LocalPreviewStorageTest extends TestCase { - private IConfig&MockObject $config; - private PreviewMapper&MockObject $previewMapper; - private IAppConfig&MockObject $appConfig; - private IDBConnection&MockObject $connection; - private IMimeTypeDetector&MockObject $mimeTypeDetector; - private LoggerInterface&MockObject $logger; - private IMimeTypeLoader&MockObject $mimeTypeLoader; - private IRootFolder&MockObject $rootFolder; private string $tmpDir; private LocalPreviewStorage $storage; @@ -50,34 +41,14 @@ protected function setUp(): void { $this->tmpDir = sys_get_temp_dir() . '/nc_preview_test_' . uniqid(); mkdir($this->tmpDir, 0777, true); - $this->config = $this->createMock(IConfig::class); - $this->config->method('getSystemValueString') + $this->storage = $this->createInstanceWithMocks(LocalPreviewStorage::class); + $this->mocks[IConfig::class]->method('getSystemValueString') ->with('datadirectory', $this->anything()) ->willReturn($this->tmpDir); + $this->mocks[IRootFolder::class]->method('getAppDataDirectoryName')->willReturn('appdata_test'); - $this->rootFolder = $this->createMock(IRootFolder::class); - $this->rootFolder->method('getAppDataDirectoryName')->willReturn('appdata_test'); - - $this->previewMapper = $this->createMock(PreviewMapper::class); - $this->appConfig = $this->createMock(IAppConfig::class); - $this->connection = $this->createMock(IDBConnection::class); - $this->mimeTypeDetector = $this->createMock(IMimeTypeDetector::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->mimeTypeLoader = $this->createMock(IMimeTypeLoader::class); - - $this->mimeTypeDetector->method('detectPath')->willReturn('image/jpeg'); - $this->mimeTypeLoader->method('getMimetypeById')->willReturn('image/jpeg'); - - $this->storage = new LocalPreviewStorage( - $this->config, - $this->previewMapper, - $this->appConfig, - $this->connection, - $this->mimeTypeDetector, - $this->logger, - $this->mimeTypeLoader, - $this->rootFolder, - ); + $this->mocks[IMimeTypeDetector::class]->method('detectPath')->willReturn('image/jpeg'); + $this->mocks[IMimeTypeLoader::class]->method('getMimetypeById')->willReturn('image/jpeg'); } #[\Override] @@ -146,7 +117,7 @@ private function buildQueryBuilderMock(array $rows): IQueryBuilder&MockObject { * checkForFileCache = false (no legacy path-hash queries). */ private function setMigrationDone(): void { - $this->appConfig->method('getValueBool') + $this->mocks[IAppConfig::class]->method('getValueBool') ->with('core', 'previewMovedDone') ->willReturn(true); } @@ -168,13 +139,13 @@ public function testScanCommitsFinalBatch(): void { 'etag' => 'abc', 'mimetype' => '6', ]; - $this->connection->method('getTypedQueryBuilder') + $this->mocks[IDBConnection::class]->method('getTypedQueryBuilder') ->willReturn($this->buildQueryBuilderMock([$filecacheRow])); // Outer batch transaction + one inner savepoint for the insert. - $this->connection->expects($this->exactly(2))->method('beginTransaction'); - $this->connection->expects($this->exactly(2))->method('commit'); - $this->connection->expects($this->never())->method('rollBack'); + $this->mocks[IDBConnection::class]->expects($this->exactly(2))->method('beginTransaction'); + $this->mocks[IDBConnection::class]->expects($this->exactly(2))->method('commit'); + $this->mocks[IDBConnection::class]->expects($this->never())->method('rollBack'); $count = $this->storage->scan(); @@ -200,7 +171,7 @@ public function testScanHandlesUniqueConstraintViolation(): void { 'etag' => 'abc', 'mimetype' => '6', ]; - $this->connection->method('getTypedQueryBuilder') + $this->mocks[IDBConnection::class]->method('getTypedQueryBuilder') ->willReturn($this->buildQueryBuilderMock([$filecacheRow])); $ucvException = new class('duplicate key') extends DBException { @@ -209,12 +180,12 @@ public function getReason(): int { return self::REASON_UNIQUE_CONSTRAINT_VIOLATION; } }; - $this->previewMapper->method('insert')->willThrowException($ucvException); + $this->mocks[PreviewMapper::class]->method('insert')->willThrowException($ucvException); // Inner savepoint is rolled back; outer batch transaction is committed. - $this->connection->expects($this->exactly(2))->method('beginTransaction'); - $this->connection->expects($this->once())->method('commit'); - $this->connection->expects($this->exactly(1))->method('rollBack'); + $this->mocks[IDBConnection::class]->expects($this->exactly(2))->method('beginTransaction'); + $this->mocks[IDBConnection::class]->expects($this->once())->method('commit'); + $this->mocks[IDBConnection::class]->expects($this->exactly(1))->method('rollBack'); $count = $this->storage->scan(); @@ -236,7 +207,7 @@ public function testScanRethrowsUnexpectedInsertException(): void { 'etag' => 'abc', 'mimetype' => '6', ]; - $this->connection->method('getTypedQueryBuilder') + $this->mocks[IDBConnection::class]->method('getTypedQueryBuilder') ->willReturn($this->buildQueryBuilderMock([$filecacheRow])); $driverException = new class('some driver error') extends DBException { @@ -245,12 +216,12 @@ public function getReason(): int { return self::REASON_DRIVER; } }; - $this->previewMapper->method('insert')->willThrowException($driverException); + $this->mocks[PreviewMapper::class]->method('insert')->willThrowException($driverException); // Inner savepoint rolled back; outer batch also rolled back via rethrow. - $this->connection->expects($this->exactly(2))->method('beginTransaction'); - $this->connection->expects($this->never())->method('commit'); - $this->connection->expects($this->exactly(2))->method('rollBack'); + $this->mocks[IDBConnection::class]->expects($this->exactly(2))->method('beginTransaction'); + $this->mocks[IDBConnection::class]->expects($this->never())->method('commit'); + $this->mocks[IDBConnection::class]->expects($this->exactly(2))->method('rollBack'); $this->expectException(DBException::class); $this->storage->scan(); @@ -277,13 +248,13 @@ public function testScanFetchesAllFilecacheRows(): void { 'mimetype' => '6', ], $fileIds); - $this->connection->method('getTypedQueryBuilder') + $this->mocks[IDBConnection::class]->method('getTypedQueryBuilder') ->willReturn($this->buildQueryBuilderMock($filecacheRows)); // 1 outer batch transaction + 3 inner savepoints (one per preview insert). - $this->connection->expects($this->exactly(4))->method('beginTransaction'); - $this->connection->expects($this->exactly(4))->method('commit'); - $this->connection->expects($this->never())->method('rollBack'); + $this->mocks[IDBConnection::class]->expects($this->exactly(4))->method('beginTransaction'); + $this->mocks[IDBConnection::class]->expects($this->exactly(4))->method('commit'); + $this->mocks[IDBConnection::class]->expects($this->never())->method('rollBack'); $count = $this->storage->scan(); diff --git a/tests/lib/Repair/ClearFrontendCachesTest.php b/tests/lib/Repair/ClearFrontendCachesTest.php index 509c04ee52cbe..3766c675b9bbf 100644 --- a/tests/lib/Repair/ClearFrontendCachesTest.php +++ b/tests/lib/Repair/ClearFrontendCachesTest.php @@ -16,8 +16,6 @@ class ClearFrontendCachesTest extends \Test\TestCase { - private ICacheFactory&MockObject $cacheFactory; - private JSCombiner&MockObject $jsCombiner; private IOutput&MockObject $outputMock; protected ClearFrontendCaches $repair; @@ -28,10 +26,7 @@ protected function setUp(): void { $this->outputMock = $this->createMock(IOutput::class); - $this->cacheFactory = $this->createMock(ICacheFactory::class); - $this->jsCombiner = $this->createMock(JSCombiner::class); - - $this->repair = new ClearFrontendCaches($this->cacheFactory, $this->jsCombiner); + $this->repair = $this->createInstanceWithMocks(ClearFrontendCaches::class); } public function testRun(): void { @@ -39,9 +34,9 @@ public function testRun(): void { $imagePathCache->expects($this->once()) ->method('clear') ->with(''); - $this->jsCombiner->expects($this->once()) + $this->mocks[JSCombiner::class]->expects($this->once()) ->method('resetCache'); - $this->cacheFactory->expects($this->once()) + $this->mocks[ICacheFactory::class]->expects($this->once()) ->method('createDistributed') ->with('imagePath') ->willReturn($imagePathCache); diff --git a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php index ce188fe3fb84b..aefe90b5a32e3 100644 --- a/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php +++ b/tests/lib/Repair/ClearGeneratedAvatarCacheTest.php @@ -7,29 +7,18 @@ namespace Test\Repair; -use OC\Avatar\AvatarManager; use OC\Repair\ClearGeneratedAvatarCache; -use OCP\BackgroundJob\IJobList; use OCP\IConfig; -use PHPUnit\Framework\MockObject\MockObject; class ClearGeneratedAvatarCacheTest extends \Test\TestCase { - private AvatarManager&MockObject $avatarManager; - private IConfig&MockObject $config; - private IJobList&MockObject $jobList; - protected ClearGeneratedAvatarCache $repair; #[\Override] protected function setUp(): void { parent::setUp(); - $this->avatarManager = $this->createMock(AvatarManager::class); - $this->config = $this->createMock(IConfig::class); - $this->jobList = $this->createMock(IJobList::class); - - $this->repair = new ClearGeneratedAvatarCache($this->config, $this->avatarManager, $this->jobList); + $this->repair = $this->createInstanceWithMocks(ClearGeneratedAvatarCache::class); } public static function shouldRunDataProvider(): array { @@ -52,7 +41,7 @@ public static function shouldRunDataProvider(): array { */ #[\PHPUnit\Framework\Attributes\DataProvider('shouldRunDataProvider')] public function testShouldRun($from, $expected): void { - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->with('version', '0.0.0.0') ->willReturn($from); diff --git a/tests/lib/Repair/NC29/SanitizeAccountPropertiesTest.php b/tests/lib/Repair/NC29/SanitizeAccountPropertiesTest.php index 66f202b29fdbe..75f033acbcc11 100644 --- a/tests/lib/Repair/NC29/SanitizeAccountPropertiesTest.php +++ b/tests/lib/Repair/NC29/SanitizeAccountPropertiesTest.php @@ -11,21 +11,17 @@ use OCP\BackgroundJob\IJobList; use OCP\Migration\IOutput; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class SanitizeAccountPropertiesTest extends TestCase { - private IJobList&MockObject $jobList; private SanitizeAccountProperties $repairStep; #[\Override] protected function setUp(): void { parent::setUp(); - $this->jobList = $this->createMock(IJobList::class); - - $this->repairStep = new SanitizeAccountProperties($this->jobList); + $this->repairStep = $this->createInstanceWithMocks(SanitizeAccountProperties::class); } public function testGetName(): void { @@ -33,7 +29,7 @@ public function testGetName(): void { } public function testRun(): void { - $this->jobList->expects(self::once()) + $this->mocks[IJobList::class]->expects(self::once()) ->method('add') ->with(SanitizeAccountPropertiesJob::class, null); diff --git a/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php b/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php index b5a4781a1e313..25cd81bff0a86 100644 --- a/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php +++ b/tests/lib/Repair/Owncloud/CleanPreviewsBackgroundJobTest.php @@ -16,38 +16,19 @@ use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; use OCP\IUserManager; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class CleanPreviewsBackgroundJobTest extends TestCase { - private IRootFolder&MockObject $rootFolder; - private LoggerInterface&MockObject $logger; - private IJobList&MockObject $jobList; - private ITimeFactory&MockObject $timeFactory; - private IUserManager&MockObject $userManager; private CleanPreviewsBackgroundJob $job; #[\Override] public function setUp(): void { parent::setUp(); - $this->rootFolder = $this->createMock(IRootFolder::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->jobList = $this->createMock(IJobList::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); - $this->userManager = $this->createMock(IUserManager::class); - - $this->userManager->expects($this->any())->method('userExists')->willReturn(true); - - $this->job = new CleanPreviewsBackgroundJob( - $this->rootFolder, - $this->logger, - $this->jobList, - $this->timeFactory, - $this->userManager - ); + $this->job = $this->createInstanceWithMocks(CleanPreviewsBackgroundJob::class); + $this->mocks[IUserManager::class]->expects($this->any())->method('userExists')->willReturn(true); } public function testCleanupPreviewsUnfinished(): void { @@ -55,7 +36,7 @@ public function testCleanupPreviewsUnfinished(): void { $userRoot = $this->createMock(Folder::class); $thumbnailFolder = $this->createMock(Folder::class); - $this->rootFolder->method('getUserFolder') + $this->mocks[IRootFolder::class]->method('getUserFolder') ->with($this->equalTo('myuid')) ->willReturn($userFolder); @@ -75,9 +56,9 @@ public function testCleanupPreviewsUnfinished(): void { $thumbnailFolder->expects($this->never()) ->method('delete'); - $this->timeFactory->method('getTime')->willReturnOnConsecutiveCalls(100, 200); + $this->mocks[ITimeFactory::class]->method('getTime')->willReturnOnConsecutiveCalls(100, 200); - $this->jobList->expects($this->once()) + $this->mocks[IJobList::class]->expects($this->once()) ->method('add') ->with( $this->equalTo(CleanPreviewsBackgroundJob::class), @@ -85,7 +66,7 @@ public function testCleanupPreviewsUnfinished(): void { ); $loggerCalls = []; - $this->logger->expects($this->exactly(2)) + $this->mocks[LoggerInterface::class]->expects($this->exactly(2)) ->method('info') ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); @@ -103,7 +84,7 @@ public function testCleanupPreviewsFinished(): void { $userRoot = $this->createMock(Folder::class); $thumbnailFolder = $this->createMock(Folder::class); - $this->rootFolder->method('getUserFolder') + $this->mocks[IRootFolder::class]->method('getUserFolder') ->with($this->equalTo('myuid')) ->willReturn($userFolder); @@ -121,13 +102,13 @@ public function testCleanupPreviewsFinished(): void { $thumbnailFolder->method('getDirectoryListing') ->willReturn([$previewFolder1]); - $this->timeFactory->method('getTime')->willReturnOnConsecutiveCalls(100, 101); + $this->mocks[ITimeFactory::class]->method('getTime')->willReturnOnConsecutiveCalls(100, 101); - $this->jobList->expects($this->never()) + $this->mocks[IJobList::class]->expects($this->never()) ->method('add'); $loggerCalls = []; - $this->logger->expects($this->exactly(2)) + $this->mocks[LoggerInterface::class]->expects($this->exactly(2)) ->method('info') ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); @@ -144,12 +125,12 @@ public function testCleanupPreviewsFinished(): void { } public function testNoUserFolder(): void { - $this->rootFolder->method('getUserFolder') + $this->mocks[IRootFolder::class]->method('getUserFolder') ->with($this->equalTo('myuid')) ->willThrowException(new NotFoundException()); $loggerCalls = []; - $this->logger->expects($this->exactly(2)) + $this->mocks[LoggerInterface::class]->expects($this->exactly(2)) ->method('info') ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); @@ -166,7 +147,7 @@ public function testNoThumbnailFolder(): void { $userFolder = $this->createMock(IUserFolder::class); $userRoot = $this->createMock(Folder::class); - $this->rootFolder->method('getUserFolder') + $this->mocks[IRootFolder::class]->method('getUserFolder') ->with($this->equalTo('myuid')) ->willReturn($userFolder); @@ -177,7 +158,7 @@ public function testNoThumbnailFolder(): void { ->willThrowException(new NotFoundException()); $loggerCalls = []; - $this->logger->expects($this->exactly(2)) + $this->mocks[LoggerInterface::class]->expects($this->exactly(2)) ->method('info') ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); @@ -195,7 +176,7 @@ public function testNotPermittedToDelete(): void { $userRoot = $this->createMock(Folder::class); $thumbnailFolder = $this->createMock(Folder::class); - $this->rootFolder->method('getUserFolder') + $this->mocks[IRootFolder::class]->method('getUserFolder') ->with($this->equalTo('myuid')) ->willReturn($userFolder); @@ -214,9 +195,9 @@ public function testNotPermittedToDelete(): void { $thumbnailFolder->method('getDirectoryListing') ->willReturn([$previewFolder1]); - $this->timeFactory->method('getTime')->willReturnOnConsecutiveCalls(100, 101); + $this->mocks[ITimeFactory::class]->method('getTime')->willReturnOnConsecutiveCalls(100, 101); - $this->jobList->expects($this->never()) + $this->mocks[IJobList::class]->expects($this->never()) ->method('add'); $thumbnailFolder->expects($this->once()) @@ -224,7 +205,7 @@ public function testNotPermittedToDelete(): void { ->willThrowException(new NotPermittedException()); $loggerCalls = []; - $this->logger->expects($this->exactly(2)) + $this->mocks[LoggerInterface::class]->expects($this->exactly(2)) ->method('info') ->willReturnCallback(function () use (&$loggerCalls): void { $loggerCalls[] = func_get_args(); diff --git a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php index 7b064228b2518..b69649c6bcd92 100644 --- a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php +++ b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php @@ -14,28 +14,16 @@ use OCP\IUser; use OCP\IUserManager; use OCP\Migration\IOutput; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class CleanPreviewsTest extends TestCase { - private IJobList&MockObject $jobList; - private IUserManager&MockObject $userManager; - private IAppConfig&MockObject $appConfig; private CleanPreviews $repair; #[\Override] public function setUp(): void { parent::setUp(); - $this->jobList = $this->createMock(IJobList::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->appConfig = $this->createMock(IAppConfig::class); - - $this->repair = new CleanPreviews( - $this->jobList, - $this->userManager, - $this->appConfig - ); + $this->repair = $this->createInstanceWithMocks(CleanPreviews::class); } public function testGetName(): void { @@ -50,7 +38,7 @@ public function testRun(): void { $user2->method('getUID') ->willReturn('user2'); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('callForSeenUsers') ->willReturnCallback(function (\Closure $function) use (&$user1, $user2): void { $function($user1); @@ -58,19 +46,19 @@ public function testRun(): void { }); $jobListCalls = []; - $this->jobList->expects($this->exactly(2)) + $this->mocks[IJobList::class]->expects($this->exactly(2)) ->method('add') ->willReturnCallback(function () use (&$jobListCalls): void { $jobListCalls[] = func_get_args(); }); - $this->appConfig->expects($this->once()) + $this->mocks[IAppConfig::class]->expects($this->once()) ->method('getValueBool') ->with( $this->equalTo('core'), $this->equalTo('previewsCleanedUp'), )->willReturn(false); - $this->appConfig->expects($this->once()) + $this->mocks[IAppConfig::class]->expects($this->once()) ->method('setValueBool') ->with( $this->equalTo('core'), @@ -86,19 +74,19 @@ public function testRun(): void { } public function testRunAlreadyDone(): void { - $this->userManager->expects($this->never()) + $this->mocks[IUserManager::class]->expects($this->never()) ->method($this->anything()); - $this->jobList->expects($this->never()) + $this->mocks[IJobList::class]->expects($this->never()) ->method($this->anything()); - $this->appConfig->expects($this->once()) + $this->mocks[IAppConfig::class]->expects($this->once()) ->method('getValueBool') ->with( $this->equalTo('core'), $this->equalTo('previewsCleanedUp'), )->willReturn(true); - $this->appConfig->expects($this->never()) + $this->mocks[IAppConfig::class]->expects($this->never()) ->method('setValueBool'); $this->repair->run($this->createMock(IOutput::class)); diff --git a/tests/lib/Repair/RepairDavSharesTest.php b/tests/lib/Repair/RepairDavSharesTest.php index c671a6968783d..c6846da3a3a63 100644 --- a/tests/lib/Repair/RepairDavSharesTest.php +++ b/tests/lib/Repair/RepairDavSharesTest.php @@ -17,17 +17,12 @@ use OCP\IGroupManager; use OCP\Migration\IOutput; use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; use Test\TestCase; use function in_array; class RepairDavSharesTest extends TestCase { private IOutput&MockObject $output; - private IConfig&MockObject $config; - private IDBConnection&MockObject $dbc; - private LoggerInterface&MockObject $logger; - private IGroupManager&MockObject $groupManager; private RepairDavShares $repair; #[\Override] @@ -36,21 +31,11 @@ public function setUp(): void { $this->output = $this->createMock(IOutput::class); - $this->config = $this->createMock(IConfig::class); - $this->dbc = $this->createMock(IDBConnection::class); - $this->groupManager = $this->createMock(IGroupManager::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->repair = new RepairDavShares( - $this->config, - $this->dbc, - $this->groupManager, - $this->logger - ); + $this->repair = $this->createInstanceWithMocks(RepairDavShares::class); } public function testRun(): void { - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->with('version', '0.0.0') ->willReturn('20.0.2'); @@ -158,11 +143,11 @@ public function testRun(): void { $updateMock->expects($this->exactly(2)) ->method('executeStatement'); - $this->dbc->expects($this->atLeast(2)) + $this->mocks[IDBConnection::class]->expects($this->atLeast(2)) ->method('getQueryBuilder') ->willReturnOnConsecutiveCalls($selectMock, $updateMock); - $this->groupManager->expects($this->any()) + $this->mocks[IGroupManager::class]->expects($this->any()) ->method('groupExists') ->willReturnCallback(function (string $gid) use ($existingGroups) { return in_array($gid, $existingGroups, true); diff --git a/tests/lib/Search/SearchComposerTest.php b/tests/lib/Search/SearchComposerTest.php index 87f0c0b39fc5d..c6b2f5899adbe 100644 --- a/tests/lib/Search/SearchComposerTest.php +++ b/tests/lib/Search/SearchComposerTest.php @@ -20,55 +20,36 @@ use OCP\Search\IInAppSearch; use OCP\Search\IProvider; use OCP\Search\ISearchQuery; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; -use Psr\Log\LoggerInterface; use Test\TestCase; class SearchComposerTest extends TestCase { - private Coordinator&MockObject $bootstrapCoordinator; - private ContainerInterface&MockObject $container; - private IURLGenerator&MockObject $urlGenerator; - private LoggerInterface&MockObject $logger; - private IAppConfig&MockObject $appConfig; private SearchComposer $searchComposer; #[\Override] protected function setUp(): void { parent::setUp(); - $this->bootstrapCoordinator = $this->createMock(Coordinator::class); - $this->container = $this->createMock(ContainerInterface::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->appConfig = $this->createMock(IAppConfig::class); - - $this->searchComposer = new SearchComposer( - $this->bootstrapCoordinator, - $this->container, - $this->urlGenerator, - $this->logger, - $this->appConfig - ); + $this->searchComposer = $this->createInstanceWithMocks(SearchComposer::class); $this->setupUrlGenerator(); } private function setupUrlGenerator(): void { - $this->urlGenerator->method('imagePath') + $this->mocks[IURLGenerator::class]->method('imagePath') ->willReturnCallback(function ($appId, $imageName) { return "/apps/$appId/img/$imageName"; }); } private function setupEmptyRegistrationContext(): void { - $this->bootstrapCoordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn(null); } private function setupAppConfigForAllowedProviders(array $allowedProviders = []): void { - $this->appConfig->method('getValueArray') + $this->mocks[IAppConfig::class]->method('getValueArray') ->with('core', 'unified_search.providers_allowed') ->willReturn($allowedProviders); } @@ -100,7 +81,7 @@ private function createMockProvidersAndRegistrations(array $providerConfigs): ar $containerMap[] = [$config['service'], $provider]; } - $this->container->expects($this->exactly(count($providerConfigs))) + $this->mocks[ContainerInterface::class]->expects($this->exactly(count($providerConfigs))) ->method('get') ->willReturnMap($containerMap); @@ -111,7 +92,7 @@ private function setupRegistrationContextWithProviders(array $registrations): vo $registrationContext = $this->createMock(RegistrationContext::class); $registrationContext->method('getSearchProviders')->willReturn($registrations); - $this->bootstrapCoordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($registrationContext); } diff --git a/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php b/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php index c8483fcb86edc..b3cd96913dc26 100644 --- a/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php +++ b/tests/lib/Security/Bruteforce/Backend/MemoryCacheBackendTest.php @@ -18,10 +18,6 @@ use Test\TestCase; class MemoryCacheBackendTest extends TestCase { - /** @var ICacheFactory|MockObject */ - private $cacheFactory; - /** @var ITimeFactory|MockObject */ - private $timeFactory; /** @var ICache|MockObject */ private $cache; private IBackend $backend; @@ -29,21 +25,14 @@ class MemoryCacheBackendTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->cacheFactory = $this->createMock(ICacheFactory::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); $this->cache = $this->createMock(ICache::class); - $this->cacheFactory + $this->backend = $this->createInstanceWithMocks(MemoryCacheBackend::class); + $this->mocks[ICacheFactory::class] ->expects($this->once()) ->method('createDistributed') ->with(MemoryCacheBackend::class) ->willReturn($this->cache); - - $this->backend = new MemoryCacheBackend( - $this->cacheFactory, - $this->timeFactory - ); } public function testGetAttemptsWithNoAttemptsBefore(): void { @@ -102,7 +91,7 @@ public function testRegisterAttemptWithNoAttemptsBefore(): void { } public function testRegisterAttempt(): void { - $this->timeFactory + $this->mocks[ITimeFactory::class] ->expects($this->once()) ->method('getTime') ->willReturn(12 * 3600 + 86); diff --git a/tests/lib/Security/Bruteforce/CapabilitiesTest.php b/tests/lib/Security/Bruteforce/CapabilitiesTest.php index f5174baed1888..638b15fa9a725 100644 --- a/tests/lib/Security/Bruteforce/CapabilitiesTest.php +++ b/tests/lib/Security/Bruteforce/CapabilitiesTest.php @@ -18,38 +18,25 @@ class CapabilitiesTest extends TestCase { /** @var Capabilities */ private $capabilities; - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $request; - - /** @var IThrottler|\PHPUnit\Framework\MockObject\MockObject */ - private $throttler; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->request = $this->createMock(IRequest::class); - - $this->throttler = $this->createMock(IThrottler::class); - - $this->capabilities = new Capabilities( - $this->request, - $this->throttler - ); + $this->capabilities = $this->createInstanceWithMocks(Capabilities::class); } public function testGetCapabilities(): void { - $this->throttler->expects($this->atLeastOnce()) + $this->mocks[IThrottler::class]->expects($this->atLeastOnce()) ->method('getDelay') ->with('10.10.10.10') ->willReturn(42); - $this->throttler->expects($this->atLeastOnce()) + $this->mocks[IThrottler::class]->expects($this->atLeastOnce()) ->method('isBypassListed') ->with('10.10.10.10') ->willReturn(true); - $this->request->method('getRemoteAddress') + $this->mocks[IRequest::class]->method('getRemoteAddress') ->willReturn('10.10.10.10'); $expected = [ @@ -64,12 +51,12 @@ public function testGetCapabilities(): void { } public function testGetCapabilitiesOnCli(): void { - $this->throttler->expects($this->atLeastOnce()) + $this->mocks[IThrottler::class]->expects($this->atLeastOnce()) ->method('getDelay') ->with('') ->willReturn(0); - $this->request->method('getRemoteAddress') + $this->mocks[IRequest::class]->method('getRemoteAddress') ->willReturn(''); $expected = [ diff --git a/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php b/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php index 72ad4e89d503c..e9051ed3af1da 100644 --- a/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php +++ b/tests/lib/Security/CSP/ContentSecurityPolicyNonceManagerTest.php @@ -13,27 +13,16 @@ use OC\Security\CSP\ContentSecurityPolicyNonceManager; use OC\Security\CSRF\CsrfToken; use OC\Security\CSRF\CsrfTokenManager; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ContentSecurityPolicyNonceManagerTest extends TestCase { - /** @var CsrfTokenManager&MockObject */ - private $CSRFTokenManager; - /** @var Request&MockObject */ - private $request; /** @var ContentSecurityPolicyNonceManager */ private $nonceManager; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->CSRFTokenManager = $this->createMock(CsrfTokenManager::class); - $this->request = $this->createMock(Request::class); - $this->nonceManager = new ContentSecurityPolicyNonceManager( - $this->CSRFTokenManager, - $this->request - ); + $this->nonceManager = $this->createInstanceWithMocks(ContentSecurityPolicyNonceManager::class); } public function testGetNonce(): void { @@ -45,7 +34,7 @@ public function testGetNonce(): void { ->method('getEncryptedValue') ->willReturn($tokenValue); - $this->CSRFTokenManager + $this->mocks[CsrfTokenManager::class] ->expects($this->once()) ->method('getToken') ->willReturn($token); @@ -57,12 +46,12 @@ public function testGetNonce(): void { public function testGetNonceServerVar(): void { $token = 'SERVERNONCE'; - $this->request + $this->mocks[Request::class] ->method('__isset') ->with('server') ->willReturn(true); - $this->request + $this->mocks[Request::class] ->method('__get') ->with('server') ->willReturn(['CSP_NONCE' => $token]); diff --git a/tests/lib/Security/HasherTest.php b/tests/lib/Security/HasherTest.php index f6dcf22116aea..6932f2e665ca9 100644 --- a/tests/lib/Security/HasherTest.php +++ b/tests/lib/Security/HasherTest.php @@ -100,21 +100,15 @@ public static function hashProviders73(): array { /** @var Hasher */ protected $hasher; - /** @var IConfig */ - protected $config; - #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - - $this->config->method('getSystemValueInt') + $this->hasher = $this->createInstanceWithMocks(Hasher::class); + $this->mocks[IConfig::class]->method('getSystemValueInt') ->willReturnCallback(function ($name, $default) { return $default; }); - - $this->hasher = new Hasher($this->config); } public function testHash(): void { @@ -130,7 +124,7 @@ public function testSplitHash($hash, $expected): void { #[\PHPUnit\Framework\Attributes\DataProvider('hashProviders70_71')] public function testVerify($password, $hash, $expected): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->any()) ->method('getSystemValue') ->willReturnCallback(function ($key, $default) { @@ -193,7 +187,7 @@ public function testUsePasswordDefaultArgon2iVerify(): void { $this->markTestSkipped('Need ARGON2 support to test ARGON2 hashes'); } - $this->config->method('getSystemValueBool') + $this->mocks[IConfig::class]->method('getSystemValueBool') ->with('hashing_default_password') ->willReturn(true); @@ -217,7 +211,7 @@ public function testDoNotUsePasswordDefaultArgon2idVerify(): void { $this->markTestSkipped('Need ARGON2ID support to test ARGON2ID hashes'); } - $this->config->method('getSystemValueBool') + $this->mocks[IConfig::class]->method('getSystemValueBool') ->with('hashing_default_password') ->willReturn(false); @@ -235,7 +229,7 @@ public function testHashUsePasswordDefault(): void { $this->markTestSkipped('Need ARGON2 support to test ARGON2 hashes'); } - $this->config->method('getSystemValueBool') + $this->mocks[IConfig::class]->method('getSystemValueBool') ->with('hashing_default_password') ->willReturn(true); diff --git a/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php b/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php index 1b08092c362b0..79b0147744f62 100644 --- a/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php +++ b/tests/lib/Security/RateLimiting/Backend/MemoryCacheBackendTest.php @@ -17,12 +17,6 @@ use Test\TestCase; class MemoryCacheBackendTest extends TestCase { - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; - /** @var ICacheFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $cacheFactory; - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; /** @var ICache|\PHPUnit\Framework\MockObject\MockObject */ private $cache; /** @var MemoryCacheBackend */ @@ -31,27 +25,18 @@ class MemoryCacheBackendTest extends TestCase { #[\Override] protected function setUp(): void { parent::setUp(); - - $this->config = $this->createMock(IConfig::class); - $this->cacheFactory = $this->createMock(ICacheFactory::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); $this->cache = $this->createMock(ICache::class); + $this->memoryCache = $this->createInstanceWithMocks(MemoryCacheBackend::class); - $this->cacheFactory + $this->mocks[ICacheFactory::class] ->expects($this->once()) ->method('createDistributed') ->with('OC\Security\RateLimiting\Backend\MemoryCacheBackend') ->willReturn($this->cache); - $this->config->method('getSystemValueBool') + $this->mocks[IConfig::class]->method('getSystemValueBool') ->with('ratelimit.protection.enabled') ->willReturn(true); - - $this->memoryCache = new MemoryCacheBackend( - $this->config, - $this->cacheFactory, - $this->timeFactory - ); } public function testGetAttemptsWithNoAttemptsBefore(): void { @@ -65,7 +50,7 @@ public function testGetAttemptsWithNoAttemptsBefore(): void { } public function testGetAttempts(): void { - $this->timeFactory + $this->mocks[ITimeFactory::class] ->expects($this->once()) ->method('getTime') ->willReturn(210); @@ -86,7 +71,7 @@ public function testGetAttempts(): void { } public function testRegisterAttemptWithNoAttemptsBefore(): void { - $this->timeFactory + $this->mocks[ITimeFactory::class] ->expects($this->once()) ->method('getTime') ->willReturn(123); @@ -108,7 +93,7 @@ public function testRegisterAttemptWithNoAttemptsBefore(): void { } public function testRegisterAttempt(): void { - $this->timeFactory + $this->mocks[ITimeFactory::class] ->expects($this->once()) ->method('getTime') ->willReturn(86); diff --git a/tests/lib/Security/RateLimiting/LimiterTest.php b/tests/lib/Security/RateLimiting/LimiterTest.php index 76a3a3a27a906..731c5ab00e8e9 100644 --- a/tests/lib/Security/RateLimiting/LimiterTest.php +++ b/tests/lib/Security/RateLimiting/LimiterTest.php @@ -14,34 +14,25 @@ use OC\Security\RateLimiting\Limiter; use OCP\IUser; use OCP\Security\RateLimiting\ILimiter; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class LimiterTest extends TestCase { - private IBackend&MockObject $backend; private ILimiter $limiter; - private LoggerInterface $logger; #[\Override] protected function setUp(): void { parent::setUp(); - $this->backend = $this->createMock(IBackend::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->limiter = new Limiter( - $this->backend, - $this->logger, - ); + $this->limiter = $this->createInstanceWithMocks(Limiter::class); } public function testRegisterAnonRequestExceeded(): void { $this->expectException(RateLimitExceededException::class); $this->expectExceptionMessage('Rate limit exceeded'); - $this->backend + $this->mocks[IBackend::class] ->expects($this->once()) ->method('getAttempts') ->with( @@ -49,14 +40,14 @@ public function testRegisterAnonRequestExceeded(): void { '4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47' ) ->willReturn(101); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('info'); $this->limiter->registerAnonRequest('MyIdentifier', 100, 100, '127.0.0.1'); } public function testRegisterAnonRequestSuccess(): void { - $this->backend + $this->mocks[IBackend::class] ->expects($this->once()) ->method('getAttempts') ->with( @@ -64,7 +55,7 @@ public function testRegisterAnonRequestSuccess(): void { '4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47' ) ->willReturn(99); - $this->backend + $this->mocks[IBackend::class] ->expects($this->once()) ->method('registerAttempt') ->with( @@ -72,7 +63,7 @@ public function testRegisterAnonRequestSuccess(): void { '4664f0d9c88dcb7552be47b37bb52ce35977b2e60e1ac13757cf625f31f87050a41f3da064887fa87d49fd042e4c8eb20de8f10464877d3959677ab011b73a47', 100 ); - $this->logger->expects($this->never()) + $this->mocks[LoggerInterface::class]->expects($this->never()) ->method('info'); $this->limiter->registerAnonRequest('MyIdentifier', 100, 100, '127.0.0.1'); @@ -88,7 +79,7 @@ public function testRegisterUserRequestExceeded(): void { ->expects($this->once()) ->method('getUID') ->willReturn('MyUid'); - $this->backend + $this->mocks[IBackend::class] ->expects($this->once()) ->method('getAttempts') ->with( @@ -96,7 +87,7 @@ public function testRegisterUserRequestExceeded(): void { 'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805' ) ->willReturn(101); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('info'); $this->limiter->registerUserRequest('MyIdentifier', 100, 100, $user); @@ -110,7 +101,7 @@ public function testRegisterUserRequestSuccess(): void { ->method('getUID') ->willReturn('MyUid'); - $this->backend + $this->mocks[IBackend::class] ->expects($this->once()) ->method('getAttempts') ->with( @@ -118,7 +109,7 @@ public function testRegisterUserRequestSuccess(): void { 'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805' ) ->willReturn(99); - $this->backend + $this->mocks[IBackend::class] ->expects($this->once()) ->method('registerAttempt') ->with( @@ -126,7 +117,7 @@ public function testRegisterUserRequestSuccess(): void { 'ddb2ec50fa973fd49ecf3d816f677c8095143e944ad10485f30fb3dac85c13a346dace4dae2d0a15af91867320957bfd38a43d9eefbb74fe6919e15119b6d805', 100 ); - $this->logger->expects($this->never()) + $this->mocks[LoggerInterface::class]->expects($this->never()) ->method('info'); $this->limiter->registerUserRequest('MyIdentifier', 100, 100, $user); diff --git a/tests/lib/Security/RemoteHostValidatorTest.php b/tests/lib/Security/RemoteHostValidatorTest.php index e152efeb857ed..c1f09bc9a44e9 100644 --- a/tests/lib/Security/RemoteHostValidatorTest.php +++ b/tests/lib/Security/RemoteHostValidatorTest.php @@ -12,36 +12,16 @@ use OC\Net\HostnameClassifier; use OC\Net\IpAddressClassifier; use OC\Security\RemoteHostValidator; -use OCP\IConfig; -use Psr\Log\LoggerInterface; use Test\TestCase; class RemoteHostValidatorTest extends TestCase { - /** @var IConfig|IConfig&MockObject|MockObject */ - private IConfig $config; - /** @var HostnameClassifier|HostnameClassifier&MockObject|MockObject */ - private HostnameClassifier $hostnameClassifier; - /** @var IpAddressClassifier|IpAddressClassifier&MockObject|MockObject */ - private IpAddressClassifier $ipAddressClassifier; - /** @var MockObject|LoggerInterface|LoggerInterface&MockObject */ - private LoggerInterface $logger; private RemoteHostValidator $validator; #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->hostnameClassifier = $this->createMock(HostnameClassifier::class); - $this->ipAddressClassifier = $this->createMock(IpAddressClassifier::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->validator = new RemoteHostValidator( - $this->config, - $this->hostnameClassifier, - $this->ipAddressClassifier, - $this->logger, - ); + $this->validator = $this->createInstanceWithMocks(RemoteHostValidator::class); } public static function dataValid(): array { @@ -53,11 +33,11 @@ public static function dataValid(): array { #[\PHPUnit\Framework\Attributes\DataProvider('dataValid')] public function testValid(string $host, bool $expected): void { - $this->hostnameClassifier + $this->mocks[HostnameClassifier::class] ->method('isLocalHostname') ->with($host) ->willReturn(false); - $this->ipAddressClassifier + $this->mocks[IpAddressClassifier::class] ->method('isLocalAddress') ->with($host) ->willReturn(false); @@ -69,11 +49,11 @@ public function testValid(string $host, bool $expected): void { public function testLocalHostname(): void { $host = 'localhost'; - $this->hostnameClassifier + $this->mocks[HostnameClassifier::class] ->method('isLocalHostname') ->with($host) ->willReturn(true); - $this->ipAddressClassifier + $this->mocks[IpAddressClassifier::class] ->method('isLocalAddress') ->with($host) ->willReturn(false); @@ -85,11 +65,11 @@ public function testLocalHostname(): void { public function testLocalAddress(): void { $host = '10.0.0.10'; - $this->hostnameClassifier + $this->mocks[HostnameClassifier::class] ->method('isLocalHostname') ->with($host) ->willReturn(false); - $this->ipAddressClassifier + $this->mocks[IpAddressClassifier::class] ->method('isLocalAddress') ->with($host) ->willReturn(true); diff --git a/tests/lib/Security/VerificationToken/VerificationTokenTest.php b/tests/lib/Security/VerificationToken/VerificationTokenTest.php index ed5890afba5a0..1be991169c226 100644 --- a/tests/lib/Security/VerificationToken/VerificationTokenTest.php +++ b/tests/lib/Security/VerificationToken/VerificationTokenTest.php @@ -11,46 +11,22 @@ use OC\Security\VerificationToken\VerificationToken; use OCP\AppFramework\Utility\ITimeFactory; -use OCP\BackgroundJob\IJobList; use OCP\IConfig; use OCP\IUser; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; use OCP\Security\VerificationToken\InvalidTokenException; -use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class VerificationTokenTest extends TestCase { /** @var VerificationToken */ protected $token; - /** @var IConfig|MockObject */ - protected $config; - /** @var ISecureRandom|MockObject */ - protected $secureRandom; - /** @var ICrypto|MockObject */ - protected $crypto; - /** @var ITimeFactory|MockObject */ - protected $timeFactory; - /** @var IJobList|MockObject */ - protected $jobList; #[\Override] protected function setUp(): void { parent::setUp(); - $this->config = $this->createMock(IConfig::class); - $this->crypto = $this->createMock(ICrypto::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); - $this->secureRandom = $this->createMock(ISecureRandom::class); - $this->jobList = $this->createMock(IJobList::class); - - $this->token = new VerificationToken( - $this->config, - $this->crypto, - $this->timeFactory, - $this->secureRandom, - $this->jobList - ); + $this->token = $this->createInstanceWithMocks(VerificationToken::class); } public function testTokenUserUnknown(): void { @@ -95,16 +71,16 @@ public function testTokenDecryptionError(): void { ->method('getUID') ->willReturn('alice'); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('getUserValue') ->with('alice', 'core', 'fingerprintToken', null) ->willReturn('encryptedToken'); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->with('secret') ->willReturn('357111317'); - $this->crypto->method('decrypt') + $this->mocks[ICrypto::class]->method('decrypt') ->with('encryptedToken', 'foobar' . '357111317') ->willThrowException(new \Exception('decryption failed')); @@ -122,16 +98,16 @@ public function testTokenInvalidFormat(): void { ->method('getUID') ->willReturn('alice'); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('getUserValue') ->with('alice', 'core', 'fingerprintToken', null) ->willReturn('encryptedToken'); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->with('secret') ->willReturn('357111317'); - $this->crypto->method('decrypt') + $this->mocks[ICrypto::class]->method('decrypt') ->with('encryptedToken', 'foobar' . '357111317') ->willReturn('decrypted^nonsense'); @@ -152,20 +128,20 @@ public function testTokenExpired(): void { ->method('getLastLogin') ->willReturn(604803); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('getUserValue') ->with('alice', 'core', 'fingerprintToken', null) ->willReturn('encryptedToken'); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->with('secret') ->willReturn('357111317'); - $this->crypto->method('decrypt') + $this->mocks[ICrypto::class]->method('decrypt') ->with('encryptedToken', 'foobar' . '357111317') ->willReturn('604800:mY70K3n'); - $this->timeFactory->expects($this->any()) + $this->mocks[ITimeFactory::class]->expects($this->any()) ->method('getTime') ->willReturn(604800 * 3); @@ -186,20 +162,20 @@ public function testTokenExpiredByLogin(): void { ->method('getLastLogin') ->willReturn(604803); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('getUserValue') ->with('alice', 'core', 'fingerprintToken', null) ->willReturn('encryptedToken'); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->with('secret') ->willReturn('357111317'); - $this->crypto->method('decrypt') + $this->mocks[ICrypto::class]->method('decrypt') ->with('encryptedToken', 'foobar' . '357111317') ->willReturn('604800:mY70K3n'); - $this->timeFactory->expects($this->any()) + $this->mocks[ITimeFactory::class]->expects($this->any()) ->method('getTime') ->willReturn(604801); @@ -220,20 +196,20 @@ public function testTokenMismatch(): void { ->method('getLastLogin') ->willReturn(604703); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('getUserValue') ->with('alice', 'core', 'fingerprintToken', null) ->willReturn('encryptedToken'); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->with('secret') ->willReturn('357111317'); - $this->crypto->method('decrypt') + $this->mocks[ICrypto::class]->method('decrypt') ->with('encryptedToken', 'foobar' . '357111317') ->willReturn('604802:mY70K3n'); - $this->timeFactory->expects($this->any()) + $this->mocks[ITimeFactory::class]->expects($this->any()) ->method('getTime') ->willReturn(604801); @@ -254,20 +230,20 @@ public function testTokenSuccess(): void { ->method('getLastLogin') ->willReturn(604703); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('getUserValue') ->with('alice', 'core', 'fingerprintToken', null) ->willReturn('encryptedToken'); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueString') ->with('secret') ->willReturn('357111317'); - $this->crypto->method('decrypt') + $this->mocks[ICrypto::class]->method('decrypt') ->with('encryptedToken', 'foobar' . '357111317') ->willReturn('604802:barfoo'); - $this->timeFactory->expects($this->any()) + $this->mocks[ITimeFactory::class]->expects($this->any()) ->method('getTime') ->willReturn(604801); @@ -280,13 +256,13 @@ public function testCreate(): void { ->method('getUID') ->willReturn('alice'); - $this->secureRandom->expects($this->atLeastOnce()) + $this->mocks[ISecureRandom::class]->expects($this->atLeastOnce()) ->method('generate') ->willReturn('barfoo'); - $this->crypto->expects($this->atLeastOnce()) + $this->mocks[ICrypto::class]->expects($this->atLeastOnce()) ->method('encrypt') ->willReturn('encryptedToken'); - $this->config->expects($this->atLeastOnce()) + $this->mocks[IConfig::class]->expects($this->atLeastOnce()) ->method('setUserValue') ->with('alice', 'core', 'fingerprintToken', 'encryptedToken'); diff --git a/tests/lib/Settings/DeclarativeManagerTest.php b/tests/lib/Settings/DeclarativeManagerTest.php index ea29eee635035..b4b25daa548f3 100644 --- a/tests/lib/Settings/DeclarativeManagerTest.php +++ b/tests/lib/Settings/DeclarativeManagerTest.php @@ -18,14 +18,12 @@ use OCP\IConfig; use OCP\IGroupManager; use OCP\IUser; -use OCP\Security\ICrypto; use OCP\Settings\DeclarativeSettingsTypes; use OCP\Settings\Events\DeclarativeSettingsSetValueEvent; use OCP\Settings\IDeclarativeManager; use OCP\Settings\IDeclarativeSettingsForm; use OCP\Settings\IDeclarativeSettingsFormWithHandlers; use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; use Test\TestCase; class DeclarativeManagerTest extends TestCase { @@ -33,27 +31,6 @@ class DeclarativeManagerTest extends TestCase { /** @var IDeclarativeManager|MockObject */ private $declarativeManager; - /** @var IEventDispatcher|MockObject */ - private $eventDispatcher; - - /** @var IGroupManager|MockObject */ - private $groupManager; - - /** @var Coordinator|MockObject */ - private $coordinator; - - /** @var IConfig|MockObject */ - private $config; - - /** @var IAppConfig|MockObject */ - private $appConfig; - - /** @var LoggerInterface|MockObject */ - private $logger; - - /** @var ICrypto|MockObject */ - private $crypto; - /** @var IUser|MockObject */ private $user; @@ -258,23 +235,7 @@ class DeclarativeManagerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->groupManager = $this->createMock(IGroupManager::class); - $this->coordinator = $this->createMock(Coordinator::class); - $this->config = $this->createMock(IConfig::class); - $this->appConfig = $this->createMock(IAppConfig::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->crypto = $this->createMock(ICrypto::class); - - $this->declarativeManager = new DeclarativeManager( - $this->eventDispatcher, - $this->groupManager, - $this->coordinator, - $this->config, - $this->appConfig, - $this->logger, - $this->crypto, - ); + $this->declarativeManager = $this->createInstanceWithMocks(DeclarativeManager::class); $this->user = $this->createMock(IUser::class); $this->user->expects($this->any()) @@ -286,7 +247,7 @@ protected function setUp(): void { ->method('getUID') ->willReturn('admin_test_user'); - $this->groupManager->expects($this->any()) + $this->mocks[IGroupManager::class]->expects($this->any()) ->method('isAdmin') ->willReturnCallback(function ($userId) { return $userId === 'admin_test_user'; @@ -437,7 +398,7 @@ public function testGetFormsWithDefaultValues(): void { $schema = self::validSchemaAllFields; $this->declarativeManager->registerSchema($app, $schema); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getAppValue') ->willReturnCallback(fn ($app, $configkey, $default) => $default); @@ -479,7 +440,7 @@ public function testGetFormsWithDefaultValuesJson(): void { $this->declarativeManager->registerSchema($app, $schema); // config->getUserValue() should be called with json encoded default value - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getUserValue') ->with($this->adminUser->getUID(), $app, 'test_field_json', json_encode($schema['fields'][0]['default'])) ->willReturn(json_encode($schema['fields'][0]['default'])); @@ -500,7 +461,7 @@ public function testSetInternalValue(): void { $this->declarativeManager->registerSchema($app, $schema); self::$testSetInternalValueAfterChange = false; - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getAppValue') ->willReturnCallback(function ($app, $configkey, $default) { if ($configkey === 'some_real_setting' && self::$testSetInternalValueAfterChange) { @@ -509,7 +470,7 @@ public function testSetInternalValue(): void { return $default; }); - $this->appConfig->expects($this->once()) + $this->mocks[IAppConfig::class]->expects($this->once()) ->method('setValueString') ->with($app, 'some_real_setting', '120m'); @@ -545,7 +506,7 @@ public function testSetExternalValue(): void { '120m' ); - $this->eventDispatcher->expects($this->once()) + $this->mocks[IEventDispatcher::class]->expects($this->once()) ->method('dispatchTyped') ->with($setDeclarativeSettingsValueEvent); $this->declarativeManager->setValue($this->adminUser, $app, $schema['id'], 'some_real_setting', '120m'); @@ -591,13 +552,13 @@ public function testSetValueWithHandler(): void { ->method('getDeclarativeSettings') ->willReturn([new ServiceRegistration('testing', 'OCA\\Testing\\Settings\\DeclarativeForm')]); - $this->coordinator->expects(self::atLeastOnce()) + $this->mocks[Coordinator::class]->expects(self::atLeastOnce()) ->method('getRegistrationContext') ->willReturn($context); $this->declarativeManager->loadSchemas(); - $this->eventDispatcher->expects(self::never()) + $this->mocks[IEventDispatcher::class]->expects(self::never()) ->method('dispatchTyped'); $this->declarativeManager->setValue($this->adminUser, 'testing', 'test_form_1', 'test_field_2', 'some password'); @@ -625,13 +586,13 @@ public function testGetValueWithHandler(): void { ->method('getDeclarativeSettings') ->willReturn([new ServiceRegistration('testing', 'OCA\\Testing\\Settings\\DeclarativeForm')]); - $this->coordinator->expects(self::atLeastOnce()) + $this->mocks[Coordinator::class]->expects(self::atLeastOnce()) ->method('getRegistrationContext') ->willReturn($context); $this->declarativeManager->loadSchemas(); - $this->eventDispatcher->expects(self::never()) + $this->mocks[IEventDispatcher::class]->expects(self::never()) ->method('dispatchTyped'); $password = $this->invokePrivate($this->declarativeManager, 'getValue', [$this->adminUser, 'testing', 'test_form_1', 'test_field_2']); diff --git a/tests/lib/Settings/ManagerTest.php b/tests/lib/Settings/ManagerTest.php index af00452d765c6..b1edeaac4c0d1 100644 --- a/tests/lib/Settings/ManagerTest.php +++ b/tests/lib/Settings/ManagerTest.php @@ -7,67 +7,36 @@ namespace OC\Settings\Tests\AppInfo; -use OC\Settings\AuthorizedGroupMapper; use OC\Settings\Manager; use OCA\WorkflowEngine\Settings\Section; use OCP\App\IAppManager; -use OCP\Group\ISubAdmin; -use OCP\IGroupManager; use OCP\IL10N; -use OCP\IURLGenerator; use OCP\L10N\IFactory; use OCP\Server; use OCP\Settings\ISettings; use OCP\Settings\ISubAdminSettings; use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; -use Psr\Log\LoggerInterface; use Test\TestCase; class ManagerTest extends TestCase { - private LoggerInterface&MockObject $logger; private IL10N&MockObject $l10n; - private IFactory&MockObject $l10nFactory; - private IURLGenerator&MockObject $url; - private ContainerInterface&MockObject $container; - private AuthorizedGroupMapper&MockObject $mapper; - private IGroupManager&MockObject $groupManager; - private ISubAdmin&MockObject $subAdmin; - private IAppManager&MockObject $appManager; private Manager $manager; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->logger = $this->createMock(LoggerInterface::class); $this->l10n = $this->createMock(IL10N::class); - $this->l10nFactory = $this->createMock(IFactory::class); - $this->url = $this->createMock(IURLGenerator::class); - $this->container = $this->createMock(ContainerInterface::class); - $this->mapper = $this->createMock(AuthorizedGroupMapper::class); - $this->groupManager = $this->createMock(IGroupManager::class); - $this->subAdmin = $this->createMock(ISubAdmin::class); - $this->appManager = $this->createMock(IAppManager::class); - - $this->manager = new Manager( - $this->logger, - $this->l10nFactory, - $this->url, - $this->container, - $this->mapper, - $this->groupManager, - $this->subAdmin, - $this->appManager, - ); + + $this->manager = $this->createInstanceWithMocks(Manager::class); } public function testGetAdminSections(): void { $this->manager->registerSection('admin', Section::class); $section = Server::get(Section::class); - $this->container->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with(Section::class) ->willReturn($section); @@ -80,7 +49,7 @@ public function testGetPersonalSections(): void { $this->manager->registerSection('personal', Section::class); $section = Server::get(Section::class); - $this->container->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with(Section::class) ->willReturn($section); @@ -94,7 +63,7 @@ public function testGetAdminSectionsEmptySection(): void { } public function testGetPersonalSectionsEmptySection(): void { - $this->l10nFactory + $this->mocks[IFactory::class] ->expects($this->once()) ->method('get') ->with('lib') @@ -113,7 +82,7 @@ public function testGetAdminSettings(): void { ->willReturn(13); $section->method('getSection') ->willReturn('sharing'); - $this->container->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with('myAdminClass') ->willReturn($section); @@ -131,7 +100,7 @@ public function testGetAdminSettingsAsSubAdmin(): void { ->willReturn(13); $section->method('getSection') ->willReturn('sharing'); - $this->container->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with('myAdminClass') ->willReturn($section); @@ -147,7 +116,7 @@ public function testGetSubAdminSettingsAsSubAdmin(): void { ->willReturn(13); $section->method('getSection') ->willReturn('sharing'); - $this->container->expects($this->once()) + $this->mocks[ContainerInterface::class]->expects($this->once()) ->method('get') ->with('mySubAdminClass') ->willReturn($section); @@ -175,7 +144,7 @@ public function testGetPersonalSettings(): void { $this->manager->registerSetting('personal', 'section1'); $this->manager->registerSetting('personal', 'section2'); - $this->container->expects($this->exactly(2)) + $this->mocks[ContainerInterface::class]->expects($this->exactly(2)) ->method('get') ->willReturnMap([ ['section1', $section], @@ -200,11 +169,11 @@ public function testGetPersonalSettingsHidesSettingsOfAppsNotEnabledForUser(): v $this->manager->registerSetting('personal', 'visibleClass', 'enabled_app'); $this->manager->registerSetting('personal', 'hiddenClass', 'restricted_app'); - $this->appManager->method('isEnabledForUser') + $this->mocks[IAppManager::class]->method('isEnabledForUser') ->willReturnCallback(static fn (string $appId): bool => $appId === 'enabled_app'); // The settings of the app the user has no access to are never instantiated. - $this->container->expects($this->once()) + $this->mocks[ContainerInterface::class]->expects($this->once()) ->method('get') ->with('visibleClass') ->willReturn($visible); @@ -215,7 +184,7 @@ public function testGetPersonalSettingsHidesSettingsOfAppsNotEnabledForUser(): v } public function testGetPersonalSectionsHidesSectionsOfAppsNotEnabledForUser(): void { - $this->l10nFactory->method('get') + $this->mocks[IFactory::class]->method('get') ->with('lib') ->willReturn($this->l10n); $this->l10n->method('t') @@ -223,11 +192,11 @@ public function testGetPersonalSectionsHidesSectionsOfAppsNotEnabledForUser(): v $this->manager->registerSection('personal', Section::class, 'restricted_app'); - $this->appManager->method('isEnabledForUser') + $this->mocks[IAppManager::class]->method('isEnabledForUser') ->with('restricted_app') ->willReturn(false); - $this->container->expects($this->never()) + $this->mocks[ContainerInterface::class]->expects($this->never()) ->method('get'); $this->assertEquals([], $this->manager->getPersonalSections()); @@ -243,9 +212,9 @@ public function testGetAdminSettingsAreNotHiddenForAppsNotEnabledForUser(): void $this->manager->registerSetting('admin', 'myAdminClass', 'restricted_app'); - $this->appManager->expects($this->never()) + $this->mocks[IAppManager::class]->expects($this->never()) ->method('isEnabledForUser'); - $this->container->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with('myAdminClass') ->willReturn($setting); @@ -255,7 +224,7 @@ public function testGetAdminSettingsAreNotHiddenForAppsNotEnabledForUser(): void } public function testSameSectionAsPersonalAndAdmin(): void { - $this->l10nFactory + $this->mocks[IFactory::class] ->expects($this->once()) ->method('get') ->with('lib') @@ -269,7 +238,7 @@ public function testSameSectionAsPersonalAndAdmin(): void { $this->manager->registerSection('admin', Section::class); $section = Server::get(Section::class); - $this->container->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with(Section::class) ->willReturn($section); diff --git a/tests/lib/Share20/ShareHelperTest.php b/tests/lib/Share20/ShareHelperTest.php index 2a07a83dc143e..1a15b3b67f62b 100644 --- a/tests/lib/Share20/ShareHelperTest.php +++ b/tests/lib/Share20/ShareHelperTest.php @@ -14,9 +14,6 @@ use Test\TestCase; class ShareHelperTest extends TestCase { - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $manager; - /** @var ShareHelper */ private $helper; @@ -24,9 +21,7 @@ class ShareHelperTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->manager = $this->createMock(IManager::class); - - $this->helper = new ShareHelper($this->manager); + $this->helper = $this->createInstanceWithMocks(ShareHelper::class); } public static function dataGetPathsForAccessList(): array { @@ -52,7 +47,7 @@ public static function dataGetPathsForAccessList(): array { #[\PHPUnit\Framework\Attributes\DataProvider('dataGetPathsForAccessList')] public function testGetPathsForAccessList(array $userList, array $userMap, $resolveUsers, array $remoteList, array $remoteMap, $resolveRemotes, array $expected): void { - $this->manager->expects($this->once()) + $this->mocks[IManager::class]->expects($this->once()) ->method('getAccessList') ->willReturn([ 'users' => $userList, @@ -63,7 +58,7 @@ public function testGetPathsForAccessList(array $userList, array $userMap, $reso $node = $this->createMock(Node::class); /** @var ShareHelper|\PHPUnit\Framework\MockObject\MockObject $helper */ $helper = $this->getMockBuilder(ShareHelper::class) - ->setConstructorArgs([$this->manager]) + ->setConstructorArgs([$this->mocks[IManager::class]]) ->onlyMethods(['getPathsForUsers', 'getPathsForRemotes']) ->getMock(); diff --git a/tests/lib/Share20/ShareTest.php b/tests/lib/Share20/ShareTest.php index 23f5a70e2a475..f7936e0883d01 100644 --- a/tests/lib/Share20/ShareTest.php +++ b/tests/lib/Share20/ShareTest.php @@ -9,11 +9,8 @@ namespace Test\Share20; use OC\Share20\Share; -use OCP\Files\IRootFolder; -use OCP\IUserManager; use OCP\Share\Exceptions\IllegalIDChangeException; use OCP\Share\IShare; -use PHPUnit\Framework\MockObject\MockObject; /** * Class ShareTest @@ -21,17 +18,12 @@ * @package Test\Share20 */ class ShareTest extends \Test\TestCase { - protected IRootFolder&MockObject $rootFolder; - protected IUserManager&MockObject $userManager; protected IShare $share; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->rootFolder = $this->createMock(IRootFolder::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->share = new Share($this->rootFolder, $this->userManager); + $this->share = $this->createInstanceWithMocks(Share::class); } public function testSetIdInt(): void { diff --git a/tests/lib/Support/Subscription/RegistryTest.php b/tests/lib/Support/Subscription/RegistryTest.php index 9bf39bd90be1b..73c87a0d9e8c4 100644 --- a/tests/lib/Support/Subscription/RegistryTest.php +++ b/tests/lib/Support/Subscription/RegistryTest.php @@ -18,35 +18,17 @@ use OCP\Support\Subscription\ISupportedApps; use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; -use Psr\Log\LoggerInterface; use Test\TestCase; class RegistryTest extends TestCase { private Registry $registry; - private MockObject&IConfig $config; - private MockObject&ContainerInterface $serverContainer; - private MockObject&IUserManager $userManager; - private MockObject&IGroupManager $groupManager; - private MockObject&LoggerInterface $logger; private MockObject&IManager $notificationManager; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->config = $this->createMock(IConfig::class); - $this->serverContainer = $this->createMock(ContainerInterface::class); - $this->userManager = $this->createMock(IUserManager::class); - $this->groupManager = $this->createMock(IGroupManager::class); - $this->logger = $this->createMock(LoggerInterface::class); $this->notificationManager = $this->createMock(IManager::class); - $this->registry = new Registry( - $this->config, - $this->serverContainer, - $this->userManager, - $this->groupManager, - $this->logger - ); + $this->registry = $this->createInstanceWithMocks(Registry::class); } /** @@ -86,7 +68,7 @@ public function testDelegateHasValidSubscription(): void { public function testDelegateHasValidSubscriptionConfig(): void { /* @var ISubscription|\PHPUnit\Framework\MockObject\MockObject $subscription */ - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueBool') ->with('has_valid_subscription') ->willReturn(true); @@ -117,7 +99,7 @@ public function testDelegateGetSupportedApps(): void { } public function testSubscriptionService(): void { - $this->serverContainer->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with(DummySubscription::class) ->willReturn(new DummySubscription(true, false, false)); $this->registry->registerService(DummySubscription::class); @@ -140,7 +122,7 @@ public function testDelegateIsHardUserLimitReached(): void { $dummyGroup->expects($this->once()) ->method('getUsers') ->willReturn([]); - $this->groupManager->expects($this->once()) + $this->mocks[IGroupManager::class]->expects($this->once()) ->method('get') ->willReturn($dummyGroup); @@ -148,7 +130,7 @@ public function testDelegateIsHardUserLimitReached(): void { } public function testDelegateIsHardUserLimitReachedWithoutSupportApp(): void { - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueBool') ->with('one-click-instance') ->willReturn(false); @@ -168,19 +150,19 @@ public static function dataForUserLimitCheck(): array { #[\PHPUnit\Framework\Attributes\DataProvider('dataForUserLimitCheck')] public function testDelegateIsHardUserLimitReachedWithoutSupportAppAndUserCount($userLimit, $userCount, $disabledUsers, $expectedResult): void { - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueBool') ->with('one-click-instance') ->willReturn(true); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getSystemValueInt') ->with('one-click-instance.user-limit') ->willReturn($userLimit); - $this->config->expects($this->once()) + $this->mocks[IConfig::class]->expects($this->once()) ->method('getUsersForUserValue') ->with('core', 'enabled', 'false') ->willReturn(array_fill(0, $disabledUsers, '')); - $this->userManager->expects($this->once()) + $this->mocks[IUserManager::class]->expects($this->once()) ->method('countUsersTotal') ->willReturn($userCount); @@ -189,7 +171,7 @@ public function testDelegateIsHardUserLimitReachedWithoutSupportAppAndUserCount( $dummyGroup->expects($this->once()) ->method('getUsers') ->willReturn([]); - $this->groupManager->expects($this->once()) + $this->mocks[IGroupManager::class]->expects($this->once()) ->method('get') ->willReturn($dummyGroup); } diff --git a/tests/lib/SystemReport/SystemReportManagerTest.php b/tests/lib/SystemReport/SystemReportManagerTest.php index acb788f713a79..0bbd32668e1eb 100644 --- a/tests/lib/SystemReport/SystemReportManagerTest.php +++ b/tests/lib/SystemReport/SystemReportManagerTest.php @@ -14,33 +14,18 @@ use OC\AppFramework\Bootstrap\ServiceRegistration; use OC\SystemReport\SystemReportManager; use OCP\SystemReport\ISystemReportSection; -use PHPUnit\Framework\MockObject\MockObject; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; use Test\TestCase; final class SystemReportManagerTest extends TestCase { - private Coordinator&MockObject $coordinator; - - private ContainerInterface&MockObject $container; - - private LoggerInterface&MockObject $logger; - private SystemReportManager $manager; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->coordinator = $this->createMock(Coordinator::class); - $this->container = $this->createMock(ContainerInterface::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->manager = new SystemReportManager( - $this->coordinator, - $this->container, - $this->logger, - ); + $this->manager = $this->createInstanceWithMocks(SystemReportManager::class); } /** @@ -52,7 +37,7 @@ private function withRegisteredSections(array $registrations): void { ->method('getSystemReportSections') ->willReturn($registrations); - $this->coordinator->expects(self::atLeastOnce()) + $this->mocks[Coordinator::class]->expects(self::atLeastOnce()) ->method('getRegistrationContext') ->willReturn($context); } @@ -69,7 +54,7 @@ public function testGetSectionsResolvesAndReturnsRegisteredSections(): void { ->method('getDetails') ->willReturn([]); - $this->container->expects(self::once()) + $this->mocks[ContainerInterface::class]->expects(self::once()) ->method('get') ->with($section::class) ->willReturn($section); @@ -86,7 +71,7 @@ public function testGetSectionsSkipsSectionThrowingDuringCollection(): void { $section->method('getDetails') ->willThrowException(new \RuntimeException('boom')); - $this->container->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with($section::class) ->willReturn($section); @@ -94,14 +79,14 @@ public function testGetSectionsSkipsSectionThrowingDuringCollection(): void { new ServiceRegistration('testing', $section::class), ]); - $this->logger->expects(self::once()) + $this->mocks[LoggerInterface::class]->expects(self::once()) ->method('error'); $this->assertSame([], $this->manager->getSections()); } public function testGetSectionsSkipsUnresolvableClass(): void { - $this->container->method('get') + $this->mocks[ContainerInterface::class]->method('get') ->with(\stdClass::class) ->willThrowException($this->createStub(NotFoundExceptionInterface::class)); @@ -109,7 +94,7 @@ public function testGetSectionsSkipsUnresolvableClass(): void { new ServiceRegistration('testing', \stdClass::class), ]); - $this->logger->expects(self::once()) + $this->mocks[LoggerInterface::class]->expects(self::once()) ->method('error'); $this->assertSame([], $this->manager->getSections()); diff --git a/tests/lib/Talk/BrokerTest.php b/tests/lib/Talk/BrokerTest.php index 8fdf2f50f1ae3..3f393aea859af 100644 --- a/tests/lib/Talk/BrokerTest.php +++ b/tests/lib/Talk/BrokerTest.php @@ -23,27 +23,13 @@ use Test\TestCase; class BrokerTest extends TestCase { - private Coordinator $coordinator; - - private ContainerInterface $container; - - private LoggerInterface $logger; - private Broker $broker; #[\Override] protected function setUp(): void { parent::setUp(); - $this->coordinator = $this->createMock(Coordinator::class); - $this->container = $this->createMock(ContainerInterface::class); - $this->logger = $this->createMock(LoggerInterface::class); - - $this->broker = new Broker( - $this->coordinator, - $this->container, - $this->logger, - ); + $this->broker = $this->createInstanceWithMocks(Broker::class); } public function testHasNoBackendCalledTooEarly(): void { @@ -53,7 +39,7 @@ public function testHasNoBackendCalledTooEarly(): void { } public function testHasNoBackend(): void { - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($this->createMock(RegistrationContext::class)); @@ -65,16 +51,16 @@ public function testHasNoBackend(): void { public function testHasFaultyBackend(): void { $fakeTalkServiceClass = '\\OCA\\Spreed\\TalkBackend'; $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $registrationContext->expects($this->once()) ->method('getTalkBackendRegistration') ->willReturn(new ServiceRegistration('spreed', $fakeTalkServiceClass)); - $this->container->expects($this->once()) + $this->mocks[ContainerInterface::class]->expects($this->once()) ->method('get') ->willThrowException(new QueryException()); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('error'); self::assertFalse( @@ -85,14 +71,14 @@ public function testHasFaultyBackend(): void { public function testHasBackend(): void { $fakeTalkServiceClass = '\\OCA\\Spreed\\TalkBackend'; $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $registrationContext->expects($this->once()) ->method('getTalkBackendRegistration') ->willReturn(new ServiceRegistration('spreed', $fakeTalkServiceClass)); $talkService = $this->createMock(ITalkBackend::class); - $this->container->expects($this->once()) + $this->mocks[ContainerInterface::class]->expects($this->once()) ->method('get') ->with($fakeTalkServiceClass) ->willReturn($talkService); @@ -111,14 +97,14 @@ public function testNewConversationOptions(): void { public function testCreateConversation(): void { $fakeTalkServiceClass = '\\OCA\\Spreed\\TalkBackend'; $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $registrationContext->expects($this->once()) ->method('getTalkBackendRegistration') ->willReturn(new ServiceRegistration('spreed', $fakeTalkServiceClass)); $talkService = $this->createMock(ITalkBackend::class); - $this->container->expects($this->once()) + $this->mocks[ContainerInterface::class]->expects($this->once()) ->method('get') ->with($fakeTalkServiceClass) ->willReturn($talkService); @@ -135,7 +121,7 @@ public function testCreateConversation(): void { } public function testIsEnabledForUserNoBackend(): void { - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($this->createMock(RegistrationContext::class)); @@ -155,14 +141,14 @@ public static function dataIsEnabledForUser(): array { public function testIsEnabledForUser(bool $enabled): void { $fakeTalkServiceClass = '\\OCA\\Spreed\\TalkBackend'; $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $registrationContext->expects($this->once()) ->method('getTalkBackendRegistration') ->willReturn(new ServiceRegistration('spreed', $fakeTalkServiceClass)); $talkService = $this->createMock(ITalkBackend::class); - $this->container->expects($this->once()) + $this->mocks[ContainerInterface::class]->expects($this->once()) ->method('get') ->with($fakeTalkServiceClass) ->willReturn($talkService); @@ -177,7 +163,7 @@ public function testIsEnabledForUser(bool $enabled): void { } public function testIsAllowedToCreateConversationsNoBackend(): void { - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($this->createMock(RegistrationContext::class)); @@ -189,14 +175,14 @@ public function testIsAllowedToCreateConversationsNoBackend(): void { public function testIsAllowedToCreateConversationsBackendDisabled(): void { $fakeTalkServiceClass = '\\OCA\\Spreed\\TalkBackend'; $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $registrationContext->expects($this->once()) ->method('getTalkBackendRegistration') ->willReturn(new ServiceRegistration('spreed', $fakeTalkServiceClass)); $talkService = $this->createMock(ITalkBackend::class); - $this->container->expects($this->once()) + $this->mocks[ContainerInterface::class]->expects($this->once()) ->method('get') ->with($fakeTalkServiceClass) ->willReturn($talkService); @@ -222,14 +208,14 @@ public static function dataIsAllowedToCreateConversations(): array { public function testIsAllowedToCreateConversations(bool $allowed): void { $fakeTalkServiceClass = '\\OCA\\Spreed\\TalkBackend'; $registrationContext = $this->createMock(RegistrationContext::class); - $this->coordinator->expects($this->once()) + $this->mocks[Coordinator::class]->expects($this->once()) ->method('getRegistrationContext') ->willReturn($registrationContext); $registrationContext->expects($this->once()) ->method('getTalkBackendRegistration') ->willReturn(new ServiceRegistration('spreed', $fakeTalkServiceClass)); $talkService = $this->createMock(ITalkBackend::class); - $this->container->expects($this->once()) + $this->mocks[ContainerInterface::class]->expects($this->once()) ->method('get') ->with($fakeTalkServiceClass) ->willReturn($talkService); diff --git a/tests/lib/Template/JSCombinerTest.php b/tests/lib/Template/JSCombinerTest.php index d3fd8444e115f..bdfbb30c8df86 100644 --- a/tests/lib/Template/JSCombinerTest.php +++ b/tests/lib/Template/JSCombinerTest.php @@ -25,39 +25,22 @@ use Psr\Log\LoggerInterface; class JSCombinerTest extends \Test\TestCase { - private IAppData&MockObject $appData; - private IURLGenerator&MockObject $urlGenerator; - private IConfig&MockObject $config; private ICache&MockObject $depsCache; - private LoggerInterface&MockObject $logger; - private ICacheFactory&MockObject $cacheFactory; private JSCombiner $jsCombiner; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->appData = $this->createMock(IAppData::class); - $this->urlGenerator = $this->createMock(IURLGenerator::class); - $this->config = $this->createMock(IConfig::class); - $this->cacheFactory = $this->createMock(ICacheFactory::class); $this->depsCache = $this->createMock(ICache::class); - $this->cacheFactory->expects($this->atLeastOnce()) + $this->jsCombiner = $this->createInstanceWithMocks(JSCombiner::class); + $this->mocks[ICacheFactory::class]->expects($this->atLeastOnce()) ->method('createDistributed') ->willReturn($this->depsCache); - $this->logger = $this->createMock(LoggerInterface::class); - $this->jsCombiner = new JSCombiner( - $this->appData, - $this->urlGenerator, - $this->cacheFactory, - $this->config, - $this->logger - ); } public function testProcessDebugMode(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->once()) ->method('getSystemValueBool') ->with('debug') @@ -68,7 +51,7 @@ public function testProcessDebugMode(): void { } public function testProcessNotInstalled(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueBool') ->willReturnMap([ @@ -81,7 +64,7 @@ public function testProcessNotInstalled(): void { } public function testProcessUncachedFileNoAppDataFolder(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueBool') ->willReturnMap([ @@ -89,8 +72,8 @@ public function testProcessUncachedFileNoAppDataFolder(): void { ['installed', true], ]); $folder = $this->createMock(ISimpleFolder::class); - $this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willThrowException(new NotFoundException()); - $this->appData->expects($this->once())->method('newFolder')->with('awesomeapp')->willReturn($folder); + $this->mocks[IAppData::class]->expects($this->once())->method('getFolder')->with('awesomeapp')->willThrowException(new NotFoundException()); + $this->mocks[IAppData::class]->expects($this->once())->method('newFolder')->with('awesomeapp')->willReturn($folder); $file = $this->createMock(ISimpleFile::class); $gzfile = $this->createMock(ISimpleFile::class); @@ -117,7 +100,7 @@ public function testProcessUncachedFileNoAppDataFolder(): void { } public function testProcessUncachedFile(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueBool') ->willReturnMap([ @@ -125,7 +108,7 @@ public function testProcessUncachedFile(): void { ['installed', true], ]); $folder = $this->createMock(ISimpleFolder::class); - $this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willReturn($folder); + $this->mocks[IAppData::class]->expects($this->once())->method('getFolder')->with('awesomeapp')->willReturn($folder); $file = $this->createMock(ISimpleFile::class); $fileDeps = $this->createMock(ISimpleFile::class); $gzfile = $this->createMock(ISimpleFile::class); @@ -151,7 +134,7 @@ public function testProcessUncachedFile(): void { } public function testProcessCachedFile(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueBool') ->willReturnMap([ @@ -159,7 +142,7 @@ public function testProcessCachedFile(): void { ['installed', true], ]); $folder = $this->createMock(ISimpleFolder::class); - $this->appData->expects($this->once())->method('getFolder')->with('awesomeapp')->willReturn($folder); + $this->mocks[IAppData::class]->expects($this->once())->method('getFolder')->with('awesomeapp')->willReturn($folder); $file = $this->createMock(ISimpleFile::class); $fileDeps = $this->createMock(ISimpleFile::class); @@ -188,7 +171,7 @@ public function testProcessCachedFile(): void { } public function testProcessCachedFileMemcache(): void { - $this->config + $this->mocks[IConfig::class] ->expects($this->exactly(2)) ->method('getSystemValueBool') ->willReturnMap([ @@ -196,7 +179,7 @@ public function testProcessCachedFileMemcache(): void { ['installed', true], ]); $folder = $this->createMock(ISimpleFolder::class); - $this->appData->expects($this->once()) + $this->mocks[IAppData::class]->expects($this->once()) ->method('getFolder') ->with('awesomeapp') ->willReturn($folder); @@ -293,7 +276,7 @@ public function testIsCachedWithoutContent(): void { $file->expects($this->once()) ->method('getContent') ->willReturn(''); - $this->logger->expects($this->once()) + $this->mocks[LoggerInterface::class]->expects($this->once()) ->method('info') ->with('JSCombiner: deps file empty: combine.js.deps'); $actual = self::invokePrivate($this->jsCombiner, 'isCached', [$fileName, $folder]); @@ -474,7 +457,7 @@ public static function dataGetCachedSCSS(): array { */ #[\PHPUnit\Framework\Attributes\DataProvider('dataGetCachedSCSS')] public function testGetCachedSCSS($appName, $fileName, $result): void { - $this->urlGenerator->expects($this->once()) + $this->mocks[IURLGenerator::class]->expects($this->once()) ->method('linkToRoute') ->with('core.Js.getJs', [ 'fileName' => 'foo.js', @@ -521,12 +504,12 @@ public function testResetCache(): void { ->willReturn([$file]); $cache = $this->createMock(ICache::class); - $this->cacheFactory->expects($this->once()) + $this->mocks[ICacheFactory::class]->expects($this->once()) ->method('createDistributed') ->willReturn($cache); $cache->expects($this->never()) ->method('clear'); - $this->appData->expects($this->once()) + $this->mocks[IAppData::class]->expects($this->once()) ->method('getDirectoryListing') ->willReturn([$folder]); diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index 59b00d43af024..bf2e8e5795b31 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -35,6 +35,7 @@ use OCP\IL10N; use OCP\IUserManager; use OCP\IUserSession; +use OCP\L10N\IFactory; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; use OCP\Security\ISecureRandom; @@ -111,7 +112,7 @@ protected function createAutoMock($className): MockObject { fn (string $text, array $parameters = []) => vsprintf($text, $parameters) ); break; - case \OCP\L10N\IFactory::class: + case IFactory::class: $mockL10n = $this->createAutoMock(IL10N::class); $mock->method('get') ->willReturn($mockL10n); diff --git a/tests/lib/UpdaterTest.php b/tests/lib/UpdaterTest.php index 41f88d2c10d40..840c9f50a1fc9 100644 --- a/tests/lib/UpdaterTest.php +++ b/tests/lib/UpdaterTest.php @@ -9,53 +9,20 @@ namespace Test; use OC\Installer; -use OC\IntegrityCheck\Checker; use OC\Updater; use OCP\App\AppPathNotFoundException; use OCP\App\IAppManager; -use OCP\IAppConfig; use OCP\IConfig; -use OCP\ServerVersion; -use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; class UpdaterTest extends TestCase { - /** @var ServerVersion|MockObject */ - private $serverVersion; - /** @var IConfig|MockObject */ - private $config; - /** @var IAppConfig|MockObject */ - private $appConfig; - /** @var LoggerInterface|MockObject */ - private $logger; /** @var Updater */ private $updater; - /** @var Checker|MockObject */ - private $checker; - /** @var Installer|MockObject */ - private $installer; - private IAppManager&MockObject $appManager; #[\Override] protected function setUp(): void { parent::setUp(); - $this->serverVersion = $this->createMock(ServerVersion::class); - $this->config = $this->createMock(IConfig::class); - $this->appConfig = $this->createMock(IAppConfig::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->checker = $this->createMock(Checker::class); - $this->installer = $this->createMock(Installer::class); - $this->appManager = $this->createMock(IAppManager::class); - - $this->updater = new Updater( - $this->serverVersion, - $this->config, - $this->appConfig, - $this->checker, - $this->logger, - $this->installer, - $this->appManager, - ); + + $this->updater = $this->createInstanceWithMocks(Updater::class); } /** @@ -98,11 +65,11 @@ public static function versionCompatibilityTestData(): array { */ #[\PHPUnit\Framework\Attributes\DataProvider('versionCompatibilityTestData')] public function testIsUpgradePossible($oldVersion, $newVersion, $allowedVersions, $result, $debug = false, $vendor = 'nextcloud'): void { - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getSystemValueBool') ->with('debug', false) ->willReturn($debug); - $this->config->expects($this->any()) + $this->mocks[IConfig::class]->expects($this->any()) ->method('getAppValue') ->with('core', 'vendor', '') ->willReturn($vendor); @@ -130,29 +97,29 @@ public function testIsMajorUpgrade(string $installedVersion, string $currentVers } public function testUpgradeAppStoreAppsRestoresMissingAutoDisabledAppBeforeEnabling(): void { - $this->installer->expects($this->once()) + $this->mocks[Installer::class]->expects($this->once()) ->method('isUpdateAvailable') ->with('mailroundcube') ->willReturn(false); - $this->installer->expects($this->once()) + $this->mocks[Installer::class]->expects($this->once()) ->method('downloadApp') ->with('mailroundcube'); - $this->installer->expects($this->once()) + $this->mocks[Installer::class]->expects($this->once()) ->method('installApp') ->with('mailroundcube'); - $this->appManager->expects($this->once()) + $this->mocks[IAppManager::class]->expects($this->once()) ->method('getAppPath') ->with('mailroundcube', true) ->willThrowException(new AppPathNotFoundException('missing')); - $this->appManager->expects($this->once()) + $this->mocks[IAppManager::class]->expects($this->once()) ->method('enableApp') ->with('mailroundcube'); - $this->appManager->expects($this->never()) + $this->mocks[IAppManager::class]->expects($this->never()) ->method('enableAppForGroups'); self::invokePrivate($this->updater, 'upgradeAppStoreApps', [ diff --git a/tests/lib/User/AvailabilityCoordinatorTest.php b/tests/lib/User/AvailabilityCoordinatorTest.php index 8244ec427e630..bda6101fab44f 100644 --- a/tests/lib/User/AvailabilityCoordinatorTest.php +++ b/tests/lib/User/AvailabilityCoordinatorTest.php @@ -18,45 +18,25 @@ use OCP\ICacheFactory; use OCP\IConfig; use OCP\IUser; -use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; use Test\TestCase; class AvailabilityCoordinatorTest extends TestCase { private AvailabilityCoordinator $availabilityCoordinator; - private ICacheFactory $cacheFactory; private ICache $cache; - private IConfig|MockObject $config; - private AbsenceService $absenceService; - private LoggerInterface $logger; - private MockObject|TimezoneService $timezoneService; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->cacheFactory = $this->createMock(ICacheFactory::class); $this->cache = $this->createMock(ICache::class); - $this->absenceService = $this->createMock(AbsenceService::class); - $this->config = $this->createMock(IConfig::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->timezoneService = $this->createMock(TimezoneService::class); - $this->cacheFactory->expects(self::once()) + $this->availabilityCoordinator = $this->createInstanceWithMocks(AvailabilityCoordinator::class); + $this->mocks[ICacheFactory::class]->expects(self::once()) ->method('createLocal') ->willReturn($this->cache); - - $this->availabilityCoordinator = new AvailabilityCoordinator( - $this->cacheFactory, - $this->config, - $this->absenceService, - $this->logger, - $this->timezoneService, - ); } public function testIsEnabled(): void { - $this->config->expects(self::once()) + $this->mocks[IConfig::class]->expects(self::once()) ->method('getAppValue') ->with('dav', 'hide_absence_settings', 'no') ->willReturn('no'); @@ -76,7 +56,7 @@ public function testGetOutOfOfficeDataInEffect(): void { $absence->setMessage('On vacation'); $absence->setReplacementUserId('batman'); $absence->setReplacementUserDisplayName('Bruce Wayne'); - $this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin'); + $this->mocks[TimezoneService::class]->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin'); $user = $this->createMock(IUser::class); $user->method('getUID') @@ -85,7 +65,7 @@ public function testGetOutOfOfficeDataInEffect(): void { $this->cache->expects(self::exactly(2)) ->method('get') ->willReturnOnConsecutiveCalls(null, null); - $this->absenceService->expects(self::once()) + $this->mocks[AbsenceService::class]->expects(self::once()) ->method('getAbsence') ->with($user->getUID()) ->willReturn($absence); @@ -133,7 +113,7 @@ public function testGetOutOfOfficeDataCachedAll(): void { $this->cache->expects(self::exactly(2)) ->method('get') ->willReturnOnConsecutiveCalls('UTC', '{"id":"420","startDate":1696118400,"endDate":1696809540,"shortMessage":"Vacation","message":"On vacation","replacementUserId":"batman","replacementUserDisplayName":"Bruce Wayne"}'); - $this->absenceService->expects(self::never()) + $this->mocks[AbsenceService::class]->expects(self::never()) ->method('getAbsence'); $this->cache->expects(self::exactly(1)) ->method('set'); @@ -168,7 +148,7 @@ public function testGetOutOfOfficeDataNoData(): void { $this->cache->expects(self::exactly(2)) ->method('get') ->willReturnOnConsecutiveCalls('UTC', null); - $this->absenceService->expects(self::once()) + $this->mocks[AbsenceService::class]->expects(self::once()) ->method('getAbsence') ->willReturn(null); $this->cache->expects(self::never()) @@ -188,7 +168,7 @@ public function testGetOutOfOfficeDataWithInvalidCachedData(): void { $absence->setMessage('On vacation'); $absence->setReplacementUserId('batman'); $absence->setReplacementUserDisplayName('Bruce Wayne'); - $this->timezoneService->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin'); + $this->mocks[TimezoneService::class]->method('getUserTimezone')->with('user')->willReturn('Europe/Berlin'); $user = $this->createMock(IUser::class); $user->method('getUID') @@ -197,7 +177,7 @@ public function testGetOutOfOfficeDataWithInvalidCachedData(): void { $this->cache->expects(self::exactly(2)) ->method('get') ->willReturnOnConsecutiveCalls('UTC', '{"id":"420",}'); - $this->absenceService->expects(self::once()) + $this->mocks[AbsenceService::class]->expects(self::once()) ->method('getAbsence') ->with('user') ->willReturn($absence); diff --git a/tests/lib/User/DatabaseTest.php b/tests/lib/User/DatabaseTest.php index 1874b17858972..07b4bfb9ed8cb 100644 --- a/tests/lib/User/DatabaseTest.php +++ b/tests/lib/User/DatabaseTest.php @@ -14,7 +14,6 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\HintException; use OCP\Security\Events\ValidatePasswordPolicyEvent; -use PHPUnit\Framework\MockObject\MockObject; /** * Class DatabaseTest @@ -23,8 +22,6 @@ class DatabaseTest extends Backend { /** @var array */ private $users; - /** @var IEventDispatcher|MockObject */ - private $eventDispatcher; /** @var Database */ protected $backend; @@ -40,9 +37,7 @@ public function getUser() { protected function setUp(): void { parent::setUp(); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - - $this->backend = new Database($this->eventDispatcher); + $this->backend = $this->createInstanceWithMocks(Database::class); foreach ($this->backend->getUsers() as $user) { $this->backend->deleteUser($user); @@ -64,7 +59,7 @@ public function testVerifyPasswordEvent(): void { $user = $this->getUser(); $this->backend->createUser($user, 'pass1'); - $this->eventDispatcher->expects($this->once())->method('dispatchTyped') + $this->mocks[IEventDispatcher::class]->expects($this->once())->method('dispatchTyped') ->willReturnCallback( function (Event $event): void { $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event); @@ -84,7 +79,7 @@ public function testVerifyPasswordEventFail(): void { $user = $this->getUser(); $this->backend->createUser($user, 'pass1'); - $this->eventDispatcher->expects($this->once())->method('dispatchTyped') + $this->mocks[IEventDispatcher::class]->expects($this->once())->method('dispatchTyped') ->willReturnCallback( function (Event $event): void { $this->assertInstanceOf(ValidatePasswordPolicyEvent::class, $event); diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php index 9530baf2fd7d1..3fbd605083a82 100644 --- a/tests/lib/User/ManagerTest.php +++ b/tests/lib/User/ManagerTest.php @@ -30,27 +30,17 @@ #[Group('DB')] class ManagerTest extends TestCase { - private IConfig&MockObject $config; - private IEventDispatcher&MockObject $eventDispatcher; - private ICacheFactory&MockObject $cacheFactory; private ICache&MockObject $cache; - private LoggerInterface&MockObject $logger; private IUserManager $manager; #[\Override] protected function setUp(): void { parent::setUp(); - - $this->config = $this->createMock(IConfig::class); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->cacheFactory = $this->createMock(ICacheFactory::class); $this->cache = $this->createMock(ICache::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->cacheFactory->method('createDistributed') + $this->manager = $this->createInstanceWithMocks(Manager::class); + $this->mocks[ICacheFactory::class]->method('createDistributed') ->willReturn($this->cache); - - $this->manager = new Manager($this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger); } public function testGetBackends(): void { @@ -667,7 +657,7 @@ public function testDeleteUser(): void { ->method('getAppValue') ->willReturnArgument(2); - $this->manager = new Manager($config, $this->cacheFactory, $this->eventDispatcher, $this->logger); + $this->manager = new Manager($config, $this->mocks[ICacheFactory::class], $this->mocks[IEventDispatcher::class], $this->mocks[LoggerInterface::class]); $backend = new \Test\Util\User\Dummy(); $this->manager->registerBackend($backend); @@ -692,7 +682,7 @@ public function testGetByEmail(): void { }); $this->manager = $this->getMockBuilder(Manager::class) - ->setConstructorArgs([$this->config, $this->cacheFactory, $this->eventDispatcher, $this->logger]) + ->setConstructorArgs([$this->mocks[IConfig::class], $this->mocks[ICacheFactory::class], $this->mocks[IEventDispatcher::class], $this->mocks[LoggerInterface::class]]) ->onlyMethods(['getUserConfig', 'get']) ->getMock(); $this->manager->method('getUserConfig')->willReturn($userConfig); From 07b84aa272277f2ca21eb279b98f3679177979d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=B4me=20Chilliet?= Date: Fri, 25 Sep 2026 17:14:36 +0200 Subject: [PATCH 5/5] feat: Support default value for simple types in constructors when autoMocking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Côme Chilliet --- tests/lib/TestCase.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/lib/TestCase.php b/tests/lib/TestCase.php index bf2e8e5795b31..9befc45b74bba 100644 --- a/tests/lib/TestCase.php +++ b/tests/lib/TestCase.php @@ -35,7 +35,7 @@ use OCP\IL10N; use OCP\IUserManager; use OCP\IUserSession; -use OCP\L10N\IFactory; +use OCP\L10N\IFactory as IL10NFactory; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; use OCP\Security\ISecureRandom; @@ -85,6 +85,10 @@ protected function createInstanceWithMocks(string $class, array $overrides = []) throw new \TypeError('Not supported'); } if ($type->isBuiltin()) { + if ($parameter->isOptional()) { + $params[] = $parameter->getDefaultValue(); + continue; + } throw new \TypeError('Not supported, please override value'); } $className = $type->getName(); @@ -112,7 +116,7 @@ protected function createAutoMock($className): MockObject { fn (string $text, array $parameters = []) => vsprintf($text, $parameters) ); break; - case IFactory::class: + case IL10NFactory::class: $mockL10n = $this->createAutoMock(IL10N::class); $mock->method('get') ->willReturn($mockL10n);