From 0e92707edd14bd1a991e834633a0c13b90c35759 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:16:04 +0000 Subject: [PATCH 1/4] Convert AI, auth, cache and console test doubles to Double Replace direct Mockery doubles across AI, API clients, authentication, broadcasting, bus, top-level cache, connection pools and non-scheduler console tests. Keep Mockery-backed framework APIs and existing PHPUnit doubles intact. Preserve required arguments, object identity, forbidden calls and verification counts with native doubles. Use initialized partials and real containers where appropriate, explicit callback capture, and local operation sequences for cross-double ordering. Declare dynamic Redis and console methods in typed test fixtures without changing production APIs. Consolidate duplicate Redis lock suites while retaining all distinct acquisition, ownership, callback and cleanup coverage. Verify ApiResource's unknown-method behavior against the real response rather than a mocking-library exception. Strengthen the untouched-parent timestamp assertion and correct the Redis integration comment. Validation: every changed test class and fixture consumer passed individually, including coroutine, cleanup and cancellation cases. Existing serializer-build skips remain. Root, type-fixture and skeleton static analysis passed; repository and skeleton formatting completed; git diff --check passed. --- tests/Ai/BroadcastBatchingTest.php | 9 +- tests/Ai/ConcurrentToolsTest.php | 65 +- tests/Ai/CoroutineIsolationTest.php | 47 +- tests/Ai/Feature/AgentEventsTest.php | 16 +- .../Ai/Feature/AgentProviderSelectionTest.php | 55 +- tests/Ai/Feature/AiManagerTest.php | 7 +- tests/Ai/Feature/BroadcastAgentTest.php | 13 +- tests/Ai/Feature/EmbeddingsCacheTest.php | 27 +- tests/Ai/Feature/FilesystemToolsTest.php | 50 +- .../Gateway/Concerns/CreatesClientTest.php | 17 +- tests/Ai/Feature/PendingProviderTest.php | 41 +- tests/Ai/Feature/RememberConversationTest.php | 112 ++- .../Storage/DatabaseConversationStoreTest.php | 48 +- tests/Ai/Feature/StoreFakeTest.php | 18 +- tests/Ai/Feature/StreamEventBroadcastTest.php | 9 +- .../Ai/Feature/ToolRequestValidationTest.php | 9 +- .../Ai/Fixtures/Tools/ApprovableNamedTool.php | 11 + tests/Ai/McpClientTransportTest.php | 13 +- tests/Ai/PartitionStoreTest.php | 6 +- tests/Ai/Unit/Gateway/InvokesToolsTest.php | 9 +- .../Unit/Gateway/OpenAi/AudioFilenameTest.php | 5 +- tests/Ai/Unit/Gateway/RunContextTest.php | 9 +- .../Unit/Gateway/TextGenerationLoopTest.php | 112 +-- tests/Ai/Unit/Tools/AgentToolTest.php | 33 +- tests/ApiClient/ApiRequestTest.php | 9 +- tests/ApiClient/ApiResourceTest.php | 75 +- tests/Auth/AuthAccessGateTest.php | 21 +- .../Auth/AuthDatabaseTokenRepositoryTest.php | 48 +- .../AuthEloquentUserProviderCacheTest.php | 329 +++++---- tests/Auth/AuthManagerTest.php | 185 +++-- .../AuthPasswordResetServiceProviderTest.php | 53 +- tests/Auth/AuthRequestGuardTest.php | 37 +- tests/Auth/AuthServiceProviderTest.php | 262 +++---- ...uthenticateWithBasicAuthMiddlewareTest.php | 34 +- tests/Auth/AuthorizableTest.php | 52 +- tests/Auth/AuthorizesRequestsTest.php | 48 +- tests/Auth/CacheTokenRepositoryTest.php | 110 +-- tests/Auth/ClearResetsCommandTest.php | 29 +- tests/Auth/EnsureEmailIsVerifiedTest.php | 63 +- .../RedirectIfAuthenticatedMiddlewareTest.php | 51 +- tests/Auth/RequirePasswordMiddlewareTest.php | 128 ++-- tests/Auth/TimeboxIsolationTest.php | 42 +- tests/Auth/UseGuardMiddlewareTest.php | 11 +- tests/Auth/VerifiedEventTest.php | 7 +- .../BroadcastConnectionReleaseTest.php | 33 +- tests/Broadcasting/BroadcastPoolProxyTest.php | 11 +- .../InteractsWithBroadcastingTest.php | 13 +- tests/Broadcasting/LogBroadcasterTest.php | 17 +- tests/Broadcasting/PendingBroadcastTest.php | 25 +- tests/Bus/BusDebounceLockTest.php | 28 +- tests/Bus/DispatchLockContextTest.php | 35 +- tests/Bus/OutboxOptionsTest.php | 10 +- tests/Bus/QueueableTest.php | 18 +- tests/Cache/CacheDatabaseLockTest.php | 244 +++---- tests/Cache/CacheMemoizedStoreTest.php | 33 +- tests/Cache/CacheNullStoreTest.php | 11 +- tests/Cache/CacheRedisLockTest.php | 303 ++++++--- tests/Cache/CacheRepositoryEnumTest.php | 98 +-- tests/Cache/CacheServiceProviderTest.php | 81 +-- tests/Cache/CacheStackStoreLocksTest.php | 49 +- tests/Cache/CacheStackStoreTagsTest.php | 359 +++++----- tests/Cache/CacheStackStoreTest.php | 640 ++++++++++-------- .../Cache/CacheSwooleStoreConcurrencyTest.php | 5 +- tests/Cache/CacheSwooleStoreIntervalTest.php | 29 +- tests/Cache/CacheSwooleStoreTest.php | 35 +- tests/Cache/CacheTaggedCacheTest.php | 89 ++- tests/Cache/ConcurrencyLimiterTest.php | 11 +- tests/Cache/ForgetCommandTest.php | 21 +- tests/Cache/ModelCacheCoordinatorTest.php | 218 +++--- tests/Cache/ModelCacheStoreValidatorTest.php | 35 +- tests/Cache/PruneStaleTagsCommandTest.php | 63 +- tests/Cache/RedisLockTest.php | 220 ------ .../RegisterSwooleMaintenanceTimersTest.php | 79 ++- tests/ConnectionPool/ConnectionPoolTest.php | 53 +- tests/ConnectionPool/ConnectionTest.php | 297 ++++---- tests/ConnectionPool/Fixtures/FooPool.php | 4 +- .../IdleConnectionMonitorTest.php | 80 ++- .../KeepaliveConnectionTest.php | 48 +- .../Console/Concerns/InteractsWithIOTest.php | 22 +- tests/Console/ConfiguresPromptsTest.php | 81 +-- ...onsoleApplicationDeferredCallbacksTest.php | 11 +- tests/Console/Events/EventsTest.php | 23 +- .../Fixtures/Commands/FooExceptionCommand.php | 8 +- .../Fixtures/Commands/FooExitCommand.php | 8 +- tests/Console/Fixtures/ComponentsFactory.php | 42 ++ tests/Console/GeneratorCommandTest.php | 69 +- tests/Console/InteractsWithSignalsTest.php | 30 +- .../Console/MigrationGeneratorCommandTest.php | 9 +- tests/Console/View/ComponentsTest.php | 14 +- .../Cache/Redis/RedisStoreTest.php | 2 +- .../Database/EloquentBelongsToManyTest.php | 2 +- 91 files changed, 3097 insertions(+), 2854 deletions(-) create mode 100644 tests/Ai/Fixtures/Tools/ApprovableNamedTool.php delete mode 100644 tests/Cache/RedisLockTest.php create mode 100644 tests/Console/Fixtures/ComponentsFactory.php diff --git a/tests/Ai/BroadcastBatchingTest.php b/tests/Ai/BroadcastBatchingTest.php index 8630012af4..22fd1963f1 100644 --- a/tests/Ai/BroadcastBatchingTest.php +++ b/tests/Ai/BroadcastBatchingTest.php @@ -22,7 +22,8 @@ use Hypervel\Support\Facades\Context; use Hypervel\Support\Facades\Event; use Hypervel\Support\Facades\Exceptions; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -31,6 +32,8 @@ class BroadcastBatchingTest extends TestCase { + use VerifiesDoubles; + public function testBatchesPreserveContentBoundariesAndOriginalReplay(): void { config(['ai.broadcasting.batching.milliseconds' => 60000]); @@ -238,8 +241,8 @@ public function testCancellationWhileFinishingBroadcastsCancelsTheSender(bool $c { config(['broadcasting.default' => 'null', 'ai.broadcasting.batching.max_bytes' => 1]); $failure = $cleanupThrows ? new RuntimeException('Release cleanup failed.', previous: new CanceledException) : new CanceledException; - $lease = m::mock(ConnectionLease::class); - $lease->shouldReceive('releaseIfIdle')->once()->andThrow($failure); + $lease = Double::for(ConnectionLease::class); + $lease->expects('releaseIfIdle')->throws($failure); $waiting = new Channel(1); $senderCanceled = false; $senderId = null; diff --git a/tests/Ai/ConcurrentToolsTest.php b/tests/Ai/ConcurrentToolsTest.php index 365c2a2878..ad7e0d57da 100644 --- a/tests/Ai/ConcurrentToolsTest.php +++ b/tests/Ai/ConcurrentToolsTest.php @@ -14,7 +14,6 @@ use Hypervel\Ai\Contracts\Gateway\Gateway; use Hypervel\Ai\Contracts\Gateway\StepTextGateway; use Hypervel\Ai\Contracts\Providers\TextProvider; -use Hypervel\Ai\Contracts\Tool; use Hypervel\Ai\Events\ToolFailed; use Hypervel\Ai\Gateway\RunContext; use Hypervel\Ai\Gateway\StepResponse; @@ -39,8 +38,10 @@ use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Support\Facades\Context; use Hypervel\Support\Facades\DB; +use Hypervel\Tests\Ai\Fixtures\Tools\NamedTool; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -49,6 +50,8 @@ class ConcurrentToolsTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('deliveryModes')] public function testOptedInToolsAreBoundedOrderedAndUseTheCapturedContext(bool $streaming): void { @@ -71,7 +74,7 @@ public function testOptedInToolsAreBoundedOrderedAndUseTheCapturedContext(bool $ Coroutine::afterCreated(static function (): void { CoroutineContext::set('tool-test.account', 'startup'); }); - $providerGateway = m::mock(Gateway::class); + $providerGateway = Double::for(Gateway::class); Ai::extend('tool-test', static fn (Application $app, array $config): Provider => new class($providerGateway, $config, $app->make(Dispatcher::class)) extends Provider {}); $accountProvider = Ai::build(['name' => 'tool-account', 'driver' => 'tool-test', 'key' => 'account-key']); $active = 0; @@ -79,9 +82,9 @@ public function testOptedInToolsAreBoundedOrderedAndUseTheCapturedContext(bool $ $accounts = []; $requestIds = []; $resolvedProviders = []; - $tool = m::mock(Tool::class); - $tool->shouldReceive('name')->andReturn('tool'); - $tool->shouldReceive('handle')->times(3)->andReturnUsing(function (Request $request) use (&$active, &$maximum, &$accounts, &$requestIds, &$resolvedProviders): string { + $tool = Double::for(NamedTool::class); + $tool->allows('name')->returns('tool'); + $tool->expects('handle')->times(3)->resolves(function (Request $request) use (&$active, &$maximum, &$accounts, &$requestIds, &$resolvedProviders): string { $this->assertSame('tool-connection', DB::getDefaultConnection()); $maximum = max($maximum, ++$active); $accounts[] = CoroutineContext::get('tool-test.account'); @@ -97,8 +100,8 @@ public function testOptedInToolsAreBoundedOrderedAndUseTheCapturedContext(bool $ } }); $calls = [new ToolCall('first', 'tool', []), new ToolCall('second', 'tool', []), new ToolCall('third', 'tool', [])]; - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('provider'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('provider'); $results = []; $gateway = $this->gateway($streaming, $calls, $results); $loop = new TextGenerationLoop($gateway); @@ -131,10 +134,10 @@ public static function deliveryModes(): array public function testInvalidConcurrencyFailsClearlyThroughTheLoop(): void { - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('provider'); - $gateway = m::mock(StepTextGateway::class); - $gateway->shouldReceive('generateTextStep')->once()->andReturn(new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta)); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('provider'); + $gateway = Double::for(StepTextGateway::class); + $gateway->expects('generateTextStep')->returns(new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta)); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Tool concurrency must be at least one.'); @@ -161,9 +164,9 @@ public function testToolFailureCancelsAndJoinsTheOtherTools(bool $canceled, bool $active = 0; $resumed = false; - $tool = m::mock(Tool::class); - $tool->shouldReceive('name')->andReturn('tool'); - $tool->shouldReceive('handle')->twice()->andReturnUsing(function (Request $request) use ($failure, &$active, &$resumed): string { + $tool = Double::for(NamedTool::class); + $tool->allows('name')->returns('tool'); + $tool->expects('handle')->times(2)->resolves(function (Request $request) use ($failure, &$active, &$resumed): string { ++$active; try { @@ -181,14 +184,14 @@ public function testToolFailureCancelsAndJoinsTheOtherTools(bool $canceled, bool --$active; } }); - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('provider'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('provider'); $results = []; $gateway = $this->gateway(false, [new ToolCall('first', 'tool', []), new ToolCall('second', 'tool', [])], $results, completes: false); $caught = null; try { - (new TextGenerationLoop($gateway))->generate($provider, 'model', '', tools: [$tool], options: new TextGenerationOptions(agent: new ConcurrentToolsTestAgent('', [], [])), context: new RunContext('invocation', m::mock(Agent::class), $provider, 'model', $events)); + (new TextGenerationLoop($gateway))->generate($provider, 'model', '', tools: [$tool], options: new TextGenerationOptions(agent: new ConcurrentToolsTestAgent('', [], [])), context: new RunContext('invocation', Double::for(Agent::class), $provider, 'model', $events)); } catch (Throwable $exception) { $caught = $exception; } @@ -210,9 +213,9 @@ public function testAbandoningLiveSubAgentOutputCancelsAndJoinsItsProducers(): v $active = 0; $resumed = false; $waiting = new Channel(1); - $agent = m::mock(Agent::class, CanActAsTool::class); - $agent->shouldReceive('name')->andReturn('child'); - $agent->shouldReceive('stream')->twice()->andReturnUsing(function (string $task) use (&$active, &$resumed, $waiting): StreamableAgentResponse { + $agent = Double::for(Agent::class, CanActAsTool::class); + $agent->allows('name')->returns('child'); + $agent->expects('stream')->times(2)->resolves(function (string $task) use (&$active, &$resumed, $waiting): StreamableAgentResponse { return new StreamableAgentResponse($task, function () use ($task, &$active, &$resumed, $waiting): Generator { ++$active; @@ -225,8 +228,8 @@ public function testAbandoningLiveSubAgentOutputCancelsAndJoinsItsProducers(): v } }); }); - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('provider'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('provider'); $results = []; $gateway = $this->gateway(true, [ new ToolCall('first', 'child', ['task' => 'first']), @@ -267,9 +270,9 @@ public function testCancelingTheConsumerCancelsAndJoinsTheTools(bool $throwExcep $resumed = false; $caught = null; $waiting = new Channel(1); - $tool = m::mock(Tool::class); - $tool->shouldReceive('name')->andReturn('tool'); - $tool->shouldReceive('handle')->twice()->andReturnUsing(function () use ($waiting, &$active, &$resumed): string { + $tool = Double::for(NamedTool::class); + $tool->allows('name')->returns('tool'); + $tool->expects('handle')->times(2)->resolves(function () use ($waiting, &$active, &$resumed): string { ++$active; try { @@ -281,8 +284,8 @@ public function testCancelingTheConsumerCancelsAndJoinsTheTools(bool $throwExcep --$active; } }); - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('provider'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('provider'); $results = []; $gateway = $this->gateway(true, [new ToolCall('first', 'tool', []), new ToolCall('second', 'tool', [])], $results, completes: false); $loop = new TextGenerationLoop($gateway); @@ -332,16 +335,16 @@ private function gateway(bool $streaming, array $calls, array &$results, bool $c return new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta); }; - $gateway = m::mock(StepTextGateway::class); + $gateway = Double::for(StepTextGateway::class); if ($streaming) { - $gateway->shouldReceive('generateStreamStep')->times($completes ? 2 : 1)->andReturnUsing(static function (...$arguments) use ($response): Generator { + $gateway->expects('generateStreamStep')->times($completes ? 2 : 1)->resolves(static function (...$arguments) use ($response): Generator { yield from []; return $response($arguments[4]); }); } else { - $gateway->shouldReceive('generateTextStep')->times($completes ? 2 : 1)->andReturnUsing(static fn (...$arguments): StepResponse => $response($arguments[3])); + $gateway->expects('generateTextStep')->times($completes ? 2 : 1)->resolves(static fn (...$arguments): StepResponse => $response($arguments[3])); } return $gateway; diff --git a/tests/Ai/CoroutineIsolationTest.php b/tests/Ai/CoroutineIsolationTest.php index 2175e5e1e7..e30559c75f 100644 --- a/tests/Ai/CoroutineIsolationTest.php +++ b/tests/Ai/CoroutineIsolationTest.php @@ -9,12 +9,10 @@ use Hypervel\Ai\AiManager; use Hypervel\Ai\AnonymousAgent; use Hypervel\Ai\Attributes\RepairToolCalls; -use Hypervel\Ai\Contracts\Approvable; use Hypervel\Ai\Contracts\Gateway\Gateway; use Hypervel\Ai\Contracts\Gateway\StepTextGateway; use Hypervel\Ai\Contracts\Providers\AudioProvider; use Hypervel\Ai\Contracts\Providers\TextProvider; -use Hypervel\Ai\Contracts\Tool; use Hypervel\Ai\Enums\Lab; use Hypervel\Ai\Gateway\FakeAudioGateway; use Hypervel\Ai\Gateway\ParentInvocation; @@ -42,8 +40,11 @@ use Hypervel\Contracts\Filesystem\Filesystem; use Hypervel\Contracts\Foundation\Application; use Hypervel\Engine\Channel; +use Hypervel\Tests\Ai\Fixtures\Tools\ApprovableNamedTool; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use WeakReference; @@ -52,6 +53,8 @@ class CoroutineIsolationTest extends TestCase { + use VerifiesDoubles; + public function testOverlappingOnDemandProvidersKeepTheirCredentialsAndFlushLocalState(): void { $manager = $this->manager(); @@ -183,8 +186,8 @@ function (): array { public function testOverlappingCallbacksReserveSeparateSequenceEntries(): void { - $provider = m::mock(AudioProvider::class); - $provider->shouldReceive('name')->andReturn('audio'); + $provider = Double::for(AudioProvider::class); + $provider->allows('name')->returns('audio'); $gateway = new FakeAudioGateway([ function (): string { usleep(5000); @@ -206,9 +209,9 @@ public function testSharedGenerationLoopKeepsRepairSettingsLocalWhileApprovalChe { $repairStarted = new Channel(1); $ordinaryStarted = new Channel(1); - $tool = m::mock(Tool::class, Approvable::class); - $tool->shouldReceive('name')->andReturn('known'); - $tool->shouldReceive('shouldRequestApproval')->andReturnUsing(static function (Request $request) use ($repairStarted, $ordinaryStarted): null { + $tool = Double::for(ApprovableNamedTool::class); + $tool->allows('name')->returns('known'); + $tool->expects('shouldRequestApproval')->times(2)->resolves(static function (Request $request) use ($repairStarted, $ordinaryStarted): null { if ($request['repair']) { $repairStarted->push(true); $ordinaryStarted->pop(1); @@ -219,12 +222,12 @@ public function testSharedGenerationLoopKeepsRepairSettingsLocalWhileApprovalChe return null; }); - $tool->shouldReceive('handle')->twice()->andReturn('done'); - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('provider'); - $gateway = m::mock(StepTextGateway::class); + $tool->expects('handle')->times(2)->returns('done'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('provider'); + $gateway = Double::for(StepTextGateway::class); $steps = []; - $gateway->shouldReceive('generateTextStep')->times(4)->andReturnUsing(static function (...$arguments) use (&$steps): StepResponse { + $gateway->expects('generateTextStep')->times(4)->resolves(static function (...$arguments) use (&$steps): StepResponse { $instructions = $arguments[2]; $step = $steps[$instructions] ?? 0; $steps[$instructions] = $step + 1; @@ -260,10 +263,10 @@ function () use ($repairStarted, $loop, $provider, $tool): TextResponse { #[DataProvider('generatedResponses')] public function testGeneratedResponseKeepsItsFilenameAcrossCoroutines(GeneratedImage|AudioResponse $response): void { - $disk = m::mock(Filesystem::class); - $disk->shouldReceive('put')->with(m::type('string'), 'generated bytes', [])->times(3)->andReturnTrue(); - $filesystems = m::mock(FilesystemFactory::class); - $filesystems->shouldReceive('disk')->with('generated')->times(3)->andReturn($disk); + $disk = Double::for(Filesystem::class); + $disk->expects('put')->with(Argument::type('string'), 'generated bytes', [])->times(3)->returns(true); + $filesystems = Double::for(FilesystemFactory::class); + $filesystems->expects('disk')->with('generated')->times(3)->returns($disk); Container::getInstance()->instance(FilesystemFactory::class, $filesystems); $parentPath = $response->store('outputs', 'generated'); @@ -427,16 +430,16 @@ protected function captureAccountContext(): Closure */ protected function manager(): AiManager { - $application = m::mock(Application::class); - $application->shouldReceive('make')->with('config')->andReturn(new Repository([ + $application = Double::for(Application::class, override: true); + $application->allows('make')->with('config')->returns(new Repository([ 'ai' => [ 'default' => 'configured', 'providers' => ['configured' => ['driver' => 'custom', 'key' => 'configured-key']], ], ])); - $gateway = m::mock(Gateway::class); - $events = m::mock(Dispatcher::class); - $manager = new AiManager($application); + $gateway = Double::for(Gateway::class); + $events = Double::for(Dispatcher::class); + $manager = new AiManager($application->instance()); $manager->extend('custom', static fn (Application $application, array $config): Provider => new IsolationTestProvider($gateway, $config, $events)); return $manager; diff --git a/tests/Ai/Feature/AgentEventsTest.php b/tests/Ai/Feature/AgentEventsTest.php index dc43cc96e3..8535d581c3 100644 --- a/tests/Ai/Feature/AgentEventsTest.php +++ b/tests/Ai/Feature/AgentEventsTest.php @@ -69,7 +69,8 @@ use Hypervel\Tests\Ai\Fixtures\Tools\FixedNumberGenerator; use Hypervel\Tests\Ai\Fixtures\Tools\NamedTool; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -86,6 +87,7 @@ class AgentEventsTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; public function testASynchronousPromptThreadsOneInvocationIdThroughThePromptAndItsEvents(): void { @@ -786,8 +788,8 @@ public function testFailoverAfterAToolStartsIsTerminalAndPersistsItsResult(): vo 'ai.providers.primary' => ['driver' => 'groq', 'key' => 'test-key'], 'ai.providers.backup' => ['driver' => 'groq', 'key' => 'test-key'], ]); - $tool = m::mock(NamedTool::class, ['send_email'])->makePartial(); - $tool->shouldReceive('handle')->once()->andReturn('Sent'); + $tool = Double::for(new NamedTool('send_email'))->passthru(); + $tool->expects('handle')->returns('Sent'); Http::preventStrayRequests(); Http::fakeSequence() ->pushResponse(fakeGroqToolCallResponse('send_email')) @@ -1027,8 +1029,8 @@ public function testThrowingToolFailureObserverPreservesToolCancellation(): void { $cancellation = new CanceledException; $observerFailure = new RuntimeException('Tool failure observer failed.'); - $tool = m::mock(NamedTool::class, ['cancel_tool'])->makePartial(); - $tool->shouldReceive('handle')->once()->andThrow($cancellation); + $tool = Double::for(new NamedTool('cancel_tool'))->passthru(); + $tool->expects('handle')->throws($cancellation); ToolUsingAgent::fake([new ToolCall('call_1', 'cancel_tool', [])]); $agent = (new ToolUsingAgent)->withTools([$tool]); Event::listen(ToolFailed::class, static fn () => throw $observerFailure); @@ -1095,8 +1097,8 @@ public function testAStreamPersistenceFailureReportsTheAgentFailure(): void config(['ai.conversations.generate_title' => false]); RememberingAssistantAgent::fake(['Hello']); $exception = new RuntimeException('Database unavailable.'); - $store = m::mock(FakeConversationStore::class)->makePartial(); - $store->shouldReceive('storeConversation')->once()->andThrow($exception); + $store = Double::for(FakeConversationStore::class)->passthru(); + $store->expects('storeConversation')->throws($exception); app()->instance(ConversationStore::class, $store); $response = (new RememberingAssistantAgent)->forUser((object) ['id' => 1])->stream('Hi'); diff --git a/tests/Ai/Feature/AgentProviderSelectionTest.php b/tests/Ai/Feature/AgentProviderSelectionTest.php index 0c01e47f98..6cf86fb43d 100644 --- a/tests/Ai/Feature/AgentProviderSelectionTest.php +++ b/tests/Ai/Feature/AgentProviderSelectionTest.php @@ -25,14 +25,17 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Contracts\Foundation\Application; use Hypervel\Testbench\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use function Hypervel\Coroutine\parallel; class AgentProviderSelectionTest extends TestCase { + use VerifiesDoubles; + /** * Configure a provider whose requests are handled by the test. */ @@ -59,8 +62,8 @@ public function testDistinctProvidersWithTheSameNameRemainSeparateFailoverAttemp { $first = Ai::build(['driver' => 'test', 'name' => 'account', 'key' => 'first-key']); $second = Ai::build(['driver' => 'test', 'name' => 'account', 'key' => 'second-key']); - $first->shouldReceive('prompt')->once()->andThrow(RateLimitedException::forProvider('account')); - $second->shouldReceive('prompt')->once()->andReturnUsing(fn (AgentPrompt $prompt): AgentResponse => new AgentResponse( + $first->expects('prompt')->throws(RateLimitedException::forProvider('account')); + $second->expects('prompt')->resolves(fn (AgentPrompt $prompt): AgentResponse => new AgentResponse( $prompt->invocationId, $prompt->provider->providerCredentials()['key'], new TextUsage, @@ -76,12 +79,12 @@ public function testNamedFallbackIsCapturedBeforeAnEarlierAttemptRebuildsIt(): v { $first = Ai::build(['driver' => 'test', 'name' => 'first', 'key' => 'first-key']); $fallback = Ai::build(['driver' => 'test', 'name' => 'account', 'key' => 'original-key']); - $first->shouldReceive('prompt')->once()->andReturnUsing(function (): never { + $first->expects('prompt')->resolves(function (): never { Ai::build(['driver' => 'test', 'name' => 'account', 'key' => 'replacement-key']); throw RateLimitedException::forProvider('first'); }); - $fallback->shouldReceive('prompt')->once()->andReturnUsing(fn (AgentPrompt $prompt): AgentResponse => new AgentResponse( + $fallback->expects('prompt')->resolves(fn (AgentPrompt $prompt): AgentResponse => new AgentResponse( $prompt->invocationId, $prompt->provider->providerCredentials()['key'], new TextUsage, @@ -96,7 +99,7 @@ public function testNamedFallbackIsCapturedBeforeAnEarlierAttemptRebuildsIt(): v public function testProviderObjectsWorkInAChildWithoutTheirNameRegistry(): void { $provider = Ai::build(['driver' => 'test', 'name' => 'account', 'key' => 'account-key']); - $provider->shouldReceive('prompt')->once()->andReturnUsing(fn (AgentPrompt $prompt): AgentResponse => new AgentResponse( + $provider->expects('prompt')->resolves(fn (AgentPrompt $prompt): AgentResponse => new AgentResponse( $prompt->invocationId, $prompt->provider->providerCredentials()['key'], new TextUsage, @@ -138,7 +141,7 @@ public function testLazyStreamsCaptureNamedProvidersAndRunInTheInitiatingContext $provider = $factory($config); if ($config['name'] === 'configured') { - $provider->shouldReceive('stream')->once()->andThrow(RateLimitedException::forProvider('configured')); + $provider->expects('stream')->throws(RateLimitedException::forProvider('configured')); } return $provider; @@ -146,7 +149,7 @@ public function testLazyStreamsCaptureNamedProvidersAndRunInTheInitiatingContext CoroutineContext::set('ai-test.account', 'producer'); $fallback = Ai::build(['driver' => 'test', 'name' => 'account', 'key' => 'original-key']); - $fallback->shouldReceive('stream')->once()->andReturnUsing(function (AgentPrompt $prompt): StreamableAgentResponse { + $fallback->expects('stream')->resolves(function (AgentPrompt $prompt): StreamableAgentResponse { $this->assertNotNull($prompt->contextRunner()); return new StreamableAgentResponse($prompt->invocationId, function () use ($prompt): Generator { @@ -189,13 +192,14 @@ public static function streamProviders(): array public function testProtectedPairOverrideRetainsRepeatedAttempts(): void { $provider = Ai::textProvider('configured'); - $provider->shouldReceive('prompt')->once()->ordered()->andThrow(RateLimitedException::forProvider('configured')); - $provider->shouldReceive('prompt')->once()->ordered()->andReturnUsing(fn (AgentPrompt $prompt): AgentResponse => new AgentResponse( - $prompt->invocationId, - $prompt->model, - new TextUsage, - new Meta, - )); + $attempts = 0; + $provider->expects('prompt')->times(2)->resolves(static function (AgentPrompt $prompt) use (&$attempts): AgentResponse { + if (++$attempts === 1) { + throw RateLimitedException::forProvider('configured'); + } + + return new AgentResponse($prompt->invocationId, $prompt->model, new TextUsage, new Meta); + }); $agent = new class extends ProviderSelectionAgent { /** * Return explicit attempts from the protected extension point. @@ -212,12 +216,12 @@ protected function getProvidersAndModels(Provider|Lab|array|string|null $provide #[DataProvider('generationMethods')] public function testContractOnlyProvidersCanFailOverAndDispatchTheirIdentity(string $method): void { - $primary = m::mock(TextProvider::class); - $primary->shouldReceive($method)->once()->andThrow(RateLimitedException::forProvider('contract')); + $primary = Double::for(TextProvider::class); + $primary->expects($method)->throws(RateLimitedException::forProvider('contract')); Ai::extend('contract', static fn (): TextProvider => $primary); $fallback = Ai::textProvider('configured'); - $fallback->shouldReceive($method)->once()->andReturnUsing(static function (AgentPrompt $prompt) use ($method): AgentResponse|StreamableAgentResponse { + $fallback->expects($method)->resolves(static function (AgentPrompt $prompt) use ($method): AgentResponse|StreamableAgentResponse { return $method === 'prompt' ? new AgentResponse($prompt->invocationId, 'fallback', new TextUsage, new Meta) : new StreamableAgentResponse($prompt->invocationId, static function (): Generator { @@ -253,12 +257,11 @@ public static function generationMethods(): array /** * Create a provider with real identity and mocked generation methods. */ - protected function provider(array $config): Provider&MockInterface + protected function provider(array $config): Provider&DoubleInterface { - $provider = m::mock(Provider::class, TextProvider::class, [ - m::mock(Gateway::class), $config, $this->app->make(Dispatcher::class), - ])->makePartial(); - $provider->shouldReceive('defaultTextModel')->andReturn('test-model'); + $provider = Double::for(ProviderSelectionTextProvider::class)->passthru(); + $provider->__construct(Double::for(Gateway::class), $config, $this->app->make(Dispatcher::class)); + $provider->allows('defaultTextModel')->returns('test-model'); return $provider; } @@ -276,3 +279,7 @@ public function instructions(): string return 'Use the selected provider.'; } } + +abstract class ProviderSelectionTextProvider extends Provider implements TextProvider +{ +} diff --git a/tests/Ai/Feature/AiManagerTest.php b/tests/Ai/Feature/AiManagerTest.php index 9880179a25..7b295f7341 100644 --- a/tests/Ai/Feature/AiManagerTest.php +++ b/tests/Ai/Feature/AiManagerTest.php @@ -16,12 +16,15 @@ use Hypervel\Support\Facades\Facade; use Hypervel\Tests\Ai\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class AiManagerTest extends TestCase { + use VerifiesDoubles; + protected AiManager $manager; /** @@ -141,7 +144,7 @@ public function testDriverExtensionsSurviveBetweenQueueJobs(): void public function testCustomDriversMayImplementProviderContractsWithoutExtendingTheBaseClass(): void { - $provider = m::mock(AudioProvider::class); + $provider = Double::for(AudioProvider::class); $this->manager->extend('custom', static fn (): AudioProvider => $provider); $this->assertSame($provider, $this->manager->audioProvider()); diff --git a/tests/Ai/Feature/BroadcastAgentTest.php b/tests/Ai/Feature/BroadcastAgentTest.php index 166b6223f7..64461765e9 100644 --- a/tests/Ai/Feature/BroadcastAgentTest.php +++ b/tests/Ai/Feature/BroadcastAgentTest.php @@ -17,13 +17,16 @@ use Hypervel\Tests\Ai\Fixtures\Agents\AssistantAgent; use Hypervel\Tests\Ai\Fixtures\Agents\ConversationalAgent; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Throwable; class BroadcastAgentTest extends TestCase { + use VerifiesDoubles; + public function testThenCallbackReceivesStreamedAgentResponse(): void { Event::fake(); @@ -169,10 +172,10 @@ public function testAnOversizedBroadcastFrameDoesNotAbortTheStreamAndThenStillRe { AssistantAgent::fake(['Hello world']); - $pending = m::mock(AnonymousEvent::class); - $pending->shouldReceive('as')->andReturnSelf(); - $pending->shouldReceive('with')->andReturnSelf(); - $pending->shouldReceive('sendNow')->atLeast()->once()->andThrow(new BroadcastException('Payload too large')); + $pending = Double::for(AnonymousEvent::class); + $pending->allows('as'); + $pending->allows('with'); + $pending->expects('sendNow')->times(minimum: 1)->throws(new BroadcastException('Payload too large')); Broadcast::shouldReceive('on')->andReturn($pending); diff --git a/tests/Ai/Feature/EmbeddingsCacheTest.php b/tests/Ai/Feature/EmbeddingsCacheTest.php index 4f328f7b5f..7529314a2b 100644 --- a/tests/Ai/Feature/EmbeddingsCacheTest.php +++ b/tests/Ai/Feature/EmbeddingsCacheTest.php @@ -23,7 +23,8 @@ use Hypervel\Http\Client\Response; use Hypervel\Support\Facades\Http; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; function fakeCohereEmbedding(string $text): array @@ -33,6 +34,8 @@ function fakeCohereEmbedding(string $text): array class EmbeddingsCacheTest extends TestCase { + use VerifiesDoubles; + /** * Configure the embedding provider and cache. */ @@ -339,8 +342,8 @@ public static function cacheModes(): array public function testSameNameOnDemandProvidersRetainTheirOwnCacheIdentity(): void { - $gateway = m::mock(Gateway::class); - $gateway->shouldReceive('generateEmbeddings')->twice()->andReturnUsing( + $gateway = Double::for(Gateway::class); + $gateway->expects('generateEmbeddings')->times(2)->resolves( fn (EmbeddingProvider $provider): EmbeddingsResponse => new EmbeddingsResponse( [[$provider->providerCredentials()['key'] === 'first-key' ? 1 : 2]], new Usage(1), @@ -375,15 +378,15 @@ public function testDisabledCachingDoesNotResolveCacheScope(): void protected function useCustomProvider(Closure $generate): void { Ai::extend('cache-test', function (Application $app, array $config) use ($generate): EmbeddingProvider { - $provider = m::mock(EmbeddingProvider::class); - $provider->shouldReceive('name')->andReturn('cache-test'); - $provider->shouldReceive('driver')->andReturn('cache-test'); - $provider->shouldReceive('providerCredentials')->andReturn(['key' => $config['key']]); - $provider->shouldReceive('additionalConfiguration')->andReturn(array_diff_key($config, array_flip(['name', 'driver', 'key']))); - $provider->shouldReceive('defaultEmbeddingsModel')->andReturn('embedding-model'); - $provider->shouldReceive('defaultEmbeddingsDimensions')->andReturn(1); - $provider->shouldReceive('withHeaders')->andReturnSelf(); - $provider->shouldReceive('embeddings')->andReturnUsing($generate); + $provider = Double::for(EmbeddingProvider::class); + $provider->allows('name')->returns('cache-test'); + $provider->allows('driver')->returns('cache-test'); + $provider->allows('providerCredentials')->returns(['key' => $config['key']]); + $provider->allows('additionalConfiguration')->returns(array_diff_key($config, array_flip(['name', 'driver', 'key']))); + $provider->allows('defaultEmbeddingsModel')->returns('embedding-model'); + $provider->allows('defaultEmbeddingsDimensions')->returns(1); + $provider->allows('withHeaders'); + $provider->allows('embeddings')->resolves($generate); return $provider; }); diff --git a/tests/Ai/Feature/FilesystemToolsTest.php b/tests/Ai/Feature/FilesystemToolsTest.php index 7edcd03268..80cfe69ef2 100644 --- a/tests/Ai/Feature/FilesystemToolsTest.php +++ b/tests/Ai/Feature/FilesystemToolsTest.php @@ -32,9 +32,10 @@ use Hypervel\Support\Facades\Http; use Hypervel\Support\Facades\Storage; use Hypervel\Tests\Ai\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\Flysystem\PathTraversalDetected; use League\Flysystem\UnableToRetrieveMetadata; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -47,6 +48,8 @@ class FilesystemToolsTest extends TestCase { + use VerifiesDoubles; + /** * Create an isolated local disk for each test. */ @@ -73,13 +76,14 @@ public function testFilesystemCancellationIsNotConvertedToAToolResult(string $to if ($cleanupThrows) { $cancellation = new RuntimeException('Filesystem cleanup failed.', previous: $cancellation); } - $disk = m::mock(FilesystemAdapter::class); - $disk->shouldReceive('fileExists')->andReturn(true); - $disk->shouldReceive('size')->andReturn(10)->byDefault(); - $disk->shouldReceive('lastModified')->andReturn(1)->byDefault(); - $disk->shouldReceive('mimeType')->andReturn('text/plain')->byDefault(); - $disk->shouldReceive('getVisibility')->andReturn('public')->byDefault(); - $disk->shouldReceive($method)->once()->andThrow($cancellation); + $disk = Double::for(FilesystemAdapter::class); + $disk->allows('fileExists')->returns(true); + foreach (['size' => 10, 'lastModified' => 1, 'mimeType' => 'text/plain', 'getVisibility' => 'public'] as $operation => $value) { + if ($operation !== $method) { + $disk->allows($operation)->returns($value); + } + } + $disk->expects($method)->throws($cancellation); $caught = null; try { @@ -151,9 +155,9 @@ public function testLookupFailuresForExistingFilesAreReportedInsteadOfDescribedA { Exceptions::fake(); $failure = UnableToRetrieveMetadata::fileSize('file.txt', 'Access denied.'); - $disk = m::mock(FilesystemAdapter::class); - $disk->shouldReceive('size')->once()->with('file.txt')->andThrow($failure); - $disk->shouldReceive('fileExists')->once()->with('file.txt')->andReturnTrue(); + $disk = Double::for(FilesystemAdapter::class); + $disk->expects('size')->with('file.txt')->throws($failure); + $disk->expects('fileExists')->with('file.txt')->returns(true); $this->assertSame($result, (new $toolClass($disk))->handle(new Request(['path' => 'file.txt']))); @@ -235,9 +239,9 @@ public function testReadFileRejectsABinaryFile(): void public function testReadFileReportsAnUnreadableFile(): void { - $disk = m::mock(FilesystemAdapter::class); - $disk->shouldReceive('size')->once()->with('note.txt')->andReturn(10); - $disk->shouldReceive('get')->once()->with('note.txt')->andReturnNull(); + $disk = Double::for(FilesystemAdapter::class); + $disk->expects('size')->with('note.txt')->returns(10); + $disk->expects('get')->with('note.txt')->returns(null); $result = (new ReadFile($disk))->handle(new Request(['path' => 'note.txt'])); @@ -356,9 +360,9 @@ public function testDeleteFileDoesNotReportDirectoriesAsFiles(): void public function testDeleteFileReportsDeleteFailures(): void { - $disk = m::mock(Filesystem::class); - $disk->shouldReceive('fileExists')->with('gone.txt')->andReturn(true); - $disk->shouldReceive('delete')->with('gone.txt')->andReturn(false); + $disk = Double::for(Filesystem::class); + $disk->expects('fileExists')->with('gone.txt')->returns(true); + $disk->expects('delete')->with('gone.txt')->returns(false); $result = (new DeleteFile($disk))->handle(new Request(['path' => 'gone.txt'])); @@ -395,9 +399,9 @@ public function testCopyFileDoesNotCopyDirectories(): void public function testCopyFileReportsCopyFailures(): void { - $disk = m::mock(Filesystem::class); - $disk->expects('fileExists')->with('a.txt')->andReturnTrue(); - $disk->expects('copy')->with('a.txt', 'b.txt')->andReturnFalse(); + $disk = Double::for(Filesystem::class); + $disk->expects('fileExists')->with('a.txt')->returns(true); + $disk->expects('copy')->with('a.txt', 'b.txt')->returns(false); $result = (new CopyFile($disk))->handle(new Request(['from' => 'a.txt', 'to' => 'b.txt'])); @@ -435,9 +439,9 @@ public function testMoveFileDoesNotMoveDirectories(): void public function testMoveFileReportsMoveFailures(): void { - $disk = m::mock(Filesystem::class); - $disk->shouldReceive('fileExists')->with('a.txt')->andReturn(true); - $disk->shouldReceive('move')->with('a.txt', 'b.txt')->andReturn(false); + $disk = Double::for(Filesystem::class); + $disk->expects('fileExists')->with('a.txt')->returns(true); + $disk->expects('move')->with('a.txt', 'b.txt')->returns(false); $result = (new MoveFile($disk))->handle(new Request(['from' => 'a.txt', 'to' => 'b.txt'])); diff --git a/tests/Ai/Feature/Gateway/Concerns/CreatesClientTest.php b/tests/Ai/Feature/Gateway/Concerns/CreatesClientTest.php index 80fdfb6cf6..98a2de8fee 100644 --- a/tests/Ai/Feature/Gateway/Concerns/CreatesClientTest.php +++ b/tests/Ai/Feature/Gateway/Concerns/CreatesClientTest.php @@ -13,10 +13,13 @@ use Hypervel\Http\Client\PendingRequest; use Hypervel\Support\Facades\Http; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CreatesClientTest extends TestCase { + use VerifiesDoubles; + /** * Configure an application-owned provider before package boot. */ @@ -52,8 +55,8 @@ public function testSelectsRegisteredConnectionsWithoutRetainingDynamicProviderN config(['ai.providers.added-later' => ['driver' => 'openai', 'key' => 'test-key']]); foreach (['configured', 'on-demand', 'added-later'] as $name) { - $provider = m::mock(Provider::class); - $provider->shouldReceive('name')->andReturn($name); + $provider = Double::for(Provider::class); + $provider->allows('name')->returns($name); $client = $this->httpClient(provider: $provider); $this->assertSame( @@ -77,10 +80,10 @@ public function testProviderCredentialsAndOptionsRemainOnEachRequest(): void $requests = []; foreach (['first', 'second'] as $index => $key) { - $provider = m::mock(BaseProvider::class); - $provider->shouldReceive('name')->andReturn('configured'); - $provider->shouldReceive('providerCredentials')->andReturn(['key' => $key]); - $provider->shouldReceive('additionalConfiguration')->andReturn(['headers' => ['X-Request' => $key]]); + $provider = Double::for(BaseProvider::class); + $provider->allows('name')->returns('configured'); + $provider->allows('providerCredentials')->returns(['key' => $key]); + $provider->allows('additionalConfiguration')->returns(['headers' => ['X-Request' => $key]]); $requests[] = $gateway->client($provider, $index + 1); } diff --git a/tests/Ai/Feature/PendingProviderTest.php b/tests/Ai/Feature/PendingProviderTest.php index bbc0eea250..b3f0ea69e0 100644 --- a/tests/Ai/Feature/PendingProviderTest.php +++ b/tests/Ai/Feature/PendingProviderTest.php @@ -39,11 +39,15 @@ use Hypervel\Contracts\Foundation\Application; use Hypervel\Support\Facades\Event; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; class PendingProviderTest extends TestCase { + use VerifiesDoubles; + /** * Configure contract-only providers for failover. */ @@ -58,37 +62,37 @@ protected function defineEnvironment(Application $app): void #[DataProvider('generations')] public function testContractProviderFailoverRetainsTheOriginalNamedFallback(string $kind, string $contract, string $method, string $responseClass): void { - $response = m::mock($responseClass); + $response = Double::for($responseClass); $exception = RateLimitedException::forProvider('first'); $providers = []; foreach (['first', 'second'] as $name) { - $provider = $name === 'first' ? m::mock($contract) : m::mock(BaseProvider::class, $contract); - $provider->shouldReceive('name')->andReturn($name); - $provider->shouldReceive('withHeaders')->once()->with(['X-Provider' => $name])->andReturnSelf(); + $provider = $name === 'first' ? Double::for($contract) : Double::for(PendingTestProvider::class); + $provider->allows('name')->returns($name); + $provider->expects('withHeaders')->with(['X-Provider' => $name]); if ($kind === 'embeddings') { - $provider->shouldReceive('defaultEmbeddingsDimensions')->andReturn(1); + $provider->allows('defaultEmbeddingsDimensions')->returns(1); } - $expectation = $provider->shouldReceive($method)->once()->withArgs( + $expectation = $provider->expects($method)->with(Argument::all( fn (mixed ...$arguments): bool => in_array(['account' => $name], $arguments, true) - ); + )); if ($name === 'first') { - $expectation->andReturnUsing(function () use ($exception): never { + $expectation->resolves(function () use ($exception): never { Ai::build(['name' => 'second', 'driver' => 'custom', 'key' => 'replacement']); throw $exception; }); } else { - $expectation->andReturn($response); + $expectation->returns($response); } $providers[$name] = $provider; } - $replacement = m::mock(BaseProvider::class, $contract); + $replacement = Double::for(PendingTestProvider::class); Ai::extend('custom', fn (Application $app, array $config): Provider => $config['key'] === 'replacement' ? $replacement : $providers[$config['name']]); @@ -113,18 +117,19 @@ public function testContractProviderFailoverRetainsTheOriginalNamedFallback(stri $this->assertCount(1, $events); $this->assertSame($providers['first'], $events[0]->provider); $this->assertSame($exception, $events[0]->exception); + $replacement->unused(); } #[DataProvider('generations')] public function testConfiguredDefaultsAcceptEnumsAndProviderLists(string $kind, string $contract, string $method, string $responseClass): void { - $response = m::mock($responseClass); - $provider = m::mock($contract); - $provider->shouldReceive('withHeaders')->twice()->with([])->andReturnSelf(); - $provider->shouldReceive($method)->twice()->andReturn($response); + $response = Double::for($responseClass); + $provider = Double::for($contract); + $provider->expects('withHeaders')->times(2)->with([]); + $provider->expects($method)->times(2)->returns($response); if ($kind === 'embeddings') { - $provider->shouldReceive('defaultEmbeddingsDimensions')->andReturn(1); + $provider->allows('defaultEmbeddingsDimensions')->returns(1); } Ai::extend('custom', fn (): Provider => $provider); @@ -172,3 +177,7 @@ protected function pendingRequest(string $kind): PendingAudioGeneration|PendingC }; } } + +abstract class PendingTestProvider extends BaseProvider implements AudioProvider, ClassificationProvider, EmbeddingProvider, ImageProvider, RerankingProvider, TranscriptionProvider +{ +} diff --git a/tests/Ai/Feature/RememberConversationTest.php b/tests/Ai/Feature/RememberConversationTest.php index 034f5b2fe5..6ae0fd2334 100644 --- a/tests/Ai/Feature/RememberConversationTest.php +++ b/tests/Ai/Feature/RememberConversationTest.php @@ -47,7 +47,9 @@ use Hypervel\Tests\Ai\Fixtures\Agents\RememberingAssistantAgent; use Hypervel\Tests\Ai\Fixtures\OpenAiHelpers; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -59,6 +61,7 @@ class RememberConversationTest extends TestCase { use OpenAiHelpers; use RefreshDatabase; + use VerifiesDoubles; public function testACompleteTurnUpdatesConversationActivityOnce(): void { @@ -80,12 +83,11 @@ public function continue(string $conversationId, ?object $as = null): static }; $agent->continue($conversationId); $agent->continuations = 0; - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('test'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('test'); $prompt = new AgentPrompt($agent, 'Hello', [], $provider, 'model'); - $middleware = m::mock(RememberConversation::class, [$store, $provider]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldNotReceive('generateTitle'); + $middleware = Double::for(new RememberConversation($store, $provider))->passthru(); + $middleware->expects('generateTitle')->never(); DB::enableQueryLog(); $response = $middleware->handle($prompt, fn (): AgentResponse => $this->response()); @@ -103,17 +105,17 @@ public function testDirectProviderCapturesAContractOnlyAgentsSelectionAndHistory config(['ai.providers.openai.key' => 'test-key']); $participant = $originalParticipant = (object) ['id' => 1]; $conversationId = null; - $agent = m::mock(Agent::class, RemembersConversations::class); - $agent->shouldReceive('currentConversation')->andReturnUsing(function () use (&$conversationId): ?string { + $agent = Double::for(Agent::class, RemembersConversations::class); + $agent->allows('currentConversation')->resolves(function () use (&$conversationId): ?string { return $conversationId; }); - $agent->shouldReceive('conversationParticipant')->andReturnUsing(function () use (&$participant): object { + $agent->allows('conversationParticipant')->resolves(function () use (&$participant): object { return $participant; }); $history = [new UserMessage('Earlier message')]; - $agent->shouldReceive('messages')->once()->andReturn($history); - $agent->shouldReceive('instructions')->andReturn('Be helpful.'); - $agent->shouldNotReceive('continue'); + $agent->expects('messages')->returns($history); + $agent->allows('instructions')->returns('Be helpful.'); + $agent->expects('continue')->never(); $provider = Ai::textProvider('openai'); $prompt = new AgentPrompt($agent, 'Hello', [], $provider, 'model'); @@ -141,8 +143,8 @@ public function testDirectProviderCapturesAContractOnlyAgentsSelectionAndHistory public function testFailedAtomicPersistenceDoesNotLeaveHalfATurnOrChangeTheAgent(): void { $failure = new RuntimeException('Cannot store assistant'); - $store = m::mock(DatabaseConversationStore::class, [null])->makePartial(); - $store->shouldReceive('storeAssistantMessage')->once()->andThrow($failure); + $store = Double::for(new DatabaseConversationStore)->passthru(); + $store->expects('storeAssistantMessage')->throws($failure); $prompt = $this->prompt(); $this->assertThrowsSame($failure, fn () => (new RememberConversation($store, $prompt->provider()))->handle($prompt, fn (): AgentResponse => $this->response())); @@ -325,11 +327,10 @@ public function testInvalidApprovalDecisionsWithoutAConversationWriteNothing(boo { config(['ai.conversations.generate_title' => true, 'ai.conversations.concurrent_title' => $concurrent]); $prompt = $this->prompt(Decisions::from(['call' => true])); - $loop = new TextGenerationLoop(m::mock(StepTextGateway::class)); + $loop = new TextGenerationLoop(Double::for(StepTextGateway::class)); $titleRequests = 0; - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldReceive('generateTitle')->andReturnUsing(function () use (&$titleRequests): string { + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); + $middleware->allows('generateTitle')->resolves(function () use (&$titleRequests): string { ++$titleRequests; return 'Unexpected title'; @@ -356,10 +357,10 @@ public static function titleModes(): array public function testASequentialStoreCanChooseItsOwnIdWhenContinuingAnEmptyId(): void { - $store = m::mock(ConversationStore::class); - $store->shouldReceive('storeConversation')->once()->andReturn('custom-conversation'); - $store->shouldReceive('storeUserMessage')->once()->with('custom-conversation', null, null, RememberingAssistantAgent::class, m::type('object'))->andReturn('user-message'); - $store->shouldReceive('storeAssistantMessage')->once()->with('custom-conversation', null, null, m::type(AgentPrompt::class), m::type(AgentResponse::class), null)->andReturn('assistant-message'); + $store = Double::for(ConversationStore::class); + $store->expects('storeConversation')->returns('custom-conversation'); + $store->expects('storeUserMessage')->with('custom-conversation', null, null, RememberingAssistantAgent::class, Argument::type('object'))->returns('user-message'); + $store->expects('storeAssistantMessage')->with('custom-conversation', null, null, Argument::type(AgentPrompt::class), Argument::type(AgentResponse::class), null)->returns('assistant-message'); $prompt = $this->prompt(); $prompt->agent->continue(''); @@ -391,9 +392,8 @@ public function testConcurrentTitlesOverlapInCapturedContextAndAreGeneratedOnce( CoroutineContext::set('title-test.account', $previous); } }); - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldReceive('generateTitle')->once()->andReturnUsing(function () use ($waiting, &$active, &$titleAccount): string { + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); + $middleware->expects('generateTitle')->resolves(function () use ($waiting, &$active, &$titleAccount): string { $this->assertSame('title-request', Context::get('request_id')); $titleAccount = CoroutineContext::get('title-test.account'); $active = true; @@ -481,12 +481,11 @@ public function testIndependentTitleCancellationPreservesTheCompletedTurn(bool $ { config(['ai.conversations.generate_title' => true, 'ai.conversations.concurrent_title' => true]); $prompt = $this->prompt(); - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); $failure = $wrapped ? new RuntimeException('Title cleanup failed.', previous: new CanceledException) : new CanceledException; - $middleware->shouldReceive('generateTitle')->once()->andThrow($failure); + $middleware->expects('generateTitle')->throws($failure); $response = $middleware->handle($prompt, fn () => $this->response()); @@ -504,9 +503,8 @@ public function testUnrecordableFailuresCancelAndJoinAnUnfinishedTitle(bool $str $active = false; $resumed = false; $failure = new RuntimeException('Provider failed before any work'); - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldReceive('generateTitle')->once()->andReturnUsing(function () use ($waiting, &$active, &$resumed): string { + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); + $middleware->expects('generateTitle')->resolves(function () use ($waiting, &$active, &$resumed): string { $active = true; try { @@ -549,9 +547,8 @@ public function testRecordableFailuresUseTheConcurrentTitleOnce(bool $streaming) config(['ai.conversations.generate_title' => true, 'ai.conversations.concurrent_title' => true]); $prompt = $this->prompt(); $failure = new RuntimeException('Provider failed after a tool'); - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldReceive('generateTitle')->once()->andReturn('Failed conversation'); + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); + $middleware->expects('generateTitle')->returns('Failed conversation'); $generate = function () use ($prompt, $failure): never { $prompt->setRunContext($context = $this->context($prompt)); $context->recordStep($this->step()); @@ -579,8 +576,8 @@ public function testFailedTurnPersistencePreservesCancellation(bool $streaming): $prompt = $this->prompt(); $cancellation = new CanceledException; $storageFailure = new RuntimeException('Conversation storage failed.'); - $store = m::mock(DatabaseConversationStore::class); - $store->shouldReceive('storeTurn')->once()->andThrow($storageFailure); + $store = Double::for(DatabaseConversationStore::class); + $store->expects('storeTurn')->throws($storageFailure); $middleware = new RememberConversation($store, $prompt->provider()); $generate = function () use ($prompt, $cancellation): never { $prompt->setRunContext($context = $this->context($prompt)); @@ -629,11 +626,10 @@ public function testRecordableStoppedStreamsDoNotWaitForOrStartTitleRequests(boo if ($cleanupThrows) { $failure = new RuntimeException('Stream cleanup failed.', previous: $failure); } - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); if ($concurrent) { - $middleware->shouldReceive('generateTitle')->once()->andReturnUsing(function () use ($waiting, &$active, &$finished): string { + $middleware->expects('generateTitle')->resolves(function () use ($waiting, &$active, &$finished): string { $active = true; try { @@ -646,7 +642,7 @@ public function testRecordableStoppedStreamsDoNotWaitForOrStartTitleRequests(boo } }); } else { - $middleware->shouldNotReceive('generateTitle'); + $middleware->expects('generateTitle')->never(); } $stream = new StreamableAgentResponse('invocation', function () use ($prompt, $failure, $abandoned, $concurrent, &$active): Generator { @@ -704,9 +700,8 @@ public function testUnconsumedStreamsDoNotStartTitlesAndAbandonmentJoinsThem(): $waiting = new Channel(1); $active = false; $started = false; - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldReceive('generateTitle')->once()->andReturnUsing(function () use ($waiting, &$active, &$started): string { + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); + $middleware->expects('generateTitle')->resolves(function () use ($waiting, &$active, &$started): string { $active = $started = true; try { @@ -746,9 +741,8 @@ public function testAgentFakesKeepSerialTitleOrderingWhenConcurrencyIsEnabled(): $prompt = $this->prompt(); Ai::fakeAgent($prompt->agent::class); $generated = false; - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldReceive('generateTitle')->once()->andReturnUsing(function () use (&$generated): string { + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); + $middleware->expects('generateTitle')->resolves(function () use (&$generated): string { $this->assertTrue($generated); return 'Fake conversation'; @@ -771,9 +765,8 @@ public function testCancelingTheStreamConsumerJoinsItsTitleRequest(): void $waiting = new Channel(1); $active = false; $caught = null; - $middleware = m::mock(RememberConversation::class, [new DatabaseConversationStore, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldReceive('generateTitle')->once()->andReturnUsing(function () use ($waiting, &$active): string { + $middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru(); + $middleware->expects('generateTitle')->resolves(function () use ($waiting, &$active): string { $active = true; try { @@ -837,9 +830,8 @@ public function storeConversation(?string $participantType, string|int|null $par $caught = null; $reported = null; $failure = new RuntimeException('Provider failed after a tool'); - $middleware = m::mock(RememberConversation::class, [$store, $prompt->provider()]) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $middleware->shouldReceive('generateTitle')->once()->andReturnUsing(function () use ($waiting, &$active): string { + $middleware = Double::for(new RememberConversation($store, $prompt->provider()))->passthru(); + $middleware->expects('generateTitle')->resolves(function () use ($waiting, &$active): string { $active = true; try { @@ -937,8 +929,8 @@ public function testTitleCancellationSavesTheCompletedTurnBeforeRethrowing(bool if ($cleanupThrows) { $failure = new RuntimeException('Title cleanup failed.', previous: $failure); } - $prompt->provider()->shouldReceive('prompt')->once()->andThrow($failure); - $prompt->provider()->shouldReceive('cheapestTextModel')->once()->andReturn('title-model'); + $prompt->provider()->expects('prompt')->throws($failure); + $prompt->provider()->expects('cheapestTextModel')->returns('title-model'); $response = $this->response(); $this->assertThrowsSame($failure, fn () => (new RememberConversation(new DatabaseConversationStore, $prompt->provider())) @@ -955,10 +947,10 @@ public function testStorageFailurePreservesTitleCancellation(): void $prompt = $this->prompt(); $cancellation = new CanceledException('Title request canceled.'); $storageFailure = new RuntimeException('Conversation storage failed.'); - $prompt->provider()->shouldReceive('prompt')->once()->andThrow($cancellation); - $prompt->provider()->shouldReceive('cheapestTextModel')->once()->andReturn('title-model'); - $store = m::mock(DatabaseConversationStore::class); - $store->shouldReceive('storeTurn')->once()->andThrow($storageFailure); + $prompt->provider()->expects('prompt')->throws($cancellation); + $prompt->provider()->expects('cheapestTextModel')->returns('title-model'); + $store = Double::for(DatabaseConversationStore::class); + $store->expects('storeTurn')->throws($storageFailure); $caught = null; try { @@ -978,8 +970,8 @@ public function testStorageFailurePreservesTitleCancellation(): void */ private function prompt(?Decisions $decisions = null): AgentPrompt { - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('test'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('test'); return new AgentPrompt((new RememberingAssistantAgent)->forUser((object) ['id' => 1]), 'Hello', [], $provider, 'model', approvalDecisions: $decisions); } diff --git a/tests/Ai/Feature/Storage/DatabaseConversationStoreTest.php b/tests/Ai/Feature/Storage/DatabaseConversationStoreTest.php index 47ce68ac4e..32510a000d 100644 --- a/tests/Ai/Feature/Storage/DatabaseConversationStoreTest.php +++ b/tests/Ai/Feature/Storage/DatabaseConversationStoreTest.php @@ -62,7 +62,8 @@ use Hypervel\Tests\Ai\Fixtures\Agents\ToolUsingAgent; use Hypervel\Tests\Ai\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Throwable; @@ -71,6 +72,7 @@ class DatabaseConversationStoreTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; public function testItWritesConversationsToTheDefaultTables(): void { @@ -416,7 +418,7 @@ public function testItStoresAResponseBuiltWithoutStepsAsASingleStepOfLists(): vo new ToolUsingAgent, 'Check my order status.', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -477,7 +479,7 @@ public function testItRoundTripsToolResultFailureStatusThroughStorage(): void new ToolUsingAgent, 'Where is Berlin?', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -507,7 +509,7 @@ public function testItStoresAToolResultIdOnTheCallThatMadeIt(): void new ToolUsingAgent, 'Write the file', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -585,7 +587,7 @@ public function testABareRejectionResumeDoesNotPersistABlankAssistantRow(): void new ToolUsingAgent, '', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => Decision::reject()]), ); @@ -620,7 +622,7 @@ public function testAResumeFoldsItsStepsTextAndUsageIntoThePausedRow(bool $strea new ToolUsingAgent, '', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]), ); @@ -676,7 +678,7 @@ public function testAStreamedTurnThatPausesTwiceKeepsTheTextOfEveryStep(): void new ToolUsingAgent, '', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from([$callId => true]), ); @@ -716,7 +718,7 @@ public function testAStreamedResumeKeepsAContinuedStepInOneParagraph(): void new ToolUsingAgent, '', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]), ); @@ -743,7 +745,7 @@ public function testAResumeKeepsTheCitationsThePausedHalfOfTheTurnCollected(): v assistantStep([['id' => 'call-1', 'name' => 'DeleteFile', 'arguments' => []]]), ], ['call-1' => 'Deletes a file'], ['provider' => 'anthropic', 'model' => 'claude-sonnet-4-5', 'citations' => [(new UrlCitation('https://hypervel.org/docs/ai'))->toArray()]]); - $prompt = new AgentPrompt(new ToolUsingAgent, '', [], m::mock(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); + $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); $meta = new Meta('anthropic', 'claude-sonnet-4-6', collect([new UrlCitation('https://hypervel.org/docs/mcp')])); @@ -769,7 +771,7 @@ public function testAFoldThatRecordedNoResultDoesNotLeaveTheRowReportingAPending assistantStep([['id' => 'call-1', 'name' => 'DeleteFile', 'arguments' => []]]), ], ['call-1' => 'Deletes a file']); - $prompt = new AgentPrompt(new ToolUsingAgent, '', [], m::mock(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); + $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); $response = (new AgentResponse('invocation-id', 'Done.', new TextUsage, new Meta))->withSteps(collect([ new Step('Done.', [], [], FinishReason::Stop, new TextUsage, new Meta, '', []), @@ -792,7 +794,7 @@ public function testAResumeDoesNotFoldIntoASettledRowOnceANewerPlainTurnFollowsI new ToolUsingAgent, '', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]), ); @@ -918,7 +920,7 @@ public function testCompletingATurnStoresNoReplayBlocksAndDropsThoseOfThePausedR ), ], [], ['provider' => 'anthropic']); - $prompt = new AgentPrompt(new ToolUsingAgent, '', [], m::mock(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); + $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); $response = (new AgentResponse('invocation-id', 'Deleted b.', new TextUsage, new Meta('anthropic')))->withSteps(collect([ new Step('Deleted b.', [], [], FinishReason::Stop, new TextUsage, new Meta, '', [['type' => 'thinking', 'signature' => 'sig-2'], ['type' => 'text', 'text' => 'Deleted b.']]), @@ -945,7 +947,7 @@ public function testATurnThatPausesAgainKeepsTheReplayBlocksOfTheRowsItResumed() ), ], [], ['provider' => 'anthropic']); - $prompt = new AgentPrompt(new ToolUsingAgent, '', [], m::mock(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); + $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); $response = (new AgentResponse('invocation-id', '', new TextUsage, new Meta('anthropic'))) ->withSteps(collect([ @@ -978,7 +980,7 @@ public function testAResumeFoldsIntoThePausedRowHoldingItsDecidedCallRatherThanT assistantStep([['id' => 'call-2', 'name' => 'delete_file', 'arguments' => ['path' => 'b']]]), ], ['call-2' => 'Deletes b file'], ['provider' => 'anthropic']); - $prompt = new AgentPrompt(new ToolUsingAgent, '', [], m::mock(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); + $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true])); $response = (new AgentResponse('invocation-id', 'Deleted a.', new TextUsage, new Meta('anthropic')))->withSteps(collect([ new Step('Deleted a.', [], [], FinishReason::Stop, new TextUsage, new Meta, '', []), @@ -1082,7 +1084,7 @@ public function testItWritesTheStepsOfAPausedTurnWithTheirReplayBlocksAndKeepsRe new ToolUsingAgent, 'Delete config/app.php.', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -1125,7 +1127,7 @@ public function testItWritesTheStepsAPausedStreamCarriedOnItsApprovalRequest(): new ToolUsingAgent, 'Delete config/app.php.', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -1158,7 +1160,7 @@ public function testItWritesTheStepsACompletedStreamCarriedOnItsStreamEnd(): voi new ToolUsingAgent, 'Read config/app.php.', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -1650,7 +1652,7 @@ public function testItRecordsNoReasoningOnTheTurnStepsWhenTheModelDidNotReason() new ToolUsingAgent, 'How cold is it?', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -1674,7 +1676,7 @@ public function testItRecordsTheSourcesAStreamedTurnCitedIntoTheMessageMeta(): v new ToolUsingAgent, 'What does Hypervel MCP do?', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -1704,7 +1706,7 @@ public function testItStoresNoSourcesWhenAStreamedTurnCitedNothing(): void new ToolUsingAgent, 'How cold is it?', [], - m::mock(TextProvider::class), + Double::for(TextProvider::class), 'test-model', ); @@ -1769,7 +1771,7 @@ public function testProviderReasoningStateIsKeptOnTheStepReplayBlocksRatherThanC { $store = new DatabaseConversationStore; $conversationId = $store->storeConversation('user', 1, 'Reasoning conversation'); - $prompt = new AgentPrompt(new ToolUsingAgent, 'Look it up', [], m::mock(TextProvider::class), 'test-model'); + $prompt = new AgentPrompt(new ToolUsingAgent, 'Look it up', [], Double::for(TextProvider::class), 'test-model'); $reasoningItem = ['type' => 'reasoning', 'id' => 'rs_1', 'summary' => [], 'encrypted_content' => 'enc-blob-1']; @@ -1823,7 +1825,7 @@ public function testProviderToolCallsAreStoredPerStepAndExposedOnTheStoredMessag { $store = new DatabaseConversationStore; $conversationId = $store->storeConversation('user', 1, 'Search conversation'); - $prompt = new AgentPrompt(new ToolUsingAgent, 'Search', [], m::mock(TextProvider::class), 'test-model'); + $prompt = new AgentPrompt(new ToolUsingAgent, 'Search', [], Double::for(TextProvider::class), 'test-model'); $search = new ProviderToolCall('ws-1', 'web_search_call', ['action' => ['query' => 'hypervel ai']]); $execution = new ProviderToolCall('ce-1', 'code_interpreter_call', ['code' => 'print(1)']); @@ -2363,7 +2365,7 @@ private function claimedPrompt(DatabaseConversationStore $store, string $convers */ private function prompt(?Decisions $decisions = null): AgentPrompt { - return new AgentPrompt(new AnonymousAgent('', [], []), 'Hello', [], m::mock(TextProvider::class), 'model', approvalDecisions: $decisions); + return new AgentPrompt(new AnonymousAgent('', [], []), 'Hello', [], Double::for(TextProvider::class), 'model', approvalDecisions: $decisions); } /** diff --git a/tests/Ai/Feature/StoreFakeTest.php b/tests/Ai/Feature/StoreFakeTest.php index 1da543f931..6d7044bc0e 100644 --- a/tests/Ai/Feature/StoreFakeTest.php +++ b/tests/Ai/Feature/StoreFakeTest.php @@ -23,7 +23,9 @@ use Hypervel\Support\Collection; use Hypervel\Tests\Ai\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\AssertionFailedError; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; @@ -32,6 +34,8 @@ class StoreFakeTest extends TestCase { + use VerifiesDoubles; + public function testStoreOperationsAcceptProviderEnums(): void { Stores::fake(); @@ -334,15 +338,15 @@ public function testCanAssertFileNotRemovedFromStore(): void public function testFileOperationsUseTheCapturedProvider(): void { - $provider = m::mock(FileProvider::class, StoreProvider::class); - $provider->shouldReceive('name')->andReturn('unregistered'); + $provider = Double::for(FileProvider::class, StoreProvider::class); + $provider->allows('name')->returns('unregistered'); $file = Document::fromString('Hello, world!', 'text/plain'); $stored = new StoredFileResponse('file_123'); - $provider->shouldReceive('putFile')->once()->with($file)->andReturn($stored); - $provider->shouldReceive('addFileToStore')->once()->with('store_123', $stored, [])->andReturn('document_456'); - $provider->shouldReceive('removeFileFromStore')->once()->with('store_123', m::type(AddedDocumentResponse::class))->andReturnTrue(); - $provider->shouldReceive('deleteFile')->once()->with('file_123'); + $provider->expects('putFile')->with(Argument::same($file))->returns($stored); + $provider->expects('addFileToStore')->with('store_123', Argument::same($stored), [])->returns('document_456'); + $provider->expects('removeFileFromStore')->with('store_123', Argument::type(AddedDocumentResponse::class))->returns(true); + $provider->expects('deleteFile')->with('file_123'); $store = new Store($provider, 'store_123', 'My Store', new StoreFileCounts(0, 0, 0), true); $document = $store->add($file); diff --git a/tests/Ai/Feature/StreamEventBroadcastTest.php b/tests/Ai/Feature/StreamEventBroadcastTest.php index 80c7755b74..15d64911bb 100644 --- a/tests/Ai/Feature/StreamEventBroadcastTest.php +++ b/tests/Ai/Feature/StreamEventBroadcastTest.php @@ -11,17 +11,20 @@ use Hypervel\Broadcasting\Channel; use Hypervel\Support\Facades\Event; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class StreamEventBroadcastTest extends TestCase { + use VerifiesDoubles; + public function testAgentsBroadcastImmediatelyUnlessQueueingIsRequested(): void { Event::fake([AnonymousEvent::class]); $event = new TextDelta('event', 'message', 'Hello', 1); - $agent = m::mock(AnonymousAgent::class, ['', [], []])->makePartial(); - $agent->shouldReceive('stream')->twice()->andReturnUsing(fn (): StreamableAgentResponse => new StreamableAgentResponse('invocation', fn (): array => [$event])); + $agent = Double::for(new AnonymousAgent('', [], []))->passthru(); + $agent->expects('stream')->times(2)->resolves(fn (): StreamableAgentResponse => new StreamableAgentResponse('invocation', fn (): array => [$event])); $agent->broadcast('Hello', new Channel('conversation')); $agent->broadcast('Hello', new Channel('conversation'), now: false); diff --git a/tests/Ai/Feature/ToolRequestValidationTest.php b/tests/Ai/Feature/ToolRequestValidationTest.php index e8ba72fdac..3096db4441 100644 --- a/tests/Ai/Feature/ToolRequestValidationTest.php +++ b/tests/Ai/Feature/ToolRequestValidationTest.php @@ -16,10 +16,13 @@ use Hypervel\Events\Dispatcher; use Hypervel\Tests\Ai\TestCase; use Hypervel\Validation\ValidationException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ToolRequestValidationTest extends TestCase { + use VerifiesDoubles; + public function testToolRequestArgumentsCanBeValidated(): void { $validated = (new Request(['city' => 'Lisbon', 'extra' => 'ignored']))->validate([ @@ -91,8 +94,8 @@ public function schema(JsonSchema $schema): array $context = new RunContext( 'inv_1', - m::mock(Agent::class), - m::mock(TextProvider::class), + Double::for(Agent::class), + Double::for(TextProvider::class), 'stub-model', $events, ); diff --git a/tests/Ai/Fixtures/Tools/ApprovableNamedTool.php b/tests/Ai/Fixtures/Tools/ApprovableNamedTool.php new file mode 100644 index 0000000000..ad75641e05 --- /dev/null +++ b/tests/Ai/Fixtures/Tools/ApprovableNamedTool.php @@ -0,0 +1,11 @@ +withServer('concurrent', function (WebClient $client): void { @@ -87,16 +90,16 @@ public function testCancelingTheAiOperationClosesItsPendingMcpResponses(): void */ private function generate(Client $client, bool $completes = true): TextResponse { - $gateway = m::mock(StepTextGateway::class); - $gateway->shouldReceive('generateTextStep')->times($completes ? 2 : 1)->andReturn( + $gateway = Double::for(StepTextGateway::class); + $gateway->expects('generateTextStep')->times($completes ? 2 : 1)->returns( new StepResponse('', [ new ToolCall('first-call', 'mcp_tools_first', []), new ToolCall('second-call', 'mcp_tools_second', []), ], FinishReason::ToolCalls, new TextUsage, new Meta), new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta), ); - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('local-test'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('local-test'); $tools = array_map(static fn (string $name): McpTool => new McpTool(Tool::from($client, [ 'name' => $name, 'inputSchema' => ['type' => 'object'], diff --git a/tests/Ai/PartitionStoreTest.php b/tests/Ai/PartitionStoreTest.php index defb767f13..bd183e63b0 100644 --- a/tests/Ai/PartitionStoreTest.php +++ b/tests/Ai/PartitionStoreTest.php @@ -27,13 +27,15 @@ use Hypervel\Support\Facades\DB; use Hypervel\Support\Str; use Hypervel\Testbench\Attributes\WithConfig; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; #[WithConfig('database.connections.testing.foreign_key_constraints', true)] class PartitionStoreTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; private const string ACCOUNT_A = '00000000-0000-4000-8000-000000000001'; @@ -146,7 +148,7 @@ public function testATurnCannotAppendToAnotherPartitionsConversation(): void */ private function prompt(?Decisions $decisions = null): AgentPrompt { - return new AgentPrompt(new AnonymousAgent('', [], []), 'Hello', [], m::mock(TextProvider::class), 'model', approvalDecisions: $decisions); + return new AgentPrompt(new AnonymousAgent('', [], []), 'Hello', [], Double::for(TextProvider::class), 'model', approvalDecisions: $decisions); } /** diff --git a/tests/Ai/Unit/Gateway/InvokesToolsTest.php b/tests/Ai/Unit/Gateway/InvokesToolsTest.php index 90795d5c3d..f9fc26c24a 100644 --- a/tests/Ai/Unit/Gateway/InvokesToolsTest.php +++ b/tests/Ai/Unit/Gateway/InvokesToolsTest.php @@ -19,7 +19,8 @@ use Hypervel\Events\Dispatcher; use Hypervel\JsonSchema\Types\Type; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Stringable; @@ -82,8 +83,8 @@ function stubRunContext(Dispatcher $events, string $invocationId = 'inv_1'): Run { return new RunContext( $invocationId, - m::mock(Agent::class), - m::mock(TextProvider::class), + Double::for(Agent::class), + Double::for(TextProvider::class), 'stub-model', $events, ); @@ -91,6 +92,8 @@ function stubRunContext(Dispatcher $events, string $invocationId = 'inv_1'): Run class InvokesToolsTest extends TestCase { + use VerifiesDoubles; + public function testEachToolInvocationReportsAgainstTheContextItWasGiven(): void { $seen = []; diff --git a/tests/Ai/Unit/Gateway/OpenAi/AudioFilenameTest.php b/tests/Ai/Unit/Gateway/OpenAi/AudioFilenameTest.php index 58f68ea862..562ff44cdd 100644 --- a/tests/Ai/Unit/Gateway/OpenAi/AudioFilenameTest.php +++ b/tests/Ai/Unit/Gateway/OpenAi/AudioFilenameTest.php @@ -7,14 +7,13 @@ use Hypervel\Ai\Contracts\Files\TranscribableAudio; use Hypervel\Ai\Files\Base64Audio; use Hypervel\Ai\Gateway\OpenAi\OpenAiGateway; -use Hypervel\Contracts\Events\Dispatcher; +use Hypervel\Events\Dispatcher; use Hypervel\Tests\TestCase; -use Mockery as m; use ReflectionMethod; function callAudioFilename(TranscribableAudio $audio): string { - $gateway = new OpenAiGateway(m::mock(Dispatcher::class)); + $gateway = new OpenAiGateway(new Dispatcher); $method = new ReflectionMethod($gateway, 'audioFilename'); diff --git a/tests/Ai/Unit/Gateway/RunContextTest.php b/tests/Ai/Unit/Gateway/RunContextTest.php index 451ef5f52d..01ca40b5db 100644 --- a/tests/Ai/Unit/Gateway/RunContextTest.php +++ b/tests/Ai/Unit/Gateway/RunContextTest.php @@ -21,11 +21,14 @@ use Hypervel\Ai\Responses\Data\TextUsage; use Hypervel\Events\Dispatcher; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class RunContextTest extends TestCase { + use VerifiesDoubles; + public function testStepAndToolEventsRequireInterestedListeners(): void { $events = new Dispatcher; @@ -33,10 +36,10 @@ public function testStepAndToolEventsRequireInterestedListeners(): void $events->listen('*', function (string $name) use (&$observed): void { $observed[] = $name; }); - $context = new RunContext('invocation', m::mock(Agent::class), m::mock(TextProvider::class), 'model', $events); + $context = new RunContext('invocation', Double::for(Agent::class), Double::for(TextProvider::class), 'model', $events); $step = new StepContext; $response = new StepResponse('Answer', [], FinishReason::Stop, new TextUsage, new Meta); - $tool = m::mock(Tool::class); + $tool = Double::for(Tool::class); $exception = new RuntimeException('Failed'); $report = static function () use ($context, $step, $response, $tool, $exception): void { $context->startingStep($step, [], null); diff --git a/tests/Ai/Unit/Gateway/TextGenerationLoopTest.php b/tests/Ai/Unit/Gateway/TextGenerationLoopTest.php index fea2f5be0d..0778a799b2 100644 --- a/tests/Ai/Unit/Gateway/TextGenerationLoopTest.php +++ b/tests/Ai/Unit/Gateway/TextGenerationLoopTest.php @@ -64,9 +64,13 @@ use Hypervel\Ai\Tools\Request; use Hypervel\Contracts\JsonSchema\JsonSchema; use Hypervel\Events\Dispatcher; +use Hypervel\Tests\Ai\Fixtures\Tools\ApprovableNamedTool; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -75,6 +79,8 @@ class TextGenerationLoopTest extends TestCase { + use VerifiesDoubles; + public function testItPausesGatedToolCallsWithoutExecutingThemWhileRunningUngatedCallsImmediately(): void { $gated = new TextGenerationLoopApprovableTool; @@ -1146,8 +1152,8 @@ public function testItDropsProviderToolsTheProviderDoesNotSupportBeforeCallingTh $regular = new TextGenerationLoopCountingTool; $webSearch = new WebSearch; - $provider = m::mock(TextProvider::class, SupportsWebSearch::class); - $provider->shouldReceive('name')->andReturn('fake'); + $provider = Double::for(TextProvider::class, SupportsWebSearch::class); + $provider->allows('name')->returns('fake'); (new TextGenerationLoop($gateway))->generate( $provider, @@ -1400,15 +1406,15 @@ public function testPreliminarySnapshotsStayBoundedWhenTextAndReasoningAlternate public function testASubAgentRunsSynchronouslyThroughTheNonStreamingLoop(): void { - $agent = m::mock(Agent::class, CanActAsTool::class); - $agent->shouldReceive('name')->andReturn('research_agent'); - $agent->shouldReceive('prompt')->once()->andReturn(new AgentResponse( + $agent = Double::for(Agent::class, CanActAsTool::class); + $agent->allows('name')->returns('research_agent'); + $agent->expects('prompt')->returns(new AgentResponse( 'sub-invocation', 'synchronous result', new TextUsage(3, 4), new Meta('fake', 'sub-model') )); - $agent->shouldNotReceive('stream'); + $agent->expects('stream')->never(); $toolCall = new ToolCall('call-sub-agent', 'research_agent', ['task' => 'Research'], 'call-sub-agent'); $gateway = new TextGenerationLoopFakeGateway([ @@ -1435,10 +1441,10 @@ public function testAStructuredSubAgentAnswersThroughARegularPromptInTheStreamed { $parent = null; - $agent = m::mock(Agent::class, CanActAsTool::class, HasStructuredOutput::class); - $agent->shouldReceive('name')->andReturn('research_agent'); - $agent->shouldNotReceive('stream'); - $agent->shouldReceive('prompt')->once()->andReturnUsing(function () use (&$parent): StructuredAgentResponse { + $agent = Double::for(Agent::class, CanActAsTool::class, HasStructuredOutput::class); + $agent->allows('name')->returns('research_agent'); + $agent->expects('stream')->never(); + $agent->expects('prompt')->resolves(function () use (&$parent): StructuredAgentResponse { $parent = ParentInvocation::current(); return new StructuredAgentResponse( @@ -1462,7 +1468,7 @@ public function testAStructuredSubAgentAnswersThroughARegularPromptInTheStreamed textGenerationLoopSubAgentStream([new AgentTool($agent)], [$toolCall], context: new RunContext( 'invocation-1', - m::mock(Agent::class), + Double::for(Agent::class), textGenerationLoopProvider(), 'model', $dispatcher, @@ -1475,10 +1481,10 @@ public function testAStructuredSubAgentAnswersThroughARegularPromptInTheStreamed public function testASubAgentIsNotExecutedOnTheFinalStreamedStep(): void { - $agent = m::mock(Agent::class, CanActAsTool::class); - $agent->shouldReceive('name')->andReturn('research_agent'); - $agent->shouldNotReceive('prompt'); - $agent->shouldNotReceive('stream'); + $agent = Double::for(Agent::class, CanActAsTool::class); + $agent->allows('name')->returns('research_agent'); + $agent->expects('prompt')->never(); + $agent->expects('stream')->never(); $toolCall = new ToolCall('call-sub-agent', 'research_agent', ['task' => 'Research'], 'call-sub-agent'); @@ -1523,7 +1529,7 @@ public function testToolInvocationEventsFireAroundASubAgentInTheStreamedLoop(): $events = textGenerationLoopSubAgentStream([$tool], [$toolCall], context: new RunContext( 'invocation-1', - m::mock(Agent::class), + Double::for(Agent::class), $provider, 'model', $dispatcher, @@ -1554,7 +1560,7 @@ public function testASubAgentNamesTheToolCallItWasDelegatedFromForTheWholeOfItsR textGenerationLoopSubAgentStream([$tool], [$toolCall], context: new RunContext( 'invocation-1', - m::mock(Agent::class), + Double::for(Agent::class), $provider, 'model', new Dispatcher, @@ -1587,31 +1593,31 @@ public function testAGatedToolPausesTheStreamedLoopWhileASubAgentStillReportsIts public function testEachResultIsPersistedBeforeTheNextToolRuns(): void { $provider = textGenerationLoopProvider(); - $store = m::mock(ClaimsPendingApprovals::class); + $store = Double::for(ClaimsPendingApprovals::class); $claim = new ApprovalClaim('message', 'token'); $recorded = []; $operations = []; - $store->shouldReceive('claimPendingApprovals')->once()->with('conversation', ['first', 'second', 'third']) - ->andReturnUsing(function () use (&$operations, $claim): ApprovalClaim { + $store->expects('claimPendingApprovals')->with('conversation', ['first', 'second', 'third']) + ->resolves(function () use (&$operations, $claim): ApprovalClaim { $operations[] = 'claim'; return $claim; }); - $store->shouldReceive('recordApprovalResult')->times(3)->with($claim, m::type(ToolResultData::class)) - ->andReturnUsing(function (ApprovalClaim $claim, ToolResultData $result) use (&$operations, &$recorded): void { + $store->expects('recordApprovalResult')->times(3)->with(Argument::same($claim), Argument::type(ToolResultData::class)) + ->resolves(function (ApprovalClaim $claim, ToolResultData $result) use (&$operations, &$recorded): void { $operations[] = 'record:' . $result->id; $recorded[$result->id] = $result; }); $tool = $this->approvalTool(); - $tool->shouldReceive('handle')->twice()->andReturnUsing(function (Request $request) use (&$operations): string { + $tool->expects('handle')->times(2)->resolves(function (Request $request) use (&$operations): string { $operations[] = 'execute:' . $request->toolCallId(); return 'done'; }); - $gateway = m::mock(StepTextGateway::class); - $gateway->shouldReceive('generateTextStep')->once()->andReturn(new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta)); - $context = (new RunContext('invocation', m::mock(Agent::class), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation'); + $gateway = Double::for(StepTextGateway::class); + $gateway->expects('generateTextStep')->returns(new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta)); + $context = (new RunContext('invocation', Double::for(Agent::class), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation'); (new TextGenerationLoop($gateway))->generate( $provider, @@ -1637,14 +1643,14 @@ public function testEachResultIsPersistedBeforeTheNextToolRuns(): void public function testAnUnavailableClaimPreventsToolExecution(): void { $provider = textGenerationLoopProvider(); - $gateway = m::mock(StepTextGateway::class); - $gateway->shouldReceive('generateTextStep')->andReturn(new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta)); - $store = m::mock(ClaimsPendingApprovals::class); - $store->shouldReceive('claimPendingApprovals')->once()->with('conversation', ['call'])->andReturnNull(); - $store->shouldNotReceive('recordApprovalResult'); + $gateway = Double::for(StepTextGateway::class); + $gateway->allows('generateTextStep')->returns(new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta)); + $store = Double::for(ClaimsPendingApprovals::class); + $store->expects('claimPendingApprovals')->with('conversation', ['call'])->returns(null); + $store->expects('recordApprovalResult')->never(); $tool = $this->approvalTool(); - $tool->shouldNotReceive('handle'); - $context = (new RunContext('invocation', m::mock(Agent::class), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation'); + $tool->expects('handle')->never(); + $context = (new RunContext('invocation', Double::for(Agent::class), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation'); $this->expectException(ApprovalMismatchException::class); @@ -1664,19 +1670,19 @@ public function testAnUnavailableClaimPreventsToolExecution(): void public function testCancellationIsNotRecordedAsACompletedToolFailure(bool $cleanupThrows): void { $provider = textGenerationLoopProvider(); - $gateway = m::mock(StepTextGateway::class); - $gateway->shouldNotReceive('generateTextStep'); - $store = m::mock(ClaimsPendingApprovals::class); + $gateway = Double::for(StepTextGateway::class); + $gateway->expects('generateTextStep')->never(); + $store = Double::for(ClaimsPendingApprovals::class); $claim = new ApprovalClaim('message', 'token'); - $store->shouldReceive('claimPendingApprovals')->once()->with('conversation', ['call', 'next'])->andReturn($claim); - $store->shouldNotReceive('recordApprovalResult'); + $store->expects('claimPendingApprovals')->with('conversation', ['call', 'next'])->returns($claim); + $store->expects('recordApprovalResult')->never(); $exception = new CanceledException('Canceled while executing the approved tool.'); if ($cleanupThrows) { $exception = new RuntimeException('Tool cleanup failed.', previous: $exception); } $tool = $this->approvalTool(); - $tool->shouldReceive('handle')->once()->andThrow($exception); - $context = (new RunContext('invocation', m::mock(Agent::class), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation'); + $tool->expects('handle')->throws($exception); + $context = (new RunContext('invocation', Double::for(Agent::class), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation'); try { (new TextGenerationLoop($gateway))->generate( @@ -1699,11 +1705,11 @@ public function testCancellationIsNotRecordedAsACompletedToolFailure(bool $clean /** * Create an approval-gated tool for the execution loop. */ - private function approvalTool(): Tool&Approvable&m\MockInterface + private function approvalTool(): Tool&Approvable&DoubleInterface { - $tool = m::mock(Tool::class, Approvable::class); - $tool->shouldReceive('name')->andReturn('tool'); - $tool->shouldReceive('shouldRequestApproval')->andReturn(Approval::required()); + $tool = Double::for(ApprovableNamedTool::class); + $tool->allows('name')->returns('tool'); + $tool->allows('shouldRequestApproval')->returns(Approval::required()); return $tool; } @@ -1714,8 +1720,8 @@ private function approvalTool(): Tool&Approvable&m\MockInterface */ function textGenerationLoopProvider(): TextProvider { - $provider = m::mock(TextProvider::class); - $provider->shouldReceive('name')->andReturn('fake'); + $provider = Double::for(TextProvider::class); + $provider->allows('name')->returns('fake'); return $provider; } @@ -1725,8 +1731,8 @@ function textGenerationLoopProvider(): TextProvider */ function textGenerationLoopToolSearchProvider(): TextProvider { - $provider = m::mock(TextProvider::class, SupportsToolSearch::class); - $provider->shouldReceive('name')->andReturn('fake'); + $provider = Double::for(TextProvider::class, SupportsToolSearch::class); + $provider->allows('name')->returns('fake'); return $provider; } @@ -1926,10 +1932,10 @@ protected function approvalAwareToolResults(array $toolCalls, array $tools, bool */ function textGenerationLoopAgentTool(Closure|string $text = 'sub-agent result'): AgentTool { - $agent = m::mock(Agent::class, CanActAsTool::class); - $agent->shouldReceive('name')->andReturn('research_agent'); - $agent->shouldNotReceive('prompt'); - $agent->shouldReceive('stream')->atLeast()->once()->andReturnUsing(fn (): StreamableAgentResponse => new StreamableAgentResponse( + $agent = Double::for(Agent::class, CanActAsTool::class); + $agent->allows('name')->returns('research_agent'); + $agent->expects('prompt')->never(); + $agent->expects('stream')->times(minimum: 1)->resolves(fn (): StreamableAgentResponse => new StreamableAgentResponse( 'sub-invocation', $text instanceof Closure ? $text : fn (): Generator => yield from [ (new TextDelta('sub-delta', 'sub-message', $text, time()))->withInvocationId('sub-invocation'), diff --git a/tests/Ai/Unit/Tools/AgentToolTest.php b/tests/Ai/Unit/Tools/AgentToolTest.php index c621e0ff46..ccebbbd4ec 100644 --- a/tests/Ai/Unit/Tools/AgentToolTest.php +++ b/tests/Ai/Unit/Tools/AgentToolTest.php @@ -18,7 +18,8 @@ use Hypervel\Support\Facades\Exceptions; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Tests\Ai\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -26,6 +27,8 @@ class AgentToolTest extends TestCase { + use VerifiesDoubles; + public function testAnAgentToolStreamsItsEventsByDefaultAndReturnsItsFinalText(): void { $stream = new StreamableAgentResponse('invocation-sub', fn (): Generator => yield from [ @@ -33,9 +36,9 @@ public function testAnAgentToolStreamsItsEventsByDefaultAndReturnsItsFinalText() new StreamEnd('event-2', 'stop', new TextUsage, time()), ], new Meta('fake', 'model')); - $agent = m::mock(Agent::class); - $agent->shouldReceive('stream')->once()->with('Do the thing')->andReturn($stream); - $agent->shouldNotReceive('prompt'); + $agent = Double::for(Agent::class); + $agent->expects('stream')->with('Do the thing')->returns($stream); + $agent->expects('prompt')->never(); $generator = (new AgentTool($agent))->stream(new Request(['task' => 'Do the thing'])); @@ -48,9 +51,9 @@ public function testAnAgentToolStreamsItsEventsByDefaultAndReturnsItsFinalText() public function testAStructuredSubAgentAnswersThroughARegularPromptOnTheStreamingPath(): void { - $agent = m::mock(Agent::class, HasStructuredOutput::class); - $agent->shouldNotReceive('stream'); - $agent->shouldReceive('prompt')->once()->andReturn(new StructuredAgentResponse( + $agent = Double::for(Agent::class, HasStructuredOutput::class); + $agent->expects('stream')->never(); + $agent->expects('prompt')->returns(new StructuredAgentResponse( 'invocation-sub', ['answer' => 42], '{"answer":42}', @@ -70,8 +73,8 @@ public function testAFailingSubAgentSurfacesItsErrorAsTheToolResultOnTheStreamin Exceptions::fake(); $exception = new RuntimeException('provider exploded'); - $agent = m::mock(Agent::class); - $agent->shouldReceive('stream')->once()->andThrow($exception); + $agent = Double::for(Agent::class); + $agent->expects('stream')->throws($exception); $generator = (new AgentTool($agent))->stream(new Request(['task' => 'Do the thing'])); @@ -89,9 +92,9 @@ public function testAFailingPromptedSubAgentIsReportedOnceAndHidesItsErrorOutsid Exceptions::fake(); $exception = new RuntimeException('provider exploded'); - $agent = $structuredStream ? m::mock(Agent::class, HasStructuredOutput::class) : m::mock(Agent::class); - $agent->shouldNotReceive('stream'); - $agent->shouldReceive('prompt')->once()->andThrow($exception); + $agent = $structuredStream ? Double::for(Agent::class, HasStructuredOutput::class) : Double::for(Agent::class); + $agent->expects('stream')->never(); + $agent->expects('prompt')->throws($exception); $tool = new AgentTool($agent); $request = new Request(['task' => 'Do the thing']); @@ -127,16 +130,16 @@ public function testCancellationEscapesTheSubAgent(bool $streaming, bool $cleanu if ($cleanupThrows) { $exception = new RuntimeException('Sub-agent cleanup failed.', previous: $exception); } - $agent = m::mock(Agent::class); + $agent = Double::for(Agent::class); if ($streaming) { - $agent->shouldReceive('stream')->once()->andReturn(new StreamableAgentResponse('invocation', function () use ($exception): Generator { + $agent->expects('stream')->returns(new StreamableAgentResponse('invocation', function () use ($exception): Generator { yield new TextDelta('event', 'message', 'Partial', time()); throw $exception; })); } else { - $agent->shouldReceive('prompt')->once()->andThrow($exception); + $agent->expects('prompt')->throws($exception); } $tool = new AgentTool($agent); diff --git a/tests/ApiClient/ApiRequestTest.php b/tests/ApiClient/ApiRequestTest.php index f09320b141..d4b86fd2dd 100644 --- a/tests/ApiClient/ApiRequestTest.php +++ b/tests/ApiClient/ApiRequestTest.php @@ -9,13 +9,16 @@ use Hypervel\Http\Client\Request as HttpRequest; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\StreamInterface; class ApiRequestTest extends TestCase { + use VerifiesDoubles; + private ApiRequest $request; protected function setUp(): void @@ -359,8 +362,8 @@ public function testWithUserAgent(): void public function testCreateFromPreservesDataAndAttributes(): void { - $body = m::mock(StreamInterface::class); - $body->shouldReceive('__toString')->once()->andReturn('[]'); + $body = Double::for(StreamInterface::class); + $body->expects('__toString')->returns('[]'); $request = (new HttpRequest(new Psr7Request( 'POST', 'https://api.example.com', diff --git a/tests/ApiClient/ApiResourceTest.php b/tests/ApiClient/ApiResourceTest.php index 8ef587938c..93d50d2f91 100644 --- a/tests/ApiClient/ApiResourceTest.php +++ b/tests/ApiClient/ApiResourceTest.php @@ -4,28 +4,25 @@ namespace Hypervel\Tests\ApiClient; -use BadMethodCallException; +use Error; use GuzzleHttp\Psr7\Response as Psr7Response; use Hypervel\ApiClient\ApiRequest; use Hypervel\ApiClient\ApiResource; use Hypervel\ApiClient\ApiResponse; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; use LogicException; -use Mockery as m; -use Mockery\MockInterface; class ApiResourceTest extends TestCase { - /** - * @var ApiResponse&MockInterface - */ - private $response; + use VerifiesDoubles; - /** - * @var ApiRequest&MockInterface - */ - private $request; + private ApiResponse&DoubleInterface $response; + + private ApiRequest&DoubleInterface $request; private ApiResource $resource; @@ -33,10 +30,9 @@ protected function setUp(): void { parent::setUp(); - $this->response = m::mock(ApiResponse::class); - $this->request = m::mock(ApiRequest::class); + $this->response = Double::for(ApiResponse::class); + $this->request = Double::for(ApiRequest::class); - // Create the resource with our mocks $this->resource = new ApiResource($this->response, $this->request); } @@ -52,8 +48,8 @@ public function testMakeFactoryMethod(): void public function testToString(): void { $this->response - ->shouldReceive('body') - ->andReturn($responseBody = '{"key": "value"}'); + ->expects('body') + ->returns($responseBody = '{"key": "value"}'); $this->assertEquals($responseBody, (string) $this->resource); } @@ -61,8 +57,8 @@ public function testToString(): void public function testResolve(): void { $this->response - ->shouldReceive('toArray') - ->andReturn($jsonData = ['key' => 'value']); + ->expects('toArray') + ->returns($jsonData = ['key' => 'value']); $this->assertEquals($jsonData, $this->resource->resolve()); } @@ -70,8 +66,8 @@ public function testResolve(): void public function testToArray(): void { $this->response - ->shouldReceive('toArray') - ->andReturn($jsonData = ['key' => 'value']); + ->expects('toArray') + ->returns($jsonData = ['key' => 'value']); $this->assertEquals($jsonData, $this->resource->toArray()); } @@ -79,15 +75,15 @@ public function testToArray(): void public function testJsonSerialize(): void { $this->response - ->shouldReceive('toArray') - ->andReturn($jsonData = ['key' => 'value']); + ->expects('toArray') + ->returns($jsonData = ['key' => 'value']); $this->assertEquals($jsonData, $this->resource->jsonSerialize()); } public function testToJsonThrowsForInvalidUtf8(): void { - $this->response->shouldReceive('toArray')->once()->andReturn(['value' => "\xB1\x31"]); + $this->response->expects('toArray')->returns(['value' => "\xB1\x31"]); $this->expectException(JsonException::class); @@ -96,7 +92,7 @@ public function testToJsonThrowsForInvalidUtf8(): void public function testToJsonHonorsInvalidUtf8Substitution(): void { - $this->response->shouldReceive('toArray')->once()->andReturn(['value' => "\xB1\x31"]); + $this->response->expects('toArray')->returns(['value' => "\xB1\x31"]); $this->assertSame( '{"value":"\ufffd1"}', @@ -106,7 +102,7 @@ public function testToJsonHonorsInvalidUtf8Substitution(): void public function testToPrettyJsonPreservesCallerOptions(): void { - $this->response->shouldReceive('toArray')->once()->andReturn(['value' => '/path']); + $this->response->expects('toArray')->returns(['value' => '/path']); $this->assertSame( "{\n \"value\": \"/path\"\n}", @@ -116,18 +112,18 @@ public function testToPrettyJsonPreservesCallerOptions(): void public function testArrayAccessOffsetExists(): void { - $this->response->shouldReceive('offsetExists') + $this->response->expects('offsetExists') ->with('key') - ->andReturn(true); + ->returns(true); $this->assertTrue($this->resource->offsetExists('key')); } public function testArrayAccessOffsetGet(): void { - $this->response->shouldReceive('offsetGet') + $this->response->expects('offsetGet') ->with('key') - ->andReturn($value = 'someValue'); + ->returns($value = 'someValue'); $this->assertEquals($value, $this->resource->offsetGet('key')); } @@ -151,8 +147,8 @@ public function testArrayAccessOffsetUnsetIsRejected(): void public function testMagicIssetMethod(): void { $this->response - ->shouldReceive('json') - ->andReturn($jsonData = ['existingKey' => 'value']); + ->expects('json')->times(2) + ->returns($jsonData = ['existingKey' => 'value']); $this->assertTrue(isset($this->resource->existingKey)); $this->assertFalse(isset($this->resource->nonExistingKey)); @@ -176,11 +172,10 @@ public function testMagicPropertyUnsetIsRejected(): void public function testMagicGetMethod(): void { - $this->response->shouldReceive('offsetGet') + $this->response->expects('offsetGet') ->with('key') - ->andReturn($value = 'value'); + ->returns($value = 'value'); - /* @phpstan-ignore-next-line */ $this->assertEquals($value, $this->resource->key); } @@ -197,8 +192,8 @@ public function testMissingArrayAndPropertyValuesReturnNull(): void public function testCallMethodOnResponse(): void { - $this->response->shouldReceive('status') - ->andReturn($expectedResult = 200); + $this->response->expects('status') + ->returns($expectedResult = 200); $this->assertEquals($expectedResult, $this->resource->status()); } @@ -217,9 +212,11 @@ public function testCallForwardsResponseMacrosAndPsrMethods(): void public function testCallNonExistentMethodThrowsException(): void { - $this->expectException(BadMethodCallException::class); + $resource = new ApiResource(new ApiResponse(new Psr7Response), $this->request); + + $this->expectException(Error::class); + $this->expectExceptionMessageIs('Call to undefined method GuzzleHttp\Psr7\Response::nonExistentMethod()'); - /* @phpstan-ignore-next-line */ - $this->resource->nonExistentMethod(); + $resource->nonExistentMethod(); } } diff --git a/tests/Auth/AuthAccessGateTest.php b/tests/Auth/AuthAccessGateTest.php index 72a80edbe8..63e0563755 100644 --- a/tests/Auth/AuthAccessGateTest.php +++ b/tests/Auth/AuthAccessGateTest.php @@ -21,12 +21,16 @@ use Hypervel\Tests\Auth\Fixtures\SubDummyWithUsePolicy; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use stdClass; class AuthAccessGateTest extends TestCase { + use VerifiesDoubles; + public function testBasicClosuresCanBeDefined(): void { $gate = $this->getBasicGate(); @@ -1561,9 +1565,9 @@ public function testCanSetDenialResponse(): void public function testGateEvaluationSkipsDispatchWhenThereAreNoListeners(): void { $container = new Container; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(GateEvaluated::class)->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(GateEvaluated::class)->returns(false); + $events->expects('dispatch')->never(); $container->instance(Dispatcher::class, $events); $gate = new Gate($container, fn () => new stdClass); @@ -1575,11 +1579,10 @@ public function testGateEvaluationSkipsDispatchWhenThereAreNoListeners(): void public function testGateEvaluationDispatchesWhenThereIsAListener(): void { $container = new Container; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(GateEvaluated::class)->andReturnTrue(); - $events->shouldReceive('dispatch') - ->once() - ->with(m::on(fn (GateEvaluated $event): bool => $event->ability === 'allowed')); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(GateEvaluated::class)->returns(true); + $events->expects('dispatch') + ->with(Argument::satisfies(fn (GateEvaluated $event): bool => $event->ability === 'allowed')); $container->instance(Dispatcher::class, $events); $gate = new Gate($container, fn () => new stdClass); diff --git a/tests/Auth/AuthDatabaseTokenRepositoryTest.php b/tests/Auth/AuthDatabaseTokenRepositoryTest.php index e24fa604d1..def26ff07f 100755 --- a/tests/Auth/AuthDatabaseTokenRepositoryTest.php +++ b/tests/Auth/AuthDatabaseTokenRepositoryTest.php @@ -16,11 +16,15 @@ use Hypervel\Hashing\BcryptHasher; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDO; class AuthDatabaseTokenRepositoryTest extends TestCase { + use VerifiesDoubles; + public function testCreateInsertsNewRecordIntoTable(): void { $repo = $this->getRepo(); @@ -127,24 +131,24 @@ public function testDeleteExpiredMethodDeletesExpiredTokens(): void public function testResolverBackedRepositoryResolvesTheConfiguredConnectionForEveryOperation(): void { - $firstConnection = m::mock(Connection::class); - $firstQuery = m::mock(Builder::class); - $firstConnection->shouldReceive('table')->once()->with('table')->andReturn($firstQuery); - $firstQuery->shouldReceive('where')->once()->with('created_at', '<', m::any())->andReturnSelf(); - $firstQuery->shouldReceive('delete')->once(); + $firstConnection = Double::for(Connection::class); + $firstQuery = Double::for(Builder::class); + $firstConnection->expects('table')->with('table')->returns($firstQuery); + $firstQuery->expects('where')->with('created_at', '<', Argument::any()); + $firstQuery->expects('delete'); - $secondConnection = m::mock(Connection::class); - $secondQuery = m::mock(Builder::class); - $secondConnection->shouldReceive('table')->once()->with('table')->andReturn($secondQuery); - $secondQuery->shouldReceive('where')->once()->with('created_at', '<', m::any())->andReturnSelf(); - $secondQuery->shouldReceive('delete')->once(); + $secondConnection = Double::for(Connection::class); + $secondQuery = Double::for(Builder::class); + $secondConnection->expects('table')->with('table')->returns($secondQuery); + $secondQuery->expects('where')->with('created_at', '<', Argument::any()); + $secondQuery->expects('delete'); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->twice()->with('passwords')->andReturn($firstConnection, $secondConnection); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->times(2)->with('passwords')->returns($firstConnection, $secondConnection); $repository = new DatabaseTokenRepository( $resolver, - m::mock(Hasher::class), + Double::for(Hasher::class), 'table', 'key', connectionName: 'passwords' @@ -156,24 +160,24 @@ public function testResolverBackedRepositoryResolvesTheConfiguredConnectionForEv public function testResolverBackedRepositoryUsesTheDefaultConnectionWhenNoNameIsConfigured(): void { - $connection = m::mock(Connection::class); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->once()->with(null)->andReturn($connection); + $connection = Double::for(Connection::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with(null)->returns($connection); - $repository = new DatabaseTokenRepository($resolver, m::mock(Hasher::class), 'table', 'key'); + $repository = new DatabaseTokenRepository($resolver, Double::for(Hasher::class), 'table', 'key'); $this->assertSame($connection, $repository->getConnection()); } public function testResolverContractTakesPrecedenceForObjectsImplementingBothConnectionContracts(): void { - $resolvedConnection = m::mock(Connection::class); - $connectionResolver = m::mock(ConnectionInterface::class . ', ' . ConnectionResolverInterface::class); - $connectionResolver->shouldReceive('connection')->once()->with('passwords')->andReturn($resolvedConnection); + $resolvedConnection = Double::for(Connection::class); + $connectionResolver = Double::for(ConnectionInterface::class, ConnectionResolverInterface::class); + $connectionResolver->expects('connection')->with('passwords')->returns($resolvedConnection); $repository = new DatabaseTokenRepository( $connectionResolver, - m::mock(Hasher::class), + Double::for(Hasher::class), 'table', 'key', connectionName: 'passwords' diff --git a/tests/Auth/AuthEloquentUserProviderCacheTest.php b/tests/Auth/AuthEloquentUserProviderCacheTest.php index e15f7c076e..30f4798057 100644 --- a/tests/Auth/AuthEloquentUserProviderCacheTest.php +++ b/tests/Auth/AuthEloquentUserProviderCacheTest.php @@ -15,10 +15,12 @@ use Hypervel\Cache\ModelCacheStoreValidator; use Hypervel\Cache\NullStore; use Hypervel\Cache\RedisStore; +use Hypervel\Cache\Repository; use Hypervel\Cache\SessionStore; use Hypervel\Cache\StackStore; use Hypervel\Cache\StorageStore; use Hypervel\Cache\SwooleStore; +use Hypervel\Cache\TaggedCache; use Hypervel\Container\Container; use Hypervel\Contracts\Auth\Authenticatable; use Hypervel\Contracts\Cache\Repository as CacheRepository; @@ -26,50 +28,54 @@ use Hypervel\Database\Connection; use Hypervel\Database\Eloquent\Builder; use Hypervel\Database\Eloquent\Model; +use Hypervel\Database\Query\Builder as QueryBuilder; +use Hypervel\Foundation\Auth\User; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\MockObject\MockObject; use ReflectionClass; class AuthEloquentUserProviderCacheTest extends TestCase { + use VerifiesDoubles; + protected const string MODEL = EloquentCacheProviderUserStub::class; protected const string DEFAULT_KEY_PREFIX = EloquentUserProvider::DEFAULT_CACHE_PREFIX; - protected MockInterface $cacheManager; + protected CacheManager&DoubleInterface $cacheManager; - protected MockInterface $storeValidator; + protected ModelCacheStoreValidator&DoubleInterface $storeValidator; - protected MockInterface $cacheCoordinator; + protected ModelCacheCoordinator&DoubleInterface $cacheCoordinator; protected function setUp(): void { parent::setUp(); $container = Container::setInstance(new Container); - $this->cacheManager = m::mock(CacheManager::class); - $this->storeValidator = m::mock(ModelCacheStoreValidator::class); - $this->cacheCoordinator = m::mock(ModelCacheCoordinator::class); - $this->storeValidator->shouldReceive('validate')->byDefault(); - $this->storeValidator->shouldReceive('validateAnyModeTags')->byDefault(); + $this->cacheManager = Double::for(CacheManager::class); + $this->storeValidator = Double::for(ModelCacheStoreValidator::class); + $this->cacheCoordinator = Double::for(ModelCacheCoordinator::class); $container->instance('cache', $this->cacheManager); $container->instance(ModelCacheStoreValidator::class, $this->storeValidator); $container->instance(ModelCacheCoordinator::class, $this->cacheCoordinator); } // ------------------------------------------------------------------ - // Cache disabled (default behaviour) + // Cache disabled (default behavior) // ------------------------------------------------------------------ public function testRetrieveByIdWithoutCacheDoesNotTouchCache(): void { - $this->cacheManager->shouldNotReceive('store'); + $this->cacheManager->expects('store')->never(); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $provider = $this->providerExpectingDbFetch($user, 42, useWritePdo: false); $this->assertSame($user, $provider->retrieveById(42)); @@ -82,7 +88,7 @@ public function testRetrieveByIdWithoutCacheDoesNotTouchCache(): void public function testRetrieveByIdCachesMissedLookup(): void { $repo = $this->stubCache(RedisStore::class); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $key = $this->buildDefaultKey(42); $this->expectCoordinatorFill($repo, $key, $user, readSource: true, expectedWriter: $repo); @@ -96,7 +102,7 @@ public function testRetrieveByIdCachesMissedLookup(): void public function testRetrieveByIdReturnsCachedUser(): void { $repo = $this->stubCache(RedisStore::class); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $this->expectCoordinatorFill($repo, $this->buildDefaultKey(42), $user); @@ -134,14 +140,14 @@ public function testRetrieveByIdReturnsNullForCachedNull(): void public function testRetrieveByCredentialsIsNeverCached(): void { $repo = $this->stubCache(RedisStore::class); - $this->cacheCoordinator->shouldNotReceive('fill'); + $this->cacheCoordinator->expects('fill')->never(); - $expectedUser = m::mock(Authenticatable::class); - $model = m::mock(Model::class); - $builder = m::mock(Builder::class); - $model->shouldReceive('newQuery')->once()->andReturn($builder); - $builder->shouldReceive('where')->once()->with('username', 'u'); - $builder->shouldReceive('first')->once()->andReturn($expectedUser); + $expectedUser = Double::for(Authenticatable::class); + $model = Double::for(User::class); + $builder = Double::for(Builder::class); + $model->expects('newQuery')->returns($builder); + $builder->expects('where')->with('username', 'u'); + $builder->expects('first')->returns($expectedUser); $provider = $this->providerMock(); $provider->expects($this->once())->method('createModel')->willReturn($model); @@ -153,16 +159,16 @@ public function testRetrieveByCredentialsIsNeverCached(): void public function testRetrieveByTokenIsNeverCached(): void { $repo = $this->stubCache(RedisStore::class); - $this->cacheCoordinator->shouldNotReceive('fill'); + $this->cacheCoordinator->expects('fill')->never(); - $user = m::mock(Authenticatable::class); - $user->shouldReceive('getRememberToken')->once()->andReturn('tok'); - $model = m::mock(Model::class); - $builder = m::mock(Builder::class); - $model->shouldReceive('newQuery')->once()->andReturn($builder); - $model->shouldReceive('getAuthIdentifierName')->once()->andReturn('id'); - $builder->shouldReceive('where')->once()->with('id', 1)->andReturn($builder); - $builder->shouldReceive('first')->once()->andReturn($user); + $user = Double::for(Authenticatable::class); + $user->expects('getRememberToken')->returns('tok'); + $model = Double::for(User::class); + $builder = Double::for(Builder::class); + $model->expects('newQuery')->returns($builder); + $model->expects('getAuthIdentifierName')->returns('id'); + $builder->expects('where')->with('id', 1)->returns($builder); + $builder->expects('first')->returns($user); $provider = $this->providerMock(); $provider->expects($this->once())->method('createModel')->willReturn($model); @@ -180,7 +186,7 @@ public function testDefaultCacheKeyIncludesFqcnAndIdentifier(): void $repo = $this->stubCache(RedisStore::class); $expectedKey = self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':42'; - $this->expectCoordinatorFill($repo, $expectedKey, m::mock(Authenticatable::class)); + $this->expectCoordinatorFill($repo, $expectedKey, Double::for(Authenticatable::class)); $provider = $this->providerWithoutDbFetch(); $provider->enableCache(null); @@ -193,17 +199,17 @@ public function testEnableCacheNormalizesBlankPrefixToDefault(): void // Two enableCache() calls with blank prefixes (null and '') should both // produce keys using the provider default. We set up two distinct // repositories returned in sequence from store(null). - $repo1 = m::mock(CacheRepository::class); - $repo1->shouldReceive('getStore')->andReturn(m::mock(RedisStore::class)); - $repo2 = m::mock(CacheRepository::class); - $repo2->shouldReceive('getStore')->andReturn(m::mock(RedisStore::class)); + $repo1 = Double::for(CacheRepository::class); + $repo1->allows('getStore')->returns(Double::for(RedisStore::class)); + $repo2 = Double::for(CacheRepository::class); + $repo2->allows('getStore')->returns(Double::for(RedisStore::class)); - $this->cacheManager->shouldReceive('store')->with(null) - ->andReturn($repo1, $repo2); + $this->cacheManager->allows('store')->with(null) + ->returns($repo1, $repo2); $expectedKey = self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':42'; - $this->expectCoordinatorFill($repo1, $expectedKey, m::mock(Authenticatable::class)); - $this->expectCoordinatorFill($repo2, $expectedKey, m::mock(Authenticatable::class)); + $this->expectCoordinatorFill($repo1, $expectedKey, Double::for(Authenticatable::class)); + $this->expectCoordinatorFill($repo2, $expectedKey, Double::for(Authenticatable::class)); $providerNull = $this->providerWithoutDbFetch(); $providerNull->enableCache(null, 300, null); @@ -220,7 +226,7 @@ public function testCustomCacheKeyResolverIsUsed(): void $repo = $this->stubCache(RedisStore::class); $expectedKey = self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':tenant5:42'; - $this->expectCoordinatorFill($repo, $expectedKey, m::mock(Authenticatable::class)); + $this->expectCoordinatorFill($repo, $expectedKey, Double::for(Authenticatable::class)); $provider = $this->providerWithoutDbFetch(); $provider->enableCache(null); @@ -242,7 +248,7 @@ public function testCustomCacheKeyResolverReceivesLookupContext(): void }); $repo = $this->stubCache(RedisStore::class); - $this->expectCoordinatorFill($repo, $this->buildDefaultKey(42), m::mock(Authenticatable::class)); + $this->expectCoordinatorFill($repo, $this->buildDefaultKey(42), Double::for(Authenticatable::class)); $provider = $this->providerWithoutDbFetch(); $provider->enableCache(null); @@ -260,7 +266,7 @@ public function testCacheKeyAlwaysIncludesFqcnEvenWithCustomResolver(): void $this->expectCoordinatorFill( $repo, self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':wrapper:42', - m::mock(Authenticatable::class), + Double::for(Authenticatable::class), ); $provider = $this->providerWithoutDbFetch(); @@ -277,7 +283,7 @@ public function testChangingTheModelUsesTheNewModelCacheKeyspace(): void $this->expectCoordinatorFill( $repo, self::DEFAULT_KEY_PREFIX . ':' . EloquentCacheProviderAlternateUserStub::class . ':42', - m::mock(Authenticatable::class), + Double::for(Authenticatable::class), ); $provider = $this->providerWithoutDbFetch(); @@ -336,7 +342,7 @@ public static function distinctCacheDescriptorProvider(): iterable #[DataProvider('invalidCacheTtlProvider')] public function testEnableCacheRejectsNonPositiveTtl(int $ttl): void { - $this->cacheManager->shouldNotReceive('store'); + $this->cacheManager->expects('store')->never(); $provider = $this->providerWithoutDbFetch(); @@ -360,9 +366,8 @@ public static function invalidCacheTtlProvider(): iterable public function testEnableCacheAcceptsSupportedStores(string $storeClass): void { $repo = $this->stubCache($storeClass); - $this->storeValidator->shouldReceive('validate') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']'); + $this->storeValidator->expects('validate') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']'); $provider = $this->providerWithoutDbFetch(); $provider->enableCache(null); @@ -386,10 +391,9 @@ public static function supportedStoreProvider(): iterable public function testEnableCacheRejectsUnsupportedStores(string $storeClass): void { $repo = $this->stubCache($storeClass); - $this->storeValidator->shouldReceive('validate') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']') - ->andThrow(new InvalidArgumentException('does not support cache store')); + $this->storeValidator->expects('validate') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']') + ->throws(new InvalidArgumentException('does not support cache store')); $provider = $this->providerWithoutDbFetch(); @@ -412,12 +416,11 @@ public static function unsupportedStoreProvider(): iterable public function testEnableCacheLeavesProviderInDisabledStateWhenValidationFails(): void { $repo = $this->stubCache(ArrayStore::class); - $this->storeValidator->shouldReceive('validate') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']') - ->andThrow(new InvalidArgumentException('does not support cache store')); + $this->storeValidator->expects('validate') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']') + ->throws(new InvalidArgumentException('does not support cache store')); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $provider = $this->providerExpectingDbFetch($user, 42, useWritePdo: false); try { @@ -442,20 +445,18 @@ public function testEnableCacheLeavesProviderInDisabledStateWhenValidationFails( public function testModelStoreValidationRunsBeforeAuthTagValidation(): void { $sequence = []; - $store = m::mock(RedisStore::class); - $repo = m::mock(CacheRepository::class); - $repo->shouldReceive('getStore')->andReturn($store); - $this->cacheManager->shouldReceive('store')->once()->with(null)->andReturn($repo); - $this->storeValidator->shouldReceive('validate') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']') - ->andReturnUsing(function () use (&$sequence): void { + $store = Double::for(RedisStore::class); + $repo = Double::for(CacheRepository::class); + $repo->allows('getStore')->returns($store); + $this->cacheManager->expects('store')->with(null)->returns($repo); + $this->storeValidator->expects('validate') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']') + ->resolves(function () use (&$sequence): void { $sequence[] = 'model'; }); - $this->storeValidator->shouldReceive('validateAnyModeTags') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']') - ->andReturnUsing(function () use (&$sequence): void { + $this->storeValidator->expects('validateAnyModeTags') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']') + ->resolves(function () use (&$sequence): void { $sequence[] = 'tags'; }); @@ -471,9 +472,8 @@ public function testModelStoreValidationRunsBeforeAuthTagValidation(): void public function testClearUserCacheRemovesCachedEntry(): void { $repo = $this->stubCache(RedisStore::class); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($repo, $this->buildDefaultKey(42)); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($repo), $this->buildDefaultKey(42)); $provider = $this->providerForCacheClear(); $provider->enableCache(null); @@ -496,7 +496,7 @@ public function testClearUserCacheUsesCustomKeyResolver(): void $repo = $this->stubCache(RedisStore::class); $expectedKey = self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':tenant:42'; - $this->cacheCoordinator->shouldReceive('invalidate')->once()->with($repo, $expectedKey); + $this->cacheCoordinator->expects('invalidate')->with(Argument::same($repo), $expectedKey); $provider = $this->providerForCacheClear(); $provider->enableCache(null); @@ -508,7 +508,7 @@ public function testClearUserCacheUsesCustomKeyResolver(): void public function testClearUserCacheIsNoOpWhenCacheDisabled(): void { - $this->cacheManager->shouldNotReceive('store'); + $this->cacheManager->expects('store')->never(); $provider = $this->providerWithoutDbFetch(); @@ -547,7 +547,7 @@ public function testFlushStateClearsAllStaticState(): void #[DataProvider('invalidCacheTagsProvider')] public function testEnableCacheRejectsNonStringTagsBeforeResolvingStore(array $tags): void { - $this->cacheManager->shouldNotReceive('store'); + $this->cacheManager->expects('store')->never(); $provider = $this->providerWithoutDbFetch(); @@ -567,9 +567,8 @@ public static function invalidCacheTagsProvider(): iterable public function testEnableCacheAcceptsTagsWhenValidationPasses(): void { $repo = $this->stubCache(RedisStore::class); - $this->storeValidator->shouldReceive('validateAnyModeTags') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']'); + $this->storeValidator->expects('validateAnyModeTags') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']'); $provider = $this->providerWithoutDbFetch(); $provider->enableCache(null, tags: ['auth_users']); @@ -580,10 +579,9 @@ public function testEnableCacheAcceptsTagsWhenValidationPasses(): void public function testEnableCacheRejectsTagsWithAllModeStore(): void { $repo = $this->stubCache(RedisStore::class); - $this->storeValidator->shouldReceive('validateAnyModeTags') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']') - ->andThrow(new InvalidArgumentException('TagMode::Any is required.')); + $this->storeValidator->expects('validateAnyModeTags') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']') + ->throws(new InvalidArgumentException('TagMode::Any is required.')); $provider = $this->providerWithoutDbFetch(); @@ -597,10 +595,9 @@ public function testEnableCacheRejectsTagsWithAllModeStore(): void public function testEnableCacheRejectsTagsWithNonTaggableStore(string $storeClass): void { $repo = $this->stubCache($storeClass); - $this->storeValidator->shouldReceive('validateAnyModeTags') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']') - ->andThrow(new InvalidArgumentException('The cache store does not support tags.')); + $this->storeValidator->expects('validateAnyModeTags') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']') + ->throws(new InvalidArgumentException('The cache store does not support tags.')); $provider = $this->providerWithoutDbFetch(); @@ -620,11 +617,11 @@ public static function nonTaggableWhitelistedStoreProvider(): iterable public function testRetrieveByIdMissUsesTaggedRepoForPutWhenTagsConfigured(): void { $plainRepo = $this->stubCache(RedisStore::class); - $taggedRepo = m::mock(CacheRepository::class); - $user = m::mock(Authenticatable::class); + $taggedRepo = Double::for(TaggedCache::class); + $user = Double::for(Authenticatable::class); $key = $this->buildDefaultKey(42); - $plainRepo->shouldReceive('tags')->once()->with(['auth_users'])->andReturn($taggedRepo); + $plainRepo->expects('tags')->with(['auth_users'])->returns($taggedRepo); $this->expectCoordinatorFill($plainRepo, $key, $user, readSource: true, expectedWriter: $taggedRepo); $provider = $this->providerExpectingDbFetch($user, 42); @@ -636,10 +633,9 @@ public function testRetrieveByIdMissUsesTaggedRepoForPutWhenTagsConfigured(): vo public function testRetrieveByIdUsesTaggedRepoWhenTagsConfigured(): void { $plainRepo = $this->stubCache(RedisStore::class); - $taggedRepo = m::mock(CacheRepository::class); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); - $plainRepo->shouldNotReceive('tags'); + $plainRepo->expects('tags')->never(); $this->expectCoordinatorFill($plainRepo, $this->buildDefaultKey(42), $user); $provider = $this->providerWithoutDbFetch(); @@ -652,10 +648,9 @@ public function testClearUserCacheUsesPlainRepoEvenWhenTagsConfigured(): void { $plainRepo = $this->stubCache(RedisStore::class); - $this->cacheCoordinator->shouldReceive('invalidate') - ->once() - ->with($plainRepo, $this->buildDefaultKey(42)); - $plainRepo->shouldNotReceive('tags'); + $this->cacheCoordinator->expects('invalidate') + ->with(Argument::same($plainRepo), $this->buildDefaultKey(42)); + $plainRepo->expects('tags')->never(); $provider = $this->providerForCacheClear(); $provider->enableCache(null, tags: ['auth_users']); @@ -668,11 +663,11 @@ public function testEffectiveTagsCombineStaticAndDynamic(): void EloquentUserProvider::resolveUserCacheTagsUsing(fn (): array => ['scope:a']); $plainRepo = $this->stubCache(RedisStore::class); - $taggedRepo = m::mock(CacheRepository::class); - $user = m::mock(Authenticatable::class); + $taggedRepo = Double::for(TaggedCache::class); + $user = Double::for(Authenticatable::class); $key = $this->buildDefaultKey(42); - $plainRepo->shouldReceive('tags')->once()->with(['auth_users', 'scope:a'])->andReturn($taggedRepo); + $plainRepo->expects('tags')->with(['auth_users', 'scope:a'])->returns($taggedRepo); $this->expectCoordinatorFill($plainRepo, $key, $user, readSource: true, expectedWriter: $taggedRepo); $provider = $this->providerExpectingDbFetch($user, 42); @@ -684,11 +679,11 @@ public function testEffectiveTagsCombineStaticAndDynamic(): void public function testEffectiveTagsAreJustStaticWhenNoResolver(): void { $plainRepo = $this->stubCache(RedisStore::class); - $taggedRepo = m::mock(CacheRepository::class); - $user = m::mock(Authenticatable::class); + $taggedRepo = Double::for(TaggedCache::class); + $user = Double::for(Authenticatable::class); $key = $this->buildDefaultKey(42); - $plainRepo->shouldReceive('tags')->once()->with(['auth_users'])->andReturn($taggedRepo); + $plainRepo->expects('tags')->with(['auth_users'])->returns($taggedRepo); $this->expectCoordinatorFill($plainRepo, $key, $user, readSource: true, expectedWriter: $taggedRepo); $provider = $this->providerExpectingDbFetch($user, 42); @@ -707,34 +702,36 @@ public function testDynamicResolverIsInvokedFreshlyOnEachPut(): void }); $plainRepo = $this->stubCache(RedisStore::class); - $taggedRepo1 = m::mock(CacheRepository::class); - $taggedRepo2 = m::mock(CacheRepository::class); - $user1 = m::mock(Authenticatable::class); - $user2 = m::mock(Authenticatable::class); + $taggedRepo1 = Double::for(TaggedCache::class); + $taggedRepo2 = Double::for(TaggedCache::class); + $user1 = Double::for(Authenticatable::class); + $user2 = Double::for(Authenticatable::class); $key1 = $this->buildDefaultKey(42); $key2 = $this->buildDefaultKey(43); - $plainRepo->shouldReceive('tags')->once()->with(['auth_users', 'scope:1'])->andReturn($taggedRepo1); - $plainRepo->shouldReceive('tags')->once()->with(['auth_users', 'scope:2'])->andReturn($taggedRepo2); + $plainRepo->expects('tags')->with(['auth_users', 'scope:1'])->returns($taggedRepo1); + $plainRepo->expects('tags')->with(['auth_users', 'scope:2'])->returns($taggedRepo2); $this->expectCoordinatorFill($plainRepo, $key1, $user1, readSource: true, expectedWriter: $taggedRepo1); $this->expectCoordinatorFill($plainRepo, $key2, $user2, readSource: true, expectedWriter: $taggedRepo2); // Set up two DB fetches with distinct models/IDs. - $model1 = m::mock(Model::class); - $builder1 = m::mock(Builder::class); - $model1->shouldReceive('newQuery')->once()->andReturn($builder1); - $model1->shouldReceive('getAuthIdentifierName')->once()->andReturn('id'); - $builder1->shouldReceive('useWritePdo')->once()->andReturnSelf(); - $builder1->shouldReceive('where')->once()->with('id', 42)->andReturn($builder1); - $builder1->shouldReceive('first')->once()->andReturn($user1); - - $model2 = m::mock(Model::class); - $builder2 = m::mock(Builder::class); - $model2->shouldReceive('newQuery')->once()->andReturn($builder2); - $model2->shouldReceive('getAuthIdentifierName')->once()->andReturn('id'); - $builder2->shouldReceive('useWritePdo')->once()->andReturnSelf(); - $builder2->shouldReceive('where')->once()->with('id', 43)->andReturn($builder2); - $builder2->shouldReceive('first')->once()->andReturn($user2); + $model1 = Double::for(User::class); + $query1 = Double::for(QueryBuilder::class); + $builder1 = Double::for(new Builder($query1))->passthru(); + $model1->expects('newQuery')->returns($builder1); + $model1->expects('getAuthIdentifierName')->returns('id'); + $query1->expects('useWritePdo'); + $builder1->expects('where')->with('id', 42)->returns($builder1); + $builder1->expects('first')->returns($user1); + + $model2 = Double::for(User::class); + $query2 = Double::for(QueryBuilder::class); + $builder2 = Double::for(new Builder($query2))->passthru(); + $model2->expects('newQuery')->returns($builder2); + $model2->expects('getAuthIdentifierName')->returns('id'); + $query2->expects('useWritePdo'); + $builder2->expects('where')->with('id', 43)->returns($builder2); + $builder2->expects('first')->returns($user2); $provider = $this->providerMock(); $provider->expects($this->exactly(2))->method('createModel')->willReturnOnConsecutiveCalls($model1, $model2); @@ -756,11 +753,11 @@ public function testDynamicResolverIgnoredWhenNoStaticTagsConfigured(): void }); $plainRepo = $this->stubCache(RedisStore::class); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $key = $this->buildDefaultKey(42); $this->expectCoordinatorFill($plainRepo, $key, $user, readSource: true, expectedWriter: $plainRepo); - $plainRepo->shouldNotReceive('tags'); + $plainRepo->expects('tags')->never(); $provider = $this->providerExpectingDbFetch($user, 42); $provider->enableCache(null); @@ -785,12 +782,11 @@ public function testFlushStateClearsTagsResolver(): void public function testEnableCacheLeavesProviderInDisabledStateWhenTagValidationFails(): void { $repo = $this->stubCache(RedisStore::class); - $this->storeValidator->shouldReceive('validateAnyModeTags') - ->once() - ->with($repo, 'Auth user cache for model [' . self::MODEL . ']') - ->andThrow(new InvalidArgumentException('TagMode::Any is required.')); + $this->storeValidator->expects('validateAnyModeTags') + ->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']') + ->throws(new InvalidArgumentException('TagMode::Any is required.')); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $provider = $this->providerExpectingDbFetch($user, 42, useWritePdo: false); try { @@ -817,15 +813,15 @@ public function testRecallingEnableCacheWithoutTagsClearsPreviousTagState(): voi // First call uses a Redis store in any-mode (tag-valid), second // call uses a plain Redis store (no tags). Set up both upfront so // the cache manager returns them in sequence from store(null). - $store1 = m::mock(RedisStore::class); - $repo1 = m::mock(CacheRepository::class); - $repo1->shouldReceive('getStore')->andReturn($store1); + $store1 = Double::for(RedisStore::class); + $repo1 = Double::for(CacheRepository::class); + $repo1->allows('getStore')->returns($store1); - $store2 = m::mock(RedisStore::class); - $repo2 = m::mock(CacheRepository::class); - $repo2->shouldReceive('getStore')->andReturn($store2); + $store2 = Double::for(RedisStore::class); + $repo2 = Double::for(CacheRepository::class); + $repo2->allows('getStore')->returns($store2); - $this->cacheManager->shouldReceive('store')->with(null)->andReturn($repo1, $repo2); + $this->cacheManager->allows('store')->with(null)->returns($repo1, $repo2); $provider = $this->providerWithoutDbFetch(); $provider->enableCache(null, tags: ['auth_users']); @@ -846,7 +842,7 @@ public function testRecallingEnableCacheWithoutTagsClearsPreviousTagState(): voi protected function providerMock(): EloquentUserProvider&MockObject { - $hasher = m::mock(Hasher::class); + $hasher = Double::for(Hasher::class); return $this->getMockBuilder(EloquentUserProvider::class) ->onlyMethods(['createModel']) @@ -863,17 +859,18 @@ protected function providerExpectingDbFetch( mixed $id, bool $useWritePdo = true, ): EloquentUserProvider&MockObject { - $model = m::mock(Model::class); - $builder = m::mock(Builder::class); - $model->shouldReceive('newQuery')->once()->andReturn($builder); - $model->shouldReceive('getAuthIdentifierName')->once()->andReturn('id'); + $model = Double::for(User::class); + $query = Double::for(QueryBuilder::class); + $builder = Double::for(new Builder($query))->passthru(); + $model->expects('newQuery')->returns($builder); + $model->expects('getAuthIdentifierName')->returns('id'); if ($useWritePdo) { - $builder->shouldReceive('useWritePdo')->once()->andReturnSelf(); + $query->expects('useWritePdo'); } else { - $builder->shouldNotReceive('useWritePdo'); + $query->expects('useWritePdo')->never(); } - $builder->shouldReceive('where')->once()->with('id', $id)->andReturn($builder); - $builder->shouldReceive('first')->once()->andReturn($user); + $builder->expects('where')->with('id', $id)->returns($builder); + $builder->expects('first')->returns($user); $provider = $this->providerMock(); $provider->expects($this->once())->method('createModel')->willReturn($model); @@ -886,14 +883,13 @@ protected function providerExpectingDbFetch( */ protected function providerForCacheClear(): EloquentUserProvider&MockObject { - $connection = m::mock(Connection::class); - $connection->shouldReceive('afterCommitOrNow') - ->once() - ->with(m::type(Closure::class)) - ->andReturnUsing(static fn (Closure $callback): mixed => $callback()); + $connection = Double::for(Connection::class); + $connection->expects('afterCommitOrNow') + ->with(Argument::type(Closure::class)) + ->resolves(static fn (Closure $callback): mixed => $callback()); - $model = m::mock(Model::class); - $model->shouldReceive('getConnection')->once()->andReturn($connection); + $model = Double::for(User::class); + $model->expects('getConnection')->returns($connection); $provider = $this->providerMock(); $provider->expects($this->once())->method('createModel')->willReturn($model); @@ -911,18 +907,17 @@ protected function expectCoordinatorFill( bool $readSource = false, ?CacheRepository $expectedWriter = null, ): void { - $this->cacheCoordinator->shouldReceive('fill') - ->once() + $this->cacheCoordinator->expects('fill') ->with( - $repository, - m::type(Closure::class), + Argument::same($repository), + Argument::type(Closure::class), $key, 300, - m::type(Closure::class), + Argument::type(Closure::class), true, - m::type(Closure::class), + Argument::type(Closure::class), ) - ->andReturnUsing(function ( + ->resolves(function ( CacheRepository $cache, Closure $source, string $receivedKey, @@ -955,13 +950,13 @@ protected function providerWithoutDbFetch(): EloquentUserProvider&MockObject * instance of $storeClass. Returns the repository mock so tests can * set further expectations on it. */ - protected function stubCache(string $storeClass, ?string $name = null): MockInterface + protected function stubCache(string $storeClass, ?string $name = null): Repository&DoubleInterface { - $store = m::mock($storeClass); + $store = Double::for($storeClass); - $repo = m::mock(CacheRepository::class); - $repo->shouldReceive('getStore')->andReturn($store); - $this->cacheManager->shouldReceive('store')->with($name)->andReturn($repo); + $repo = Double::for(Repository::class); + $repo->allows('getStore')->returns($store); + $this->cacheManager->allows('store')->with($name)->returns($repo); return $repo; } @@ -972,10 +967,10 @@ protected function buildDefaultKey(mixed $identifier): string } } -class EloquentCacheProviderUserStub extends Model +class EloquentCacheProviderUserStub extends User { } -class EloquentCacheProviderAlternateUserStub extends Model +class EloquentCacheProviderAlternateUserStub extends User { } diff --git a/tests/Auth/AuthManagerTest.php b/tests/Auth/AuthManagerTest.php index 7aa1610222..e9ae7c96d6 100644 --- a/tests/Auth/AuthManagerTest.php +++ b/tests/Auth/AuthManagerTest.php @@ -39,7 +39,9 @@ use Hypervel\Support\Facades\Auth as AuthFacade; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionClass; use ReflectionProperty; @@ -48,6 +50,8 @@ class AuthManagerTest extends TestCase { + use VerifiesDoubles; + public function testGetDefaultDriverFromConfig(): void { $manager = new AuthManager($container = $this->getContainer()); @@ -101,7 +105,7 @@ public function testShouldUseSetsDefaultDriverAndUserResolver(): void $container->make('config') ->set('auth.guards.api', ['driver' => 'custom']); - $guard = m::mock(Guard::class); + $guard = Double::for(Guard::class); $manager->extend('custom', function () use ($guard) { return $guard; }); @@ -140,7 +144,7 @@ public function testExtendDriver(): void $manager = new AuthManager($container = $this->getContainer()); $container->make('config') ->set('auth.guards.foo', ['driver' => 'bar']); - $guard = m::mock(Guard::class); + $guard = Double::for(Guard::class); $manager->extend('bar', function () use ($guard) { return $guard; @@ -159,7 +163,7 @@ public function testGuardWithExplicitFalseyNameDoesNotFallBackToDefaultDriver(): $container->make('config') ->set('auth.guards.foo', ['driver' => 'bar']); - $guard = m::mock(Guard::class); + $guard = Double::for(Guard::class); $test = $this; $manager->extend('bar', function ($app, string $name) use ($guard, $test): Guard { $test->assertSame('0', $name); @@ -178,7 +182,7 @@ public function testGuardWithEmptyNameUsesDefaultDriver(): void $container->make('config') ->set('auth.guards.foo', ['driver' => 'bar']); - $guard = m::mock(Guard::class); + $guard = Double::for(Guard::class); $manager->extend('bar', fn () => $guard); $this->assertSame($guard, $manager->guard('')); @@ -195,7 +199,7 @@ public function testExtendCallbackIsBoundToManager(): void $manager->extend('bar', function () use (&$boundTo) { $boundTo = $this; - return m::mock(Guard::class); + return Double::for(Guard::class); }); $manager->guard('foo'); @@ -368,23 +372,22 @@ public function testCreateDatabaseUserProvider(): void 'table' => 'users', ]); - $query = m::mock(Builder::class); - $query->shouldReceive('find')->once()->with(1)->andReturn(null); - $connection = m::mock(Connection::class); - $connection->shouldReceive('table')->once()->with('users')->andReturn($query); + $query = Double::for(Builder::class); + $query->expects('find')->with(1)->returns(null); + $connection = Double::for(Connection::class); + $connection->expects('table')->with('users')->returns($query); $resolutions = 0; - $database = m::mock(ConnectionResolverInterface::class); - $database->shouldReceive('connection') + $database = Double::for(ConnectionResolverInterface::class); + $database->expects('connection') ->with('foo') - ->once() - ->andReturnUsing(function () use (&$resolutions, $connection) { + ->resolves(function () use (&$resolutions, $connection) { ++$resolutions; return $connection; }); $container->instance('db', $database); - $container->instance('hash', m::mock(HashContract::class)); + $container->instance('hash', Double::for(HashContract::class)); $provider = $manager->createUserProvider('foo'); @@ -400,15 +403,14 @@ public function testDatabaseUserProviderUsesDefaultConnectionWhenOmitted(): void 'driver' => 'database', 'table' => 'users', ]); - $query = m::mock(Builder::class); - $query->shouldReceive('find')->once()->with(1)->andReturn(null); - $connection = m::mock(Connection::class); - $connection->shouldReceive('table')->once()->with('users')->andReturn($query); - $database = m::mock(ConnectionResolverInterface::class); - $database->shouldReceive('connection') - ->once() + $query = Double::for(Builder::class); + $query->expects('find')->with(1)->returns(null); + $connection = Double::for(Connection::class); + $connection->expects('table')->with('users')->returns($query); + $database = Double::for(ConnectionResolverInterface::class); + $database->expects('connection') ->with(null) - ->andReturn($connection); + ->returns($connection); $this->app->instance('db', $database); $provider = (new AuthManager($this->app))->createUserProvider('database'); @@ -422,8 +424,8 @@ public function testDatabaseUserProviderRequiresDeclaredTable(): void $this->app->make('config')->set('auth.providers.incomplete', [ 'driver' => 'database', ]); - $database = m::mock(ConnectionResolverInterface::class); - $database->shouldNotReceive('connection'); + $database = Double::for(ConnectionResolverInterface::class); + $database->expects('connection')->never(); $this->app->instance('db', $database); $this->expectException(ErrorException::class); @@ -441,7 +443,7 @@ public function testCreateCustomUserProvider(): void 'driver' => 'bar', ]); - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $manager->provider('bar', fn () => $provider); $this->assertSame($provider, $manager->createUserProvider('foo')); @@ -502,14 +504,13 @@ public function testPartialEloquentUserProviderCacheUsesProviderDefaults(): void 'enabled' => true, ], ]); - $repository = m::mock(CacheRepository::class); - $cache = m::mock(CacheManager::class); - $cache->shouldReceive('store')->once()->with(null)->andReturn($repository); + $repository = Double::for(CacheRepository::class); + $cache = Double::for(CacheManager::class); + $cache->expects('store')->with(null)->returns($repository); $this->app->instance('cache', $cache); - $validator = m::mock(ModelCacheStoreValidator::class); - $validator->shouldReceive('validate') - ->once() - ->with($repository, 'Auth user cache for model [' . AuthManagerCacheUserStub::class . ']'); + $validator = Double::for(ModelCacheStoreValidator::class); + $validator->expects('validate') + ->with(Argument::same($repository), 'Auth user cache for model [' . AuthManagerCacheUserStub::class . ']'); $this->app->instance(ModelCacheStoreValidator::class, $validator); $provider = (new AuthManager($this->app))->createUserProvider('cached'); @@ -545,10 +546,10 @@ public function testCreateEloquentUserProviderRejectsInvalidCacheTtl(mixed $ttl, ])); Container::setInstance($container); - $container->instance('hash', m::mock(HashContract::class)); + $container->instance('hash', Double::for(HashContract::class)); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldNotReceive('store'); + $cacheManager = Double::for(CacheManager::class); + $cacheManager->expects('store')->never(); $container->instance('cache', $cacheManager); $this->expectException(InvalidArgumentException::class); @@ -597,10 +598,10 @@ public function testViaRequest(): void 'provider' => 'foo', ]); - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $manager->provider('foo', fn () => $provider); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $manager->viaRequest('custom', function (Request $request, ?UserProvider $requestProvider) use ($provider, $user) { $this->assertSame($provider, $requestProvider); @@ -622,7 +623,7 @@ public function testViaRequestGuardWithoutProviderKeyGetsNullProvider(): void 'driver' => 'custom', ]); - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $manager->viaRequest('custom', function (Request $request, ?UserProvider $requestProvider) use ($user) { $this->assertNull($requestProvider); @@ -638,11 +639,11 @@ public function testRedirectGuestsToConfiguresAuthenticateMiddleware(): void { $manager = new AuthManager($this->getContainer()); - $guard = m::mock(Guard::class); - $guard->shouldReceive('check')->andReturnFalse(); + $guard = Double::for(Guard::class); + $guard->allows('check')->returns(false); - $factory = m::mock(AuthFactory::class); - $factory->shouldReceive('guard')->with(null)->andReturn($guard); + $factory = Double::for(AuthFactory::class); + $factory->allows('guard')->with(null)->returns($guard); $manager->redirectGuestsTo('/login'); @@ -714,11 +715,11 @@ public function testRedirectUsersToConfiguresRedirectIfAuthenticatedMiddlewarePe ? '/admin' : '/dashboard'); - $guard = m::mock(Guard::class); - $guard->shouldReceive('check')->andReturnTrue(); + $guard = Double::for(Guard::class); + $guard->allows('check')->returns(true); - $factory = m::mock(AuthFactory::class); - $factory->shouldReceive('guard')->andReturn($guard); + $factory = Double::for(AuthFactory::class); + $factory->allows('guard')->returns($guard); AuthFacade::swap($factory); $response = (new RedirectIfAuthenticated)->handle( @@ -737,11 +738,11 @@ public function testRedirectToConfiguresBothRedirectSides(): void $this->assertSame('/login', (new AuthenticationException)->redirectTo(Request::create('/'))); - $guard = m::mock(Guard::class); - $guard->shouldReceive('check')->andReturnTrue(); + $guard = Double::for(Guard::class); + $guard->allows('check')->returns(true); - $factory = m::mock(AuthFactory::class); - $factory->shouldReceive('guard')->andReturn($guard); + $factory = Double::for(AuthFactory::class); + $factory->allows('guard')->returns($guard); AuthFacade::swap($factory); $response = (new RedirectIfAuthenticated)->handle(Request::create('/login'), fn () => null); @@ -771,11 +772,11 @@ public function testRedirectConfigurationUsesMostRecentHighLevelRegistration(): $manager->redirectUsersTo('/first-dashboard'); $manager->redirectUsersTo('/second-dashboard'); - $guard = m::mock(Guard::class); - $guard->shouldReceive('check')->andReturnTrue(); + $guard = Double::for(Guard::class); + $guard->allows('check')->returns(true); - $factory = m::mock(AuthFactory::class); - $factory->shouldReceive('guard')->andReturn($guard); + $factory = Double::for(AuthFactory::class); + $factory->allows('guard')->returns($guard); AuthFacade::swap($factory); $response = (new RedirectIfAuthenticated)->handle(Request::create('/login'), fn () => null); @@ -789,7 +790,7 @@ public function testGuardCachesResolvedInstances(): void $container->make('config') ->set('auth.guards.foo', ['driver' => 'bar']); - $manager->extend('bar', fn () => m::mock(Guard::class)); + $manager->extend('bar', fn () => Double::for(Guard::class)); $guard1 = $manager->guard('foo'); $guard2 = $manager->guard('foo'); @@ -810,7 +811,7 @@ public function testHasResolvedGuardsReturnsTrueAfterResolving(): void $container->make('config') ->set('auth.guards.foo', ['driver' => 'bar']); - $manager->extend('bar', fn () => m::mock(Guard::class)); + $manager->extend('bar', fn () => Double::for(Guard::class)); $manager->guard('foo'); $this->assertTrue($manager->hasResolvedGuards()); @@ -822,7 +823,7 @@ public function testForgetGuardsClearsCache(): void $container->make('config') ->set('auth.guards.foo', ['driver' => 'bar']); - $manager->extend('bar', fn () => m::mock(Guard::class)); + $manager->extend('bar', fn () => Double::for(Guard::class)); $manager->guard('foo'); $this->assertTrue($manager->hasResolvedGuards()); @@ -841,7 +842,7 @@ public function testGetGuardsReturnsAllResolved(): void $container->make('config') ->set('auth.guards.baz', ['driver' => 'bar']); - $manager->extend('bar', fn () => m::mock(Guard::class)); + $manager->extend('bar', fn () => Double::for(Guard::class)); $manager->guard('foo'); $manager->guard('baz'); @@ -892,8 +893,8 @@ public function testMagicCallDelegatesToDefaultGuard(): void $container->make('config') ->set('auth.guards.foo', ['driver' => 'bar']); - $guard = m::mock(Guard::class); - $guard->shouldReceive('check')->once()->andReturn(true); + $guard = Double::for(Guard::class); + $guard->expects('check')->returns(true); $manager->extend('bar', fn () => $guard); @@ -908,7 +909,7 @@ public function testClearUserCacheIsNoOpForCustomGuardWithoutGetProvider(): void ], ])); - $guard = m::mock(Guard::class); + $guard = Double::for(Guard::class); $manager->extend('custom', fn () => $guard); $manager->clearUserCache(42, 'api'); @@ -941,15 +942,14 @@ public function testClearUserCacheUsesSpecifiedGuardProvider(): void ])); Container::setInstance($container); - $container->instance('hash', m::mock(HashContract::class)); - - $cacheManager = m::mock(CacheManager::class); - $adminRepo = m::mock(CacheRepository::class); - $coordinator = m::mock(ModelCacheCoordinator::class); - $coordinator->shouldReceive('invalidate') - ->once() - ->with($adminRepo, 'admin_users:' . AuthManagerCacheAdminStub::class . ':42'); - $cacheManager->shouldReceive('store')->with('admin-store')->andReturn($adminRepo); + $container->instance('hash', Double::for(HashContract::class)); + + $cacheManager = Double::for(CacheManager::class); + $adminRepo = Double::for(CacheRepository::class); + $coordinator = Double::for(ModelCacheCoordinator::class); + $coordinator->expects('invalidate') + ->with(Argument::same($adminRepo), 'admin_users:' . AuthManagerCacheAdminStub::class . ':42'); + $cacheManager->allows('store')->with('admin-store')->returns($adminRepo); $container->instance('cache', $cacheManager); $container->instance(ModelCacheCoordinator::class, $coordinator); @@ -963,10 +963,10 @@ public function testClearUserCacheAcceptsAnEnumGuardIdentifier(): void 'admin' => ['driver' => 'custom'], ], ])); - $provider = m::mock(EloquentUserProvider::class); - $provider->shouldReceive('clearUserCache')->once()->with(42); - $guard = m::mock(TokenGuard::class); - $guard->shouldReceive('getProvider')->once()->andReturn($provider); + $provider = Double::for(EloquentUserProvider::class); + $provider->expects('clearUserCache')->with(42); + $guard = Double::for(TokenGuard::class); + $guard->expects('getProvider')->returns($provider); $manager->extend('custom', fn () => $guard); $manager->clearUserCache(42, AuthManagerGuardEnum::Admin); @@ -991,15 +991,14 @@ public function testClearUserCacheUsesDefaultGuardAndRespectsResolver(): void ])); Container::setInstance($container); - $container->instance('hash', m::mock(HashContract::class)); - - $cacheManager = m::mock(CacheManager::class); - $repo = m::mock(CacheRepository::class); - $coordinator = m::mock(ModelCacheCoordinator::class); - $coordinator->shouldReceive('invalidate') - ->once() - ->with($repo, EloquentUserProvider::DEFAULT_CACHE_PREFIX . ':' . AuthManagerCacheUserStub::class . ':tenant:42'); - $cacheManager->shouldReceive('store')->with('web-store')->andReturn($repo); + $container->instance('hash', Double::for(HashContract::class)); + + $cacheManager = Double::for(CacheManager::class); + $repo = Double::for(CacheRepository::class); + $coordinator = Double::for(ModelCacheCoordinator::class); + $coordinator->expects('invalidate') + ->with(Argument::same($repo), EloquentUserProvider::DEFAULT_CACHE_PREFIX . ':' . AuthManagerCacheUserStub::class . ':tenant:42'); + $cacheManager->allows('store')->with('web-store')->returns($repo); $container->instance('cache', $cacheManager); $container->instance(ModelCacheCoordinator::class, $coordinator); @@ -1029,14 +1028,14 @@ public function testForgetGuardsDoesNotAccumulateAuthCacheDescriptors(): void ])); Container::setInstance($container); - $container->instance('hash', m::mock(HashContract::class)); - - $cacheManager = m::mock(CacheManager::class); - $firstRepo = m::mock(CacheRepository::class); - $firstRepo->shouldReceive('getStore')->andReturn(m::mock(RedisStore::class)); - $secondRepo = m::mock(CacheRepository::class); - $secondRepo->shouldReceive('getStore')->andReturn(m::mock(RedisStore::class)); - $cacheManager->shouldReceive('store')->with('redis')->andReturn($firstRepo, $secondRepo); + $container->instance('hash', Double::for(HashContract::class)); + + $cacheManager = Double::for(CacheManager::class); + $firstRepo = Double::for(CacheRepository::class); + $firstRepo->allows('getStore')->returns(Double::for(RedisStore::class)); + $secondRepo = Double::for(CacheRepository::class); + $secondRepo->allows('getStore')->returns(Double::for(RedisStore::class)); + $cacheManager->allows('store')->with('redis')->returns($firstRepo, $secondRepo); $container->instance('cache', $cacheManager); $container->instance(ModelCacheCoordinator::class, new ModelCacheCoordinator($container)); @@ -1064,7 +1063,7 @@ protected function getContainer(array $authConfig = []): Container $container->instance('config', new Repository([ 'auth' => $authConfig, ])); - $validator = m::mock(ModelCacheStoreValidator::class); + $validator = Double::for(ModelCacheStoreValidator::class); $validator->allows('validate'); $container->instance(ModelCacheStoreValidator::class, $validator); diff --git a/tests/Auth/AuthPasswordResetServiceProviderTest.php b/tests/Auth/AuthPasswordResetServiceProviderTest.php index 62dd68e176..7ff8c15805 100644 --- a/tests/Auth/AuthPasswordResetServiceProviderTest.php +++ b/tests/Auth/AuthPasswordResetServiceProviderTest.php @@ -10,57 +10,54 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Contracts\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\OverriddenDouble; class AuthPasswordResetServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testEventRebindDoesNotResolveAnUnusedPasswordManager(): void { [$application, $callback] = $this->registerProvider(); - $events = m::mock(Dispatcher::class); - $application->shouldReceive('resolved')->once()->with('auth.password')->andReturnFalse(); - $application->shouldNotReceive('make')->with('auth.password'); + $events = Double::for(Dispatcher::class); + $application->expects('resolved')->with('auth.password')->returns(false); + $application->expects('make')->never()->with('auth.password'); - $callback($application, $events); + $callback($application->instance(), $events); } public function testEventRebindRefreshesAnAlreadyResolvedPasswordManager(): void { [$application, $callback] = $this->registerProvider(); - $events = m::mock(Dispatcher::class); - $manager = m::mock(PasswordBrokerManager::class); - $application->shouldReceive('resolved')->once()->with('auth.password')->andReturnTrue(); - $application->shouldReceive('make')->once()->with('auth.password')->andReturn($manager); - $manager->shouldReceive('refreshEventDispatcher')->once()->with($events); + $events = Double::for(Dispatcher::class); + $manager = Double::for(PasswordBrokerManager::class); + $application->expects('resolved')->with('auth.password')->returns(true); + $application->expects('make')->with('auth.password')->returns($manager); + $manager->expects('refreshEventDispatcher')->with(Argument::same($events)); - $callback($application, $events); + $callback($application->instance(), $events); } /** * Register the provider and return its event-rebind callback. * - * @return array{Application&MockInterface, Closure} + * @return array{OverriddenDouble, Closure} */ private function registerProvider(): array { $callback = null; - $application = m::mock(Application::class); - $application->shouldReceive('singleton') - ->once() - ->with('auth.password', m::type(Closure::class)); - $application->shouldReceive('bind') - ->once() - ->with('auth.password.broker', m::type(Closure::class)); - $application->shouldReceive('rebinding') - ->once() - ->with('events', m::on(function (mixed $registered) use (&$callback): bool { - $callback = $registered; - - return $registered instanceof Closure; - })); + $application = Double::for(Application::class, override: true); + $application->expects('singleton') + ->with('auth.password', Argument::type(Closure::class)); + $application->expects('bind') + ->with('auth.password.broker', Argument::type(Closure::class)); + $application->expects('rebinding') + ->with('events', Argument::capture($callback)); - (new PasswordResetServiceProvider($application))->register(); + (new PasswordResetServiceProvider($application->instance()))->register(); $this->assertInstanceOf(Closure::class, $callback); diff --git a/tests/Auth/AuthRequestGuardTest.php b/tests/Auth/AuthRequestGuardTest.php index 31bb892de9..6ef6b165fa 100644 --- a/tests/Auth/AuthRequestGuardTest.php +++ b/tests/Auth/AuthRequestGuardTest.php @@ -10,14 +10,17 @@ use Hypervel\Contracts\Auth\UserProvider; use Hypervel\Http\Request; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class AuthRequestGuardTest extends TestCase { + use VerifiesDoubles; + public function testCallbackReceivesRequestAndProvider(): void { $request = Request::create('/'); - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); RequestContext::set($request); $receivedRequest = null; @@ -27,7 +30,7 @@ public function testCallbackReceivesRequestAndProvider(): void $receivedRequest = $req; $receivedProvider = $prov; - return m::mock(Authenticatable::class); + return Double::for(Authenticatable::class); }, $this->app, $provider); $guard->user(); @@ -41,7 +44,7 @@ public function testUserReturnsCachedUserOnSubsequentCalls(): void RequestContext::set(Request::create('/')); $callCount = 0; - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); $guard = new RequestGuard('custom', function () use (&$callCount, $user) { ++$callCount; @@ -75,7 +78,7 @@ public function testHasUserReturnsTrueWhenUserExists(): void { RequestContext::set(Request::create('/')); - $guard = new RequestGuard('custom', fn () => m::mock(Authenticatable::class), $this->app); + $guard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class), $this->app); $guard->user(); $this->assertTrue($guard->hasUser()); @@ -102,8 +105,8 @@ public function testSetUserOverridesCachedUser(): void { RequestContext::set(Request::create('/')); - $originalUser = m::mock(Authenticatable::class); - $newUser = m::mock(Authenticatable::class); + $originalUser = Double::for(Authenticatable::class); + $newUser = Double::for(Authenticatable::class); $guard = new RequestGuard('custom', fn () => $originalUser, $this->app); $guard->user(); @@ -118,8 +121,8 @@ public function testSetUserOverridesTheResolverAcrossRequestChanges(): void { RequestContext::set(Request::create('/first')); - $resolvedUser = m::mock(Authenticatable::class); - $explicitUser = m::mock(Authenticatable::class); + $resolvedUser = Double::for(Authenticatable::class); + $explicitUser = Double::for(Authenticatable::class); $guard = new RequestGuard('custom', fn () => $resolvedUser, $this->app); $guard->setUser($explicitUser); @@ -132,7 +135,7 @@ public function testForgetUserClearsCachedUser(): void { RequestContext::set(Request::create('/')); - $guard = new RequestGuard('custom', fn () => m::mock(Authenticatable::class), $this->app); + $guard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class), $this->app); $guard->user(); $this->assertTrue($guard->hasUser()); @@ -146,8 +149,8 @@ public function testTwoGuardNamesDoNotCollideInContext(): void { RequestContext::set(Request::create('/')); - $user1 = m::mock(Authenticatable::class); - $user2 = m::mock(Authenticatable::class); + $user1 = Double::for(Authenticatable::class); + $user2 = Double::for(Authenticatable::class); $guard1 = new RequestGuard('guard_one', fn () => $user1, $this->app); $guard2 = new RequestGuard('guard_two', fn () => $user2, $this->app); @@ -159,9 +162,9 @@ public function testTwoGuardNamesDoNotCollideInContext(): void public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsUsers(): void { RequestContext::set(Request::create('/')); - $previousGuard = new RequestGuard('custom', fn () => m::mock(Authenticatable::class), $this->app); + $previousGuard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class), $this->app); $previousGuard->user(); - $previousGuard->setUser(m::mock(Authenticatable::class)); + $previousGuard->setUser(Double::for(Authenticatable::class)); $callCount = 0; $guard = new RequestGuard('custom', function () use (&$callCount) { @@ -186,7 +189,7 @@ public function testReplacingRequestInContextChangesWhatGuardSees(): void $guard = new RequestGuard('custom', function ($req) use (&$seenRequests) { $seenRequests[] = $req; - return m::mock(Authenticatable::class); + return Double::for(Authenticatable::class); }, $this->app); // First call sees request1 @@ -215,10 +218,10 @@ public function testAuthContextKeysIncludeOnlyDurableExplicitState(): void public function testValidateCallsCallbackWithCredentialsRequest(): void { $request = Request::create('/'); - $provider = m::mock(UserProvider::class); + $provider = Double::for(UserProvider::class); $guard = new RequestGuard('custom', function ($req) { - return $req instanceof Request ? m::mock(Authenticatable::class) : null; + return $req instanceof Request ? Double::for(Authenticatable::class) : null; }, $this->app, $provider); $this->assertTrue($guard->validate(['request' => $request])); diff --git a/tests/Auth/AuthServiceProviderTest.php b/tests/Auth/AuthServiceProviderTest.php index d0aa3e8ecf..60c1760894 100644 --- a/tests/Auth/AuthServiceProviderTest.php +++ b/tests/Auth/AuthServiceProviderTest.php @@ -23,12 +23,18 @@ use Hypervel\Foundation\Auth\User; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\OverriddenDouble; use PHPUnit\Framework\Attributes\DataProvider; use Swoole\Server as SwooleServer; class AuthServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testBootContributesEnabledConfiguredEloquentModelsAndFrameworkContainers(): void { $config = new ConfigRepository([ @@ -46,22 +52,16 @@ public function testBootContributesEnabledConfiguredEloquentModelsAndFrameworkCo ], ]); $resolver = null; - $manager = m::mock(CacheManager::class); - $manager->shouldReceive('allowSerializableClassesUsing') - ->once() - ->with(m::on(function (mixed $callback) use (&$resolver): bool { - $resolver = $callback; - - return $callback instanceof Closure; - })) - ->andReturnSelf(); + $manager = Double::for(CacheManager::class); + $manager->expects('allowSerializableClassesUsing') + ->with(Argument::capture($resolver)); $application = $this->consoleApplication(); - $application->shouldReceive('booted')->once(); + $application->expects('booted'); - (new AuthServiceProvider($application))->boot( + (new AuthServiceProvider($application->instance()))->boot( $manager, $config, - m::mock(GateContract::class), + Double::for(GateContract::class, override: true)->instance(), ); $this->assertInstanceOf(Closure::class, $resolver); @@ -90,37 +90,29 @@ public function testConsoleStartupValidatesEveryEnabledProviderUsingCapturedDepe ], ], ]); - $defaultRepository = m::mock(CacheRepository::class); - $redisRepository = m::mock(CacheRepository::class); - $manager = m::mock(CacheManager::class); - $manager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $manager->shouldReceive('store')->once()->with(null)->andReturn($defaultRepository); - $manager->shouldReceive('store')->once()->with('redis')->andReturn($redisRepository); - $validator = m::mock(ModelCacheStoreValidator::class); - $validator->shouldReceive('validate') - ->once() - ->with($defaultRepository, 'Auth user provider [0]'); - $validator->shouldReceive('validate') - ->once() - ->with($redisRepository, 'Auth user provider []'); + $defaultRepository = Double::for(CacheRepository::class); + $redisRepository = Double::for(CacheRepository::class); + $manager = Double::for(CacheManager::class); + $manager->expects('allowSerializableClassesUsing'); + $manager->expects('store')->with(null)->returns($defaultRepository); + $manager->expects('store')->with('redis')->returns($redisRepository); + $validator = Double::for(ModelCacheStoreValidator::class); + $validator->expects('validate') + ->with(Argument::same($defaultRepository), 'Auth user provider [0]'); + $validator->expects('validate') + ->with(Argument::same($redisRepository), 'Auth user provider []'); $bootedCallback = null; $application = $this->consoleApplication(); - $application->shouldReceive('make') - ->once() + $application->expects('make') ->with(ModelCacheStoreValidator::class) - ->andReturn($validator); - $application->shouldReceive('booted') - ->once() - ->with(m::on(function (mixed $callback) use (&$bootedCallback): bool { - $bootedCallback = $callback; - - return $callback instanceof Closure; - })); + ->returns($validator); + $application->expects('booted') + ->with(Argument::capture($bootedCallback)); - (new AuthServiceProvider($application))->boot( + (new AuthServiceProvider($application->instance()))->boot( $manager, $config, - m::mock(GateContract::class), + Double::for(GateContract::class, override: true)->instance(), ); $this->assertInstanceOf(Closure::class, $bootedCallback); @@ -148,27 +140,24 @@ public function testDisabledProvidersResolveNeitherAStoreNorTheValidator(): void ], ], ]); - $manager = m::mock(CacheManager::class); - $manager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $manager->shouldNotReceive('store'); + $manager = Double::for(CacheManager::class); + $resolver = null; + $manager->expects('allowSerializableClassesUsing') + ->with(Argument::capture($resolver)); + $manager->expects('store')->never(); $bootedCallback = null; $application = $this->consoleApplication(); - $application->shouldNotReceive('make')->with(ModelCacheStoreValidator::class); - $application->shouldReceive('booted') - ->once() - ->with(m::on(function (mixed $callback) use (&$bootedCallback): bool { - $bootedCallback = $callback; - - return $callback instanceof Closure; - })); + $application->expects('make')->never()->with(ModelCacheStoreValidator::class); + $application->expects('booted') + ->with(Argument::capture($bootedCallback)); - (new AuthServiceProvider($application))->boot( + (new AuthServiceProvider($application->instance()))->boot( $manager, $config, - m::mock(GateContract::class), + Double::for(GateContract::class, override: true)->instance(), ); - $this->assertSame([], $this->capturedResolver($manager)()); + $this->assertSame([], $resolver()); $this->assertInstanceOf(Closure::class, $bootedCallback); $bootedCallback(); } @@ -185,50 +174,41 @@ public function testServerValidationUsesWorkerDependenciesAndRunsForTaskworkers( ], ], ]); - $masterManager = m::mock(CacheManager::class); - $masterManager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $masterManager->shouldNotReceive('store'); - $workerRepository = m::mock(CacheRepository::class); - $workerManager = m::mock(CacheManager::class); - $workerManager->shouldReceive('store')->once()->with('worker')->andReturn($workerRepository); - $validator = m::mock(ModelCacheStoreValidator::class); - $validator->shouldReceive('validate') - ->once() - ->with($workerRepository, 'Auth user provider [users]'); + $masterManager = Double::for(CacheManager::class); + $masterManager->expects('allowSerializableClassesUsing'); + $masterManager->expects('store')->never(); + $workerRepository = Double::for(CacheRepository::class); + $workerManager = Double::for(CacheManager::class); + $workerManager->expects('store')->with('worker')->returns($workerRepository); + $validator = Double::for(ModelCacheStoreValidator::class); + $validator->expects('validate') + ->with(Argument::same($workerRepository), 'Auth user provider [users]'); $listener = null; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('listen') - ->once() - ->with(AfterWorkerStart::class, m::on(function (mixed $callback) use (&$listener): bool { - $listener = $callback; - - return $callback instanceof Closure; - })); - $application = m::mock(Application::class); - $application->shouldReceive('make') - ->once() + $events = Double::for(Dispatcher::class); + $events->expects('listen') + ->with(AfterWorkerStart::class, Argument::capture($listener)); + $application = Double::for(Application::class, override: true); + $application->expects('make') ->with(CacheManager::class) - ->andReturn($workerManager); - $application->shouldReceive('make') - ->once() + ->returns($workerManager); + $application->expects('make') ->with(ConfigRepositoryContract::class) - ->andReturn($workerConfig); - $application->shouldReceive('make')->once()->with('events')->andReturn($events); - $application->shouldReceive('make') - ->once() + ->returns($workerConfig); + $application->expects('make')->with('events')->returns($events); + $application->expects('make') ->with(ModelCacheStoreValidator::class) - ->andReturn($validator); - $application->shouldReceive('runningInConsole')->once()->andReturnFalse(); - $application->shouldNotReceive('booted'); + ->returns($validator); + $application->expects('runningInConsole')->returns(false); + $application->expects('booted')->never(); - (new AuthServiceProvider($application))->boot( + (new AuthServiceProvider($application->instance()))->boot( $masterManager, $masterConfig, - m::mock(GateContract::class), + Double::for(GateContract::class, override: true)->instance(), ); $this->assertInstanceOf(Closure::class, $listener); - $server = m::mock(SwooleServer::class); + $server = Double::for(SwooleServer::class); // Store validation runs in request workers and taskworkers, unlike Swoole timer registration. $server->taskworker = true; $listener(new AfterWorkerStart($server, 8)); @@ -239,26 +219,25 @@ public function testBootReplacesQueryBuilderMacrosWithFreshGate(): void $config = new ConfigRepository([ 'auth' => ['providers' => []], ]); - $firstManager = m::mock(CacheManager::class); - $firstManager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $secondManager = m::mock(CacheManager::class); - $secondManager->shouldReceive('allowSerializableClassesUsing')->once()->andReturnSelf(); - $firstGate = m::mock(GateContract::class); - $firstGate->shouldNotReceive('scope'); - $secondGate = m::mock(GateContract::class); - $secondGate->shouldReceive('scope') - ->once() - ->with('edit', m::type(EloquentBuilder::class)) - ->andReturnUsing(static fn (mixed $ability, EloquentBuilder $query): EloquentBuilder => $query); + $firstManager = Double::for(CacheManager::class); + $firstManager->expects('allowSerializableClassesUsing'); + $secondManager = Double::for(CacheManager::class); + $secondManager->expects('allowSerializableClassesUsing'); + $firstGate = Double::for(GateContract::class, override: true); + $firstGate->expects('scope')->never(); + $secondGate = Double::for(GateContract::class, override: true); + $secondGate->expects('scope') + ->with('edit', Argument::type(EloquentBuilder::class)) + ->resolves(static fn (mixed $ability, EloquentBuilder $query): EloquentBuilder => $query); $firstApplication = $this->consoleApplication(); - $firstApplication->shouldReceive('booted')->once(); + $firstApplication->expects('booted'); $secondApplication = $this->consoleApplication(); - $secondApplication->shouldReceive('booted')->once(); + $secondApplication->expects('booted'); - (new AuthServiceProvider($firstApplication))->boot($firstManager, $config, $firstGate); - (new AuthServiceProvider($secondApplication))->boot($secondManager, $config, $secondGate); + (new AuthServiceProvider($firstApplication->instance()))->boot($firstManager, $config, $firstGate->instance()); + (new AuthServiceProvider($secondApplication->instance()))->boot($secondManager, $config, $secondGate->instance()); - $query = new EloquentBuilder(m::mock(QueryBuilder::class)); + $query = new EloquentBuilder(Double::for(QueryBuilder::class)); $this->assertSame($query, $query->whereCan('edit')); } @@ -272,7 +251,7 @@ public function testStartupRequiresAnEloquentAuthenticatableModel(): void ], ], ]); - $manager = m::mock(CacheManager::class); + $manager = Double::for(CacheManager::class); $startup = $this->bootAndCaptureStartupValidation($manager, $config); $this->expectException(InvalidArgumentException::class); @@ -292,7 +271,7 @@ public function testStartupRequiresAStringOrNullStore(): void ], ], ]); - $manager = m::mock(CacheManager::class); + $manager = Double::for(CacheManager::class); $startup = $this->bootAndCaptureStartupValidation($manager, $config); $this->expectException(InvalidArgumentException::class); @@ -313,7 +292,7 @@ public function testStartupRequiresPositiveIntegerCacheTtl(mixed $ttl): void ], ], ]); - $manager = m::mock(CacheManager::class); + $manager = Double::for(CacheManager::class); $startup = $this->bootAndCaptureStartupValidation($manager, $config); $this->expectException(InvalidArgumentException::class); @@ -344,7 +323,7 @@ public function testStartupRequiresAnArrayOfStringsOrNullCacheTags(mixed $tags): ], ], ]); - $manager = m::mock(CacheManager::class); + $manager = Double::for(CacheManager::class); $startup = $this->bootAndCaptureStartupValidation($manager, $config); $this->expectException(InvalidArgumentException::class); @@ -372,17 +351,15 @@ public function testStartupValidatesTagSupportForTaggedProvider(): void ], ], ]); - $repository = m::mock(CacheRepository::class); - $manager = m::mock(CacheManager::class); - $manager->shouldReceive('store')->once()->with('redis')->andReturn($repository); - $validator = m::mock(ModelCacheStoreValidator::class); - $validator->shouldReceive('validate') - ->once() - ->with($repository, 'Auth user provider [users]'); - $validator->shouldReceive('validateAnyModeTags') - ->once() - ->with($repository, 'Auth user provider [users]') - ->andThrow(new InvalidArgumentException('TagMode::Any is required.')); + $repository = Double::for(CacheRepository::class); + $manager = Double::for(CacheManager::class); + $manager->expects('store')->with('redis')->returns($repository); + $validator = Double::for(ModelCacheStoreValidator::class); + $validator->expects('validate') + ->with(Argument::same($repository), 'Auth user provider [users]'); + $validator->expects('validateAnyModeTags') + ->with(Argument::same($repository), 'Auth user provider [users]') + ->throws(new InvalidArgumentException('TagMode::Any is required.')); $startup = $this->bootAndCaptureStartupValidation($manager, $config, $validator); $this->expectException(InvalidArgumentException::class); @@ -415,10 +392,10 @@ private function cachedProvider( /** * Create a console application double for provider boot. */ - private function consoleApplication(): Application|m\MockInterface + private function consoleApplication(): OverriddenDouble { - $application = m::mock(Application::class); - $application->shouldReceive('runningInConsole')->once()->andReturnTrue(); + $application = Double::for(Application::class, override: true); + $application->expects('runningInConsole')->returns(true); return $application; } @@ -427,60 +404,33 @@ private function consoleApplication(): Application|m\MockInterface * Boot the provider and capture its console startup validation callback. */ private function bootAndCaptureStartupValidation( - CacheManager|m\MockInterface $manager, + CacheManager&DoubleInterface $manager, ConfigRepositoryContract $config, - (ModelCacheStoreValidator&m\MockInterface)|null $validator = null, + (ModelCacheStoreValidator&DoubleInterface)|null $validator = null, ): Closure { - $manager->shouldReceive('allowSerializableClassesUsing') - ->once() - ->andReturnSelf(); + $manager->expects('allowSerializableClassesUsing'); $startup = null; $application = $this->consoleApplication(); if ($validator !== null) { - $application->shouldReceive('make') - ->once() + $application->expects('make') ->with(ModelCacheStoreValidator::class) - ->andReturn($validator); + ->returns($validator); } - $application->shouldReceive('booted') - ->once() - ->with(m::on(function (mixed $callback) use (&$startup): bool { - $startup = $callback; + $application->expects('booted') + ->with(Argument::capture($startup)); - return $callback instanceof Closure; - })); - - (new AuthServiceProvider($application))->boot( + (new AuthServiceProvider($application->instance()))->boot( $manager, $config, - m::mock(GateContract::class), + Double::for(GateContract::class, override: true)->instance(), ); $this->assertInstanceOf(Closure::class, $startup); return $startup; } - - /** - * Capture the registered class resolver from a manager mock. - */ - private function capturedResolver(CacheManager|m\MockInterface $manager): Closure - { - $resolver = null; - $manager->shouldHaveReceived('allowSerializableClassesUsing') - ->with(m::on(function (mixed $callback) use (&$resolver): bool { - $resolver = $callback; - - return $callback instanceof Closure; - })) - ->once(); - - $this->assertInstanceOf(Closure::class, $resolver); - - return $resolver; - } } class AuthProviderUser extends User diff --git a/tests/Auth/AuthenticateWithBasicAuthMiddlewareTest.php b/tests/Auth/AuthenticateWithBasicAuthMiddlewareTest.php index 6ada60a795..134d8086a1 100644 --- a/tests/Auth/AuthenticateWithBasicAuthMiddlewareTest.php +++ b/tests/Auth/AuthenticateWithBasicAuthMiddlewareTest.php @@ -10,14 +10,18 @@ use Hypervel\Container\Container; use Hypervel\Contracts\Auth\Factory as AuthFactory; use Hypervel\Contracts\Auth\Guard; +use Hypervel\Contracts\Auth\SupportsBasicAuth; use Hypervel\Http\Request; use Hypervel\Pipeline\Pipeline; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response; class AuthenticateWithBasicAuthMiddlewareTest extends TestCase { + use VerifiesDoubles; + public function testUsingGeneratesCorrectMiddlewareString(): void { $this->assertSame( @@ -38,11 +42,11 @@ public function testUsingGeneratesCorrectMiddlewareString(): void public function testItCallsBasicWithDefaultField(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('basic')->with('email')->once()->andReturnNull(); + $guard = Double::for(Guard::class, SupportsBasicAuth::class); + $guard->expects('basic')->with('email')->returns(null); - $authFactory = m::mock(AuthFactory::class); - $authFactory->shouldReceive('guard')->with(null)->andReturn($guard); + $authFactory = Double::for(AuthFactory::class); + $authFactory->expects('guard')->with(null)->returns($guard); $middleware = new AuthenticateWithBasicAuth($authFactory); $request = Request::create('/', 'GET'); @@ -55,11 +59,11 @@ public function testItCallsBasicWithDefaultField(): void public function testItCallsBasicWithCustomField(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('basic')->with('username')->once()->andReturnNull(); + $guard = Double::for(Guard::class, SupportsBasicAuth::class); + $guard->expects('basic')->with('username')->returns(null); - $authFactory = m::mock(AuthFactory::class); - $authFactory->shouldReceive('guard')->with('api')->andReturn($guard); + $authFactory = Double::for(AuthFactory::class); + $authFactory->expects('guard')->with('api')->returns($guard); $middleware = new AuthenticateWithBasicAuth($authFactory); $request = Request::create('/', 'GET'); @@ -72,11 +76,11 @@ public function testItCallsBasicWithCustomField(): void public function testItUsesSpecifiedGuard(): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('basic')->with('email')->once()->andReturnNull(); + $guard = Double::for(Guard::class, SupportsBasicAuth::class); + $guard->expects('basic')->with('email')->returns(null); - $authFactory = m::mock(AuthFactory::class); - $authFactory->shouldReceive('guard')->with('web')->andReturn($guard); + $authFactory = Double::for(AuthFactory::class); + $authFactory->expects('guard')->with('web')->returns($guard); $middleware = new AuthenticateWithBasicAuth($authFactory); $request = Request::create('/', 'GET'); @@ -97,8 +101,8 @@ public function testFieldOnlyDefinitionUsesDefaultGuard(): void ], ])); - $guard = m::mock(Guard::class); - $guard->shouldReceive('basic')->with('username')->once()->andReturnNull(); + $guard = Double::for(Guard::class, SupportsBasicAuth::class); + $guard->expects('basic')->with('username')->returns(null); $auth = new AuthManager($container); $auth->extend('basic', fn () => $guard); diff --git a/tests/Auth/AuthorizableTest.php b/tests/Auth/AuthorizableTest.php index 093501fc23..c2524cbed6 100644 --- a/tests/Auth/AuthorizableTest.php +++ b/tests/Auth/AuthorizableTest.php @@ -9,19 +9,23 @@ use Hypervel\Contracts\Auth\Access\Gate; use Hypervel\Tests\Auth\Fixtures\AuthorizableStub; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\OverriddenDouble; class AuthorizableTest extends TestCase { + use VerifiesDoubles; + public function testAuthorize(): void { $user = new AuthorizableStub; $gate = $this->mockGate(); $response = Response::allow(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('authorize')->with('foo', ['bar'])->once()->andReturn($response); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('authorize')->with('foo', ['bar'])->returns($response); $this->assertSame($response, $user->authorize('foo', ['bar'])); } @@ -31,8 +35,8 @@ public function testCan(): void $user = new AuthorizableStub; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('check')->with('foo', ['bar'])->once()->andReturnTrue(); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('check')->with('foo', ['bar'])->returns(true); $this->assertTrue($user->can('foo', ['bar'])); } @@ -42,8 +46,8 @@ public function testCanAny(): void $user = new AuthorizableStub; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('any')->with(['foo'], ['bar'])->once()->andReturnTrue(); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('any')->with(['foo'], ['bar'])->returns(true); $this->assertTrue($user->canAny(['foo'], ['bar'])); } @@ -53,8 +57,8 @@ public function testCant(): void $user = new AuthorizableStub; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('check')->with('foo', ['bar'])->once()->andReturnTrue(); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('check')->with('foo', ['bar'])->returns(true); $this->assertFalse($user->cant('foo', ['bar'])); } @@ -64,8 +68,8 @@ public function testCannot(): void $user = new AuthorizableStub; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('check')->with('foo', ['bar'])->once()->andReturnTrue(); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('check')->with('foo', ['bar'])->returns(true); $this->assertFalse($user->cannot('foo', ['bar'])); } @@ -75,8 +79,8 @@ public function testCanAcceptsUnitEnumAbilities(): void $user = new AuthorizableStub; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('check')->with(AuthorizableTestAbility::ManageUsers, ['bar'])->once()->andReturnTrue(); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('check')->with(AuthorizableTestAbility::ManageUsers, ['bar'])->returns(true); $this->assertTrue($user->can(AuthorizableTestAbility::ManageUsers, ['bar'])); } @@ -86,8 +90,8 @@ public function testCanAnyAcceptsUnitEnumAbilities(): void $user = new AuthorizableStub; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('any')->with(AuthorizableTestAbility::ManageUsers, ['bar'])->once()->andReturnTrue(); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('any')->with(AuthorizableTestAbility::ManageUsers, ['bar'])->returns(true); $this->assertTrue($user->canAny(AuthorizableTestAbility::ManageUsers, ['bar'])); } @@ -97,8 +101,8 @@ public function testCantAcceptsUnitEnumAbilities(): void $user = new AuthorizableStub; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('check')->with(AuthorizableTestAbility::ManageUsers, ['bar'])->once()->andReturnTrue(); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('check')->with(AuthorizableTestAbility::ManageUsers, ['bar'])->returns(true); $this->assertFalse($user->cant(AuthorizableTestAbility::ManageUsers, ['bar'])); } @@ -108,21 +112,21 @@ public function testCannotAcceptsUnitEnumAbilities(): void $user = new AuthorizableStub; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('check')->with(AuthorizableTestAbility::ManageUsers, ['bar'])->once()->andReturnTrue(); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('check')->with(AuthorizableTestAbility::ManageUsers, ['bar'])->returns(true); $this->assertFalse($user->cannot(AuthorizableTestAbility::ManageUsers, ['bar'])); } /** - * @return Gate|MockInterface + * Create and bind an authorization gate double. */ - private function mockGate(): Gate + private function mockGate(): OverriddenDouble { - $gate = m::mock(Gate::class); + $gate = Double::for(Gate::class, override: true); $container = new Container; - $container->instance(Gate::class, $gate); + $container->instance(Gate::class, $gate->instance()); Container::setInstance($container); return $gate; diff --git a/tests/Auth/AuthorizesRequestsTest.php b/tests/Auth/AuthorizesRequestsTest.php index 74eaadb1b6..b7ee3d7b80 100644 --- a/tests/Auth/AuthorizesRequestsTest.php +++ b/tests/Auth/AuthorizesRequestsTest.php @@ -10,57 +10,61 @@ use Hypervel\Database\Eloquent\Model; use Hypervel\Tests\Auth\Fixtures\AuthorizesRequestsStub; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use JMac\Testing\OverriddenDouble; use stdClass; class AuthorizesRequestsTest extends TestCase { + use VerifiesDoubles; + public function testAuthorize(): void { - $response = m::mock(Response::class); + $response = Response::allow(); $gate = $this->mockGate(); - $gate->shouldReceive('authorize')->with('foo', ['bar'])->once()->andReturn($response); + $gate->expects('authorize')->with('foo', ['bar'])->returns($response); - $this->assertEquals($response, (new AuthorizesRequestsStub)->authorize('foo', ['bar'])); + $this->assertSame($response, (new AuthorizesRequestsStub)->authorize('foo', ['bar'])); } public function testAuthorizeMayBeGuessedPassingModelInstance(): void { $model = new class extends Model {}; - $response = m::mock(Response::class); + $response = Response::allow(); $gate = $this->mockGate(); - $gate->shouldReceive('authorize')->with(__FUNCTION__, $model)->once()->andReturn($response); + $gate->expects('authorize')->with(__FUNCTION__, Argument::same($model))->returns($response); - $this->assertEquals($response, (new AuthorizesRequestsStub)->authorize($model)); + $this->assertSame($response, (new AuthorizesRequestsStub)->authorize($model)); } public function testAuthorizeMayBeGuessedPassingClassName(): void { $class = Model::class; - $response = m::mock(Response::class); + $response = Response::allow(); $gate = $this->mockGate(); - $gate->shouldReceive('authorize')->with(__FUNCTION__, $class)->once()->andReturn($response); + $gate->expects('authorize')->with(__FUNCTION__, $class)->returns($response); - $this->assertEquals($response, (new AuthorizesRequestsStub)->authorize($class)); + $this->assertSame($response, (new AuthorizesRequestsStub)->authorize($class)); } public function testAuthorizeMayBeGuessedAndNormalized(): void { $model = new class extends Model {}; - $response = m::mock(Response::class); + $response = Response::allow(); $gate = $this->mockGate(); - $gate->shouldReceive('authorize')->with('create', $model)->once()->andReturn($response); + $gate->expects('authorize')->with('create', Argument::same($model))->returns($response); - $this->assertEquals($response, (new class extends AuthorizesRequestsStub { + $this->assertSame($response, (new class extends AuthorizesRequestsStub { public function store($model) { return $this->authorize($model); @@ -70,26 +74,26 @@ public function store($model) public function testAuthorizeForUserDelegatesToGateForUser(): void { - $response = m::mock(Response::class); + $response = Response::allow(); $user = new stdClass; $gate = $this->mockGate(); - $gate->shouldReceive('forUser')->with($user)->once()->andReturnSelf(); - $gate->shouldReceive('authorize')->with('foo', ['bar'])->once()->andReturn($response); + $gate->expects('forUser')->with(Argument::same($user)); + $gate->expects('authorize')->with('foo', ['bar'])->returns($response); - $this->assertEquals($response, (new AuthorizesRequestsStub)->authorizeForUser($user, 'foo', ['bar'])); + $this->assertSame($response, (new AuthorizesRequestsStub)->authorizeForUser($user, 'foo', ['bar'])); } /** - * @return Gate|MockInterface + * Create and bind an authorization gate double. */ - private function mockGate(): Gate + private function mockGate(): OverriddenDouble { - $gate = m::mock(Gate::class); + $gate = Double::for(Gate::class, override: true); $container = new Container; - $container->instance(Gate::class, $gate); + $container->instance(Gate::class, $gate->instance()); Container::setInstance($container); return $gate; diff --git a/tests/Auth/CacheTokenRepositoryTest.php b/tests/Auth/CacheTokenRepositoryTest.php index 7cf8e56575..f2de676f54 100644 --- a/tests/Auth/CacheTokenRepositoryTest.php +++ b/tests/Auth/CacheTokenRepositoryTest.php @@ -10,22 +10,25 @@ use Hypervel\Contracts\Hashing\Hasher; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CacheTokenRepositoryTest extends TestCase { + use VerifiesDoubles; + public function testCreateStoresHashedTokenAndReturnsPlainToken(): void { CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0)); - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); - $hasher->shouldReceive('make')->once()->andReturnUsing(fn ($token) => 'hashed_' . $token); - $cache->shouldReceive('forget')->once(); // delete() called first - $cache->shouldReceive('put')->once()->andReturnUsing(function ($key, $value, $ttl) { + $hasher->expects('make')->resolves(fn ($token) => 'hashed_' . $token); + $cache->expects('forget'); // delete() called first + $cache->expects('put')->resolves(function ($key, $value, $ttl) { $this->assertIsString($key); $this->assertIsArray($value); $this->assertCount(2, $value); @@ -47,16 +50,16 @@ public function testExistsReturnsTrueForValidToken(): void { CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0)); - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); - $cache->shouldReceive('get')->once()->andReturn([ + $cache->expects('get')->returns([ 'hashed_token', '2024-01-01 11:59:00', // Created 1 minute ago ]); - $hasher->shouldReceive('check')->with('plain_token', 'hashed_token')->andReturnTrue(); + $hasher->expects('check')->with('plain_token', 'hashed_token')->returns(true); $repository = new CacheTokenRepository($cache, $hasher, 'test-hash-key', 3600); @@ -67,12 +70,13 @@ public function testExistsReturnsFalseForExpiredToken(): void { CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0)); - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $hasher->expects('check')->never(); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); - $cache->shouldReceive('get')->once()->andReturn([ + $cache->expects('get')->returns([ 'hashed_token', '2024-01-01 10:00:00', // Created 2 hours ago, expired with 3600s TTL ]); @@ -86,16 +90,16 @@ public function testExistsReturnsFalseForInvalidHash(): void { CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0)); - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); - $cache->shouldReceive('get')->once()->andReturn([ + $cache->expects('get')->returns([ 'hashed_token', '2024-01-01 11:59:00', ]); - $hasher->shouldReceive('check')->with('wrong_token', 'hashed_token')->andReturnFalse(); + $hasher->expects('check')->with('wrong_token', 'hashed_token')->returns(false); $repository = new CacheTokenRepository($cache, $hasher, 'test-hash-key', 3600); @@ -106,12 +110,12 @@ public function testRecentlyCreatedTokenReturnsTrueWithinThrottle(): void { CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0)); - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); - $cache->shouldReceive('get')->once()->andReturn([ + $cache->expects('get')->returns([ 'hashed_token', '2024-01-01 11:59:30', // Created 30 seconds ago ]); @@ -126,12 +130,12 @@ public function testRecentlyCreatedTokenReturnsFalseAfterThrottle(): void { CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0)); - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); - $cache->shouldReceive('get')->once()->andReturn([ + $cache->expects('get')->returns([ 'hashed_token', '2024-01-01 11:58:00', // Created 2 minutes ago ]); @@ -146,12 +150,12 @@ public function testRecentlyCreatedTokenReturnsFalseWhenThrottleIsZero(): void { CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0)); - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); - $cache->shouldReceive('get')->once()->andReturn([ + $cache->expects('get')->returns([ 'hashed_token', '2024-01-01 11:59:59', // Created 1 second ago ]); @@ -164,13 +168,13 @@ public function testRecentlyCreatedTokenReturnsFalseWhenThrottleIsZero(): void public function testDeleteRemovesFromCache(): void { - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); $expectedKey = hash('sha256', 'foo@bar.com'); - $cache->shouldReceive('forget')->with($expectedKey)->once(); + $cache->expects('forget')->with($expectedKey); $repository = new CacheTokenRepository($cache, $hasher, 'test-hash-key'); $repository->delete($user); @@ -178,10 +182,10 @@ public function testDeleteRemovesFromCache(): void public function testCacheKeyHashesEmail(): void { - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); - $user = m::mock(CanResetPassword::class); - $user->shouldReceive('getEmailForPasswordReset')->andReturn('foo@bar.com'); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); + $user = Double::for(CanResetPassword::class); + $user->allows('getEmailForPasswordReset')->returns('foo@bar.com'); $repository = new CacheTokenRepository($cache, $hasher, 'test-hash-key'); @@ -190,14 +194,14 @@ public function testCacheKeyHashesEmail(): void public function testDeleteExpiredIsNoOp(): void { - $cache = m::mock(Repository::class); - $hasher = m::mock(Hasher::class); + $cache = Double::for(Repository::class); + $hasher = Double::for(Hasher::class); // No cache interaction expected — TTL handles expiry $repository = new CacheTokenRepository($cache, $hasher, 'test-hash-key'); $repository->deleteExpired(); - // If we get here without exceptions, it's a no-op as expected - $this->assertTrue(true); + $cache->unused(); + $hasher->unused(); } } diff --git a/tests/Auth/ClearResetsCommandTest.php b/tests/Auth/ClearResetsCommandTest.php index d2cbea6c97..5ec845ca30 100644 --- a/tests/Auth/ClearResetsCommandTest.php +++ b/tests/Auth/ClearResetsCommandTest.php @@ -10,34 +10,37 @@ use Hypervel\Auth\Passwords\TokenRepositoryInterface; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class ClearResetsCommandTest extends TestCase { + use VerifiesDoubles; + public function testClearsExpiredTokensThroughDefaultBroker(): void { - $command = $this->makeCommand($manager = m::mock(PasswordBrokerManager::class)); - $broker = m::mock(PasswordBroker::class); - $repository = m::mock(TokenRepositoryInterface::class); + $command = $this->makeCommand($manager = Double::for(PasswordBrokerManager::class)); + $broker = Double::for(PasswordBroker::class); + $repository = Double::for(TokenRepositoryInterface::class); - $manager->shouldReceive('broker')->once()->with(null)->andReturn($broker); - $broker->shouldReceive('getRepository')->once()->andReturn($repository); - $repository->shouldReceive('deleteExpired')->once(); + $manager->expects('broker')->with(null)->returns($broker); + $broker->expects('getRepository')->returns($repository); + $repository->expects('deleteExpired'); $this->assertSame(0, $this->runCommand($command)); } public function testClearsExpiredTokensThroughNamedBroker(): void { - $command = $this->makeCommand($manager = m::mock(PasswordBrokerManager::class)); - $broker = m::mock(PasswordBroker::class); - $repository = m::mock(TokenRepositoryInterface::class); + $command = $this->makeCommand($manager = Double::for(PasswordBrokerManager::class)); + $broker = Double::for(PasswordBroker::class); + $repository = Double::for(TokenRepositoryInterface::class); - $manager->shouldReceive('broker')->once()->with('admins')->andReturn($broker); - $broker->shouldReceive('getRepository')->once()->andReturn($repository); - $repository->shouldReceive('deleteExpired')->once(); + $manager->expects('broker')->with('admins')->returns($broker); + $broker->expects('getRepository')->returns($repository); + $repository->expects('deleteExpired'); $this->assertSame(0, $this->runCommand($command, ['name' => 'admins'])); } diff --git a/tests/Auth/EnsureEmailIsVerifiedTest.php b/tests/Auth/EnsureEmailIsVerifiedTest.php index 1492e9f52c..a298e86202 100644 --- a/tests/Auth/EnsureEmailIsVerifiedTest.php +++ b/tests/Auth/EnsureEmailIsVerifiedTest.php @@ -9,12 +9,15 @@ use Hypervel\Contracts\Auth\MustVerifyEmail; use Hypervel\Http\Request; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpException; class EnsureEmailIsVerifiedTest extends TestCase { + use VerifiesDoubles; + public function testItCanGenerateDefinitionViaStaticMethod(): void { $signature = EnsureEmailIsVerified::redirectTo('route.name'); @@ -23,15 +26,15 @@ public function testItCanGenerateDefinitionViaStaticMethod(): void public function testVerifiedUserPassesThrough(): void { - $user = m::mock(Authenticatable::class . ',' . MustVerifyEmail::class); - $user->shouldReceive('hasVerifiedEmail')->andReturnTrue(); + $user = Double::for(Authenticatable::class, MustVerifyEmail::class); + $user->allows('hasVerifiedEmail')->returns(true); - $request = m::mock(Request::class); - $request->shouldReceive('user')->andReturn($user); + $request = Double::for(Request::class, override: true); + $request->allows('user')->returns($user); $expectedResponse = new Response('ok'); $middleware = new EnsureEmailIsVerified; - $result = $middleware->handle($request, fn () => $expectedResponse); + $result = $middleware->handle($request->instance(), fn () => $expectedResponse); $this->assertSame($expectedResponse, $result); } @@ -39,43 +42,43 @@ public function testVerifiedUserPassesThrough(): void public function testUserThatDoesNotImplementMustVerifyEmailPassesThrough(): void { // User implements Authenticatable but does not implement MustVerifyEmail. - $user = m::mock(Authenticatable::class); + $user = Double::for(Authenticatable::class); - $request = m::mock(Request::class); - $request->shouldReceive('user')->andReturn($user); + $request = Double::for(Request::class, override: true); + $request->allows('user')->returns($user); $expectedResponse = new Response('ok'); $middleware = new EnsureEmailIsVerified; - $result = $middleware->handle($request, fn () => $expectedResponse); + $result = $middleware->handle($request->instance(), fn () => $expectedResponse); $this->assertSame($expectedResponse, $result); } public function testGuestRequestReturnsJsonWhenExpectsJson(): void { - $request = m::mock(Request::class); - $request->shouldReceive('user')->andReturn(null); - $request->shouldReceive('expectsJson')->andReturnTrue(); + $request = Double::for(Request::class, override: true); + $request->allows('user')->returns(null); + $request->allows('expectsJson')->returns(true); $this->expectException(HttpException::class); $middleware = new EnsureEmailIsVerified; - $middleware->handle($request, fn () => new Response('should not reach')); + $middleware->handle($request->instance(), fn () => new Response('should not reach')); } public function testUnverifiedUserReturnsJsonWhenExpectsJson(): void { - $user = m::mock(Authenticatable::class . ',' . MustVerifyEmail::class); - $user->shouldReceive('hasVerifiedEmail')->andReturnFalse(); + $user = Double::for(Authenticatable::class, MustVerifyEmail::class); + $user->allows('hasVerifiedEmail')->returns(false); - $request = m::mock(Request::class); - $request->shouldReceive('user')->andReturn($user); - $request->shouldReceive('expectsJson')->andReturnTrue(); + $request = Double::for(Request::class, override: true); + $request->allows('user')->returns($user); + $request->allows('expectsJson')->returns(true); $this->expectException(HttpException::class); $middleware = new EnsureEmailIsVerified; - $middleware->handle($request, fn () => new Response('should not reach')); + $middleware->handle($request->instance(), fn () => new Response('should not reach')); } public function testUnverifiedUserRedirectsWhenNotJson(): void @@ -83,15 +86,15 @@ public function testUnverifiedUserRedirectsWhenNotJson(): void // Register a named route so URL::route() can resolve it $this->app->make('router')->get('/email/verify', fn () => 'verify')->name('verify.email'); - $user = m::mock(Authenticatable::class . ',' . MustVerifyEmail::class); - $user->shouldReceive('hasVerifiedEmail')->andReturnFalse(); + $user = Double::for(Authenticatable::class, MustVerifyEmail::class); + $user->allows('hasVerifiedEmail')->returns(false); - $request = m::mock(Request::class); - $request->shouldReceive('user')->andReturn($user); - $request->shouldReceive('expectsJson')->andReturnFalse(); + $request = Double::for(Request::class, override: true); + $request->allows('user')->returns($user); + $request->allows('expectsJson')->returns(false); $middleware = new EnsureEmailIsVerified; - $result = $middleware->handle($request, fn () => new Response('should not reach'), 'verify.email'); + $result = $middleware->handle($request->instance(), fn () => new Response('should not reach'), 'verify.email'); $this->assertSame(302, $result->getStatusCode()); } @@ -100,12 +103,12 @@ public function testGuestRequestRedirectsWhenNotJson(): void { $this->app->make('router')->get('/email/verify', fn () => 'verify')->name('verify.email'); - $request = m::mock(Request::class); - $request->shouldReceive('user')->andReturn(null); - $request->shouldReceive('expectsJson')->andReturnFalse(); + $request = Double::for(Request::class, override: true); + $request->allows('user')->returns(null); + $request->allows('expectsJson')->returns(false); $middleware = new EnsureEmailIsVerified; - $result = $middleware->handle($request, fn () => new Response('should not reach'), 'verify.email'); + $result = $middleware->handle($request->instance(), fn () => new Response('should not reach'), 'verify.email'); $this->assertSame(302, $result->getStatusCode()); } diff --git a/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php b/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php index ff720c7512..fdcc1cb2df 100644 --- a/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php +++ b/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php @@ -17,11 +17,14 @@ use Hypervel\Http\Request; use Hypervel\Support\Facades\Auth; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response; class RedirectIfAuthenticatedMiddlewareTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -96,15 +99,15 @@ public function testDefaultRedirectFallsBackToSlash(): void public function testMultipleGuardsRedirectsIfAnyAuthenticated(): void { - $guestGuard = m::mock(Guard::class); - $guestGuard->shouldReceive('check')->andReturn(false); + $guestGuard = Double::for(Guard::class); + $guestGuard->allows('check')->returns(false); - $authGuard = m::mock(Guard::class); - $authGuard->shouldReceive('check')->andReturn(true); + $authGuard = Double::for(Guard::class); + $authGuard->allows('check')->returns(true); - $factory = m::mock(AuthFactory::class); - $factory->shouldReceive('guard')->with('web')->andReturn($guestGuard); - $factory->shouldReceive('guard')->with('api')->andReturn($authGuard); + $factory = Double::for(AuthFactory::class); + $factory->expects('guard')->with('web')->returns($guestGuard); + $factory->expects('guard')->with('api')->returns($authGuard); Auth::swap($factory); $request = Request::create('/login', 'GET'); @@ -117,16 +120,16 @@ public function testMultipleGuardsRedirectsIfAnyAuthenticated(): void public function testPassesThroughWhenAllGuardsAreGuests(): void { - $guard1 = m::mock(Guard::class); - $guard1->shouldReceive('check')->andReturn(false); + $guard1 = Double::for(Guard::class); + $guard1->allows('check')->returns(false); - $guard2 = m::mock(Guard::class); - $guard2->shouldReceive('check')->andReturn(false); + $guard2 = Double::for(Guard::class); + $guard2->allows('check')->returns(false); - $factory = m::mock(AuthFactory::class); - $factory->shouldReceive('guard')->with('web')->andReturn($guard1); - $factory->shouldReceive('guard')->with('api')->andReturn($guard2); - $factory->shouldReceive('shouldUse')->once()->with('web'); + $factory = Double::for(AuthFactory::class); + $factory->expects('guard')->with('web')->returns($guard1); + $factory->expects('guard')->with('api')->returns($guard2); + $factory->expects('shouldUse')->with('web'); Auth::swap($factory); $request = Request::create('/login', 'GET'); @@ -237,11 +240,11 @@ public function testFlushStateClearsRedirectCallback(): void */ protected function swapAuthGuard(bool $authenticated): void { - $guard = m::mock(Guard::class); - $guard->shouldReceive('check')->andReturn($authenticated); + $guard = Double::for(Guard::class); + $guard->allows('check')->returns($authenticated); - $factory = m::mock(AuthFactory::class); - $factory->shouldReceive('guard')->andReturn($guard); + $factory = Double::for(AuthFactory::class); + $factory->allows('guard')->returns($guard); Auth::swap($factory); } @@ -265,16 +268,16 @@ protected function makeAuthManager(bool $webAuthenticated, bool $secondaryAuthen $auth->extend('web', fn (): RequestGuard => new RequestGuard( 'web', - static fn (): ?Authenticatable => $webAuthenticated ? m::mock(Authenticatable::class) : null, + static fn (): ?Authenticatable => $webAuthenticated ? Double::for(Authenticatable::class) : null, $container, - m::mock(EloquentUserProvider::class), + Double::for(EloquentUserProvider::class), )); $auth->extend('secondary', fn (): RequestGuard => new RequestGuard( 'secondary', - static fn (): ?Authenticatable => $secondaryAuthenticated ? m::mock(Authenticatable::class) : null, + static fn (): ?Authenticatable => $secondaryAuthenticated ? Double::for(Authenticatable::class) : null, $container, - m::mock(EloquentUserProvider::class), + Double::for(EloquentUserProvider::class), )); return $auth; diff --git a/tests/Auth/RequirePasswordMiddlewareTest.php b/tests/Auth/RequirePasswordMiddlewareTest.php index 1274cdd29d..5c74cbe1b9 100644 --- a/tests/Auth/RequirePasswordMiddlewareTest.php +++ b/tests/Auth/RequirePasswordMiddlewareTest.php @@ -14,35 +14,37 @@ use Hypervel\Http\Request; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response; class RequirePasswordMiddlewareTest extends TestCase { + use VerifiesDoubles; + public function testReturnsJson423WhenStaleAndRequestExpectsJson(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(20000)); - $session = m::mock(Session::class); - $session->shouldReceive('get') + $session = Double::for(Session::class); + $session->expects('get') ->with('auth.password_confirmed_at_web', 0) - ->andReturn(0); // Never confirmed + ->returns(0); // Never confirmed - $request = m::mock(Request::class); - $request->shouldReceive('session')->andReturn($session); - $request->shouldReceive('expectsJson')->andReturnTrue(); + $request = Double::for(Request::class, override: true); + $request->allows('session')->returns($session); + $request->allows('expectsJson')->returns(true); $jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423); - $responseFactory = m::mock(ResponseFactory::class); - $responseFactory->shouldReceive('json') + $responseFactory = Double::for(ResponseFactory::class); + $responseFactory->expects('json') ->with(['message' => 'Password confirmation required.'], 423) - ->once() - ->andReturn($jsonResponse); + ->returns($jsonResponse); - $urlGenerator = m::mock(UrlGenerator::class); + $urlGenerator = Double::for(UrlGenerator::class); $middleware = $this->middleware(responseFactory: $responseFactory, urlGenerator: $urlGenerator); - $result = $middleware->handle($request, fn () => new Response('should not reach')); + $result = $middleware->handle($request->instance(), fn () => new Response('should not reach')); $this->assertSame($jsonResponse, $result); @@ -53,34 +55,33 @@ public function testCustomTimeoutIsHonored(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1000)); - $session = m::mock(Session::class); - $session->shouldReceive('get') + $session = Double::for(Session::class); + $session->expects('get')->times(2) ->with('auth.password_confirmed_at_web', 0) - ->andReturn(990); // Confirmed 10 seconds ago + ->returns(990); // Confirmed 10 seconds ago - $request = m::mock(Request::class); - $request->shouldReceive('session')->andReturn($session); + $request = Double::for(Request::class, override: true); + $request->allows('session')->returns($session); - $responseFactory = m::mock(ResponseFactory::class); - $urlGenerator = m::mock(UrlGenerator::class); + $responseFactory = Double::for(ResponseFactory::class); + $urlGenerator = Double::for(UrlGenerator::class); $middleware = $this->middleware(responseFactory: $responseFactory, urlGenerator: $urlGenerator); // With default timeout (10800), 10 seconds would pass through $expectedResponse = new Response('ok'); - $result = $middleware->handle($request, fn () => $expectedResponse); + $result = $middleware->handle($request->instance(), fn () => $expectedResponse); $this->assertSame($expectedResponse, $result); // With custom timeout of 5 seconds, 10 seconds ago is stale - $request->shouldReceive('expectsJson')->andReturnTrue(); + $request->allows('expectsJson')->returns(true); $jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423); - $responseFactory->shouldReceive('json') + $responseFactory->expects('json') ->with(['message' => 'Password confirmation required.'], 423) - ->once() - ->andReturn($jsonResponse); + ->returns($jsonResponse); $result = $middleware->handle( - $request, + $request->instance(), fn () => new Response('should not reach'), null, 5, @@ -94,23 +95,22 @@ public function testConfirmationIsScopedToCurrentGuard(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(20000)); - $session = m::mock(Session::class); - $session->shouldReceive('get') + $session = Double::for(Session::class); + $session->expects('get') ->with('auth.password_confirmed_at_admin', 0) - ->andReturn(0); + ->returns(0); - $request = m::mock(Request::class); - $request->shouldReceive('session')->andReturn($session); - $request->shouldReceive('expectsJson')->andReturnTrue(); + $request = Double::for(Request::class, override: true); + $request->allows('session')->returns($session); + $request->allows('expectsJson')->returns(true); - $responseFactory = m::mock(ResponseFactory::class); - $responseFactory->shouldReceive('json') + $responseFactory = Double::for(ResponseFactory::class); + $responseFactory->expects('json') ->with(['message' => 'Password confirmation required.'], 423) - ->once() - ->andReturn($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423)); + ->returns($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423)); $result = $this->middleware(responseFactory: $responseFactory, guard: 'admin') - ->handle($request, fn () => new Response('should not reach')); + ->handle($request->instance(), fn () => new Response('should not reach')); $this->assertSame($jsonResponse, $result); @@ -121,20 +121,19 @@ public function testPerGuardTimeoutIsHonored(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1000)); - $session = m::mock(Session::class); - $session->shouldReceive('get') + $session = Double::for(Session::class); + $session->expects('get') ->with('auth.password_confirmed_at_admin', 0) - ->twice() - ->andReturn(989, 991); + ->times(2) + ->returns(989, 991); - $request = m::mock(Request::class); - $request->shouldReceive('session')->andReturn($session); + $request = Double::for(Request::class, override: true); + $request->allows('session')->returns($session); - $responseFactory = m::mock(ResponseFactory::class); - $responseFactory->shouldReceive('json') + $responseFactory = Double::for(ResponseFactory::class); + $responseFactory->expects('json') ->with(['message' => 'Password confirmation required.'], 423) - ->once() - ->andReturn($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423)); + ->returns($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423)); $config = new Repository([ 'auth' => [ @@ -148,12 +147,12 @@ public function testPerGuardTimeoutIsHonored(): void $middleware = $this->middleware(responseFactory: $responseFactory, config: $config, guard: 'admin'); - $request->shouldReceive('expectsJson')->andReturnTrue(); - $result = $middleware->handle($request, fn () => new Response('should not reach')); + $request->allows('expectsJson')->returns(true); + $result = $middleware->handle($request->instance(), fn () => new Response('should not reach')); $this->assertSame($jsonResponse, $result); $expectedResponse = new Response('ok'); - $result = $middleware->handle($request, fn () => $expectedResponse); + $result = $middleware->handle($request->instance(), fn () => $expectedResponse); $this->assertSame($expectedResponse, $result); CarbonImmutable::setTestNow(); @@ -163,20 +162,19 @@ public function testRouteParameterOverridesPerGuardTimeout(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1000)); - $session = m::mock(Session::class); - $session->shouldReceive('get') + $session = Double::for(Session::class); + $session->expects('get') ->with('auth.password_confirmed_at_admin', 0) - ->andReturn(994); + ->returns(994); - $request = m::mock(Request::class); - $request->shouldReceive('session')->andReturn($session); - $request->shouldReceive('expectsJson')->andReturnTrue(); + $request = Double::for(Request::class, override: true); + $request->allows('session')->returns($session); + $request->allows('expectsJson')->returns(true); - $responseFactory = m::mock(ResponseFactory::class); - $responseFactory->shouldReceive('json') + $responseFactory = Double::for(ResponseFactory::class); + $responseFactory->expects('json') ->with(['message' => 'Password confirmation required.'], 423) - ->once() - ->andReturn($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423)); + ->returns($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423)); $config = new Repository([ 'auth' => [ @@ -189,7 +187,7 @@ public function testRouteParameterOverridesPerGuardTimeout(): void ]); $result = $this->middleware(responseFactory: $responseFactory, config: $config, guard: 'admin') - ->handle($request, fn () => new Response('should not reach'), null, 5); + ->handle($request->instance(), fn () => new Response('should not reach'), null, 5); $this->assertSame($jsonResponse, $result); @@ -205,12 +203,12 @@ private function middleware( ?Repository $config = null, string $guard = 'web' ): RequirePassword { - $auth = m::mock(AuthFactory::class); - $auth->shouldReceive('getDefaultDriver')->andReturn($guard); + $auth = Double::for(AuthFactory::class); + $auth->allows('getDefaultDriver')->returns($guard); return new RequirePassword( - $responseFactory ?? m::mock(ResponseFactory::class), - $urlGenerator ?? m::mock(UrlGenerator::class), + $responseFactory ?? Double::for(ResponseFactory::class), + $urlGenerator ?? Double::for(UrlGenerator::class), $auth, $config ?? new Repository([ 'auth' => [ diff --git a/tests/Auth/TimeboxIsolationTest.php b/tests/Auth/TimeboxIsolationTest.php index 64b77c1c02..1fca51ea83 100644 --- a/tests/Auth/TimeboxIsolationTest.php +++ b/tests/Auth/TimeboxIsolationTest.php @@ -15,31 +15,35 @@ use Hypervel\Contracts\Session\Session; use Hypervel\Support\Timebox; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; class TimeboxIsolationTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('guardOperationProvider')] public function testGuardOperationsUseIndependentTimeboxes(string $operation): void { $recorder = new TimeboxOperationRecorder; $timebox = new TrackingTimebox($recorder); - $provider = m::mock(UserProvider::class); - $user = m::mock(Authenticatable::class); + $provider = Double::for(UserProvider::class); + $user = Double::for(Authenticatable::class); - $provider->shouldReceive('retrieveByCredentials')->twice()->andReturn($user, null); - $provider->shouldReceive('validateCredentials')->once()->with($user, ['email' => 'test@example.com'])->andReturn(true); + $provider->expects('retrieveByCredentials')->times(2)->returns($user, null); + $provider->expects('validateCredentials')->with(Argument::same($user), ['email' => 'test@example.com'])->returns(true); if ($operation !== 'validate') { - $provider->shouldReceive('rehashPasswordIfRequired')->once()->with($user, ['email' => 'test@example.com']); + $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), ['email' => 'test@example.com']); } $guard = new TrackingSessionGuard( 'web', $provider, - m::mock(Session::class), - m::mock(Container::class), + Double::for(Session::class), + Double::for(Container::class, override: true)->instance(), $timebox, timeboxDuration: 1_000_000, ); @@ -65,11 +69,11 @@ public function testSendingResetLinksUsesIndependentTimeboxes(): void { $recorder = new TimeboxOperationRecorder; $timebox = new TrackingTimebox($recorder); - $users = m::mock(UserProvider::class); - $users->shouldReceive('retrieveByCredentials')->twice()->with(['email' => 'missing@example.com'])->andReturnNull(); + $users = Double::for(UserProvider::class); + $users->expects('retrieveByCredentials')->times(2)->with(['email' => 'missing@example.com'])->returns(null); $broker = new PasswordBroker( - m::mock(TokenRepositoryInterface::class), + Double::for(TokenRepositoryInterface::class), $users, 'users', timebox: $timebox, @@ -87,21 +91,21 @@ public function testPasswordResetsUseIndependentTimeboxes(): void { $recorder = new TimeboxOperationRecorder; $timebox = new TrackingTimebox($recorder); - $tokens = m::mock(TokenRepositoryInterface::class); - $users = m::mock(UserProvider::class); - $user = m::mock(Authenticatable::class . ',' . CanResetPassword::class); + $tokens = Double::for(TokenRepositoryInterface::class); + $users = Double::for(UserProvider::class); + $user = Double::for(Authenticatable::class, CanResetPassword::class); $credentials = [ 'email' => 'test@example.com', 'password' => 'secret', 'token' => 'token', ]; - $users->shouldReceive('retrieveByCredentials') - ->twice() + $users->expects('retrieveByCredentials') + ->times(2) ->with(['email' => 'test@example.com', 'password' => 'secret']) - ->andReturn($user, null); - $tokens->shouldReceive('exists')->once()->with($user, 'token')->andReturnTrue(); - $tokens->shouldReceive('delete')->once()->with($user); + ->returns($user, null); + $tokens->expects('exists')->with(Argument::same($user), 'token')->returns(true); + $tokens->expects('delete')->with(Argument::same($user)); $broker = new PasswordBroker( $tokens, diff --git a/tests/Auth/UseGuardMiddlewareTest.php b/tests/Auth/UseGuardMiddlewareTest.php index 696b8d55aa..5db0326ff3 100644 --- a/tests/Auth/UseGuardMiddlewareTest.php +++ b/tests/Auth/UseGuardMiddlewareTest.php @@ -14,17 +14,20 @@ use Hypervel\Contracts\Auth\Factory as AuthFactory; use Hypervel\Http\Request; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Response; use function Hypervel\Coroutine\parallel; class UseGuardMiddlewareTest extends TestCase { + use VerifiesDoubles; + public function testItSelectsTheGuardForTheCurrentRequest(): void { - $auth = m::mock(AuthFactory::class); - $auth->shouldReceive('shouldUse')->once()->with('admin'); + $auth = Double::for(AuthFactory::class); + $auth->expects('shouldUse')->with('admin'); $request = Request::create('/login'); $response = new Response('ok'); @@ -87,7 +90,7 @@ private function makeAuthManager(): AuthManager $guard, static fn (): ?Authenticatable => null, $container, - m::mock(EloquentUserProvider::class), + Double::for(EloquentUserProvider::class), )); } diff --git a/tests/Auth/VerifiedEventTest.php b/tests/Auth/VerifiedEventTest.php index 92cb5e956d..4892c08bf3 100644 --- a/tests/Auth/VerifiedEventTest.php +++ b/tests/Auth/VerifiedEventTest.php @@ -8,13 +8,16 @@ use Hypervel\Contracts\Auth\Authenticatable; use Hypervel\Contracts\Auth\MustVerifyEmail; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class VerifiedEventTest extends TestCase { + use VerifiesDoubles; + public function testAcceptsVerifiableUserThatIsNotAuthenticatable(): void { - $user = m::mock(MustVerifyEmail::class); + $user = Double::for(MustVerifyEmail::class); $this->assertNotInstanceOf(Authenticatable::class, $user); $this->assertSame($user, (new Verified($user))->user); diff --git a/tests/Broadcasting/BroadcastConnectionReleaseTest.php b/tests/Broadcasting/BroadcastConnectionReleaseTest.php index 9a2ef66bfb..4cee4dce7b 100644 --- a/tests/Broadcasting/BroadcastConnectionReleaseTest.php +++ b/tests/Broadcasting/BroadcastConnectionReleaseTest.php @@ -5,6 +5,8 @@ namespace Hypervel\Tests\Broadcasting; use Ably\AblyRest; +use Ably\Channel; +use Ably\Channels; use Ably\Models\Message; use Closure; use Hypervel\Broadcasting\Broadcasters\AblyBroadcaster; @@ -18,7 +20,8 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Pusher\Pusher; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; @@ -27,6 +30,8 @@ class BroadcastConnectionReleaseTest extends TestCase { + use VerifiesDoubles; + /** * Configure a pooled session that broadcasting can return before sending. */ @@ -42,8 +47,8 @@ protected function defineEnvironment(Application $app): void public function testPusherReleasesIdleSessionsAndPreservesTransactionsAndPins(): void { $observed = []; - $pusher = m::mock(Pusher::class); - $pusher->shouldReceive('trigger')->times(12)->andReturnUsing(function () use (&$observed): object { + $pusher = Double::for(Pusher::class); + $pusher->expects('trigger')->times(12)->resolves(function () use (&$observed): object { $observed[] = $this->borrowedConnections(); DB::connection('broadcast')->selectOne('select 1'); @@ -61,17 +66,17 @@ public function testPusherReleasesIdleSessionsAndPreservesTransactionsAndPins(): public function testAblyReleasesAfterPreparingTheMessage(): void { $observed = []; - $ably = m::mock(AblyRest::class); - $channel = m::mock(); - $channel->shouldReceive('publish')->times(3)->andReturnUsing(function () use (&$observed): void { + $ably = Double::for(AblyRest::class); + $channel = Double::for(Channel::class); + $channel->expects('publish')->times(3)->resolves(function () use (&$observed): void { $observed[] = $this->borrowedConnections(); }); - $channel->shouldReceive('getCipherParams')->andReturnNull(); - $ably->channels = m::mock(); - $ably->channels->shouldReceive('get')->andReturn($channel); - $ably->channels->shouldReceive('release')->times(3); - $broadcaster = m::mock(AblyBroadcaster::class, [$this->app, $ably])->makePartial()->shouldAllowMockingProtectedMethods(); - $broadcaster->shouldReceive('buildAblyMessage')->times(3)->andReturnUsing(static function (): Message { + $channel->expects('getCipherParams')->times(3)->returns(null); + $ably->channels = Double::for(Channels::class); + $ably->channels->expects('get')->times(3)->returns($channel); + $ably->channels->expects('release')->times(3); + $broadcaster = Double::for(new AblyBroadcaster($this->app, $ably))->passthru(); + $broadcaster->expects('buildAblyMessage')->times(3)->resolves(static function (): Message { DB::connection('broadcast')->selectOne('select 1'); return new Message; @@ -85,8 +90,8 @@ public function testAblyReleasesAfterPreparingTheMessage(): void public function testMercureReleasesBeforeBorrowingItsHttpClient(): void { $observed = []; - $token = m::mock(TokenProviderInterface::class); - $token->shouldReceive('getJwt')->andReturn('test.token.signature'); + $token = Double::for(TokenProviderInterface::class); + $token->allows('getJwt')->returns('test.token.signature'); $hub = new Hub( new PoolDefinition('release-test', 'mercure', 'release-test', PoolOptions::fromArray([])), function () use (&$observed): MockHttpClient { diff --git a/tests/Broadcasting/BroadcastPoolProxyTest.php b/tests/Broadcasting/BroadcastPoolProxyTest.php index a6be14ec9e..5b494875e4 100644 --- a/tests/Broadcasting/BroadcastPoolProxyTest.php +++ b/tests/Broadcasting/BroadcastPoolProxyTest.php @@ -15,11 +15,14 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class BroadcastPoolProxyTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $poolManagers = []; @@ -32,7 +35,7 @@ protected function tearDownInCoroutine(): void public function testAuthenticatedUserResolverStateIsWrittenOnEveryBorrowIncludingNull(): void { - $broadcaster = new PoolProxyUserAuthenticationBroadcaster(m::mock(ContainerContract::class)); + $broadcaster = new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->instance()); [$configured, $pools, $definition] = $this->proxy(fn () => $broadcaster); [$unconfigured] = $this->proxy(fn () => $broadcaster, $pools, $definition); $configured->resolveAuthenticatedUserUsing(function (Request $request): array { @@ -61,7 +64,7 @@ public function testAuthenticatedUserResolverStateIsWrittenOnEveryBorrowIncludin public function testReplacingAndClearingAuthenticatedUserResolverUpdatesBorrowedBroadcaster(): void { [$proxy] = $this->proxy( - fn () => new PoolProxyUserAuthenticationBroadcaster(m::mock(ContainerContract::class)) + fn () => new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->instance()) ); $request = Request::create('/broadcasting/user-auth', 'POST'); @@ -107,7 +110,7 @@ public function testConfiguredCallbackFailsClearlyForContractOnlyBroadcaster(): public function testChannelRegistrationReturnsTheProxy(): void { [$proxy] = $this->proxy( - fn () => new PoolProxyUserAuthenticationBroadcaster(m::mock(ContainerContract::class)) + fn () => new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->instance()) ); $this->assertSame($proxy, $proxy->channel('orders.{order}', fn (): bool => true)); diff --git a/tests/Broadcasting/InteractsWithBroadcastingTest.php b/tests/Broadcasting/InteractsWithBroadcastingTest.php index 19138e6c80..c2b6a562ab 100644 --- a/tests/Broadcasting/InteractsWithBroadcastingTest.php +++ b/tests/Broadcasting/InteractsWithBroadcastingTest.php @@ -10,7 +10,8 @@ use Hypervel\Contracts\Broadcasting\Broadcaster; use Hypervel\Contracts\Broadcasting\Factory as BroadcastingFactory; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; enum InteractsWithBroadcastingTestConnectionStringEnum: string { @@ -32,6 +33,8 @@ enum InteractsWithBroadcastingTestConnectionUnitEnum class InteractsWithBroadcastingTest extends TestCase { + use VerifiesDoubles; + public function testBroadcastViaAcceptsStringBackedEnum(): void { $event = new TestBroadcastingEvent; @@ -105,11 +108,11 @@ public function testBroadcastWithIntegerBackedEnumUsesNormalizedConnection(): vo $event->broadcastVia(InteractsWithBroadcastingTestConnectionIntEnum::Connection1); $broadcastEvent = new BroadcastEvent($event); - $manager = m::mock(BroadcastingFactory::class); - $broadcaster = m::mock(Broadcaster::class); + $manager = Double::for(BroadcastingFactory::class); + $broadcaster = Double::for(Broadcaster::class); - $manager->shouldReceive('connection')->once()->with('1')->andReturn($broadcaster); - $broadcaster->shouldReceive('broadcast')->once(); + $manager->expects('connection')->with('1')->returns($broadcaster); + $broadcaster->expects('broadcast'); $broadcastEvent->handle($manager); } diff --git a/tests/Broadcasting/LogBroadcasterTest.php b/tests/Broadcasting/LogBroadcasterTest.php index b404de67eb..f839ede0b7 100644 --- a/tests/Broadcasting/LogBroadcasterTest.php +++ b/tests/Broadcasting/LogBroadcasterTest.php @@ -7,12 +7,16 @@ use Hypervel\Broadcasting\Broadcasters\Broadcaster; use Hypervel\Broadcasting\Broadcasters\LogBroadcaster; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use JsonException; -use Mockery as m; use Psr\Log\LoggerInterface; class LogBroadcasterTest extends TestCase { + use VerifiesDoubles; + public function testBroadcastUsesFormattedChannelNames(): void { Broadcaster::formatChannelsUsing( @@ -22,10 +26,9 @@ public function testBroadcastUsesFormattedChannelNames(): void ), ); - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('info') - ->once() - ->with(m::on( + $logger = Double::for(LoggerInterface::class); + $logger->expects('info') + ->with(Argument::satisfies( static fn (string $message): bool => str_contains( $message, 'on channels [application.orders, application.users]', @@ -43,8 +46,8 @@ public function testBroadcastThrowsWhenPayloadCannotBeEncoded(): void { $this->expectException(JsonException::class); - $logger = m::mock(LoggerInterface::class); - $logger->shouldNotReceive('info'); + $logger = Double::for(LoggerInterface::class); + $logger->expects('info')->never(); (new LogBroadcaster($logger))->broadcast( ['orders'], diff --git a/tests/Broadcasting/PendingBroadcastTest.php b/tests/Broadcasting/PendingBroadcastTest.php index 2ff23bfccc..367e469a23 100644 --- a/tests/Broadcasting/PendingBroadcastTest.php +++ b/tests/Broadcasting/PendingBroadcastTest.php @@ -8,7 +8,8 @@ use Hypervel\Broadcasting\PendingBroadcast; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; enum PendingBroadcastTestConnectionStringEnum: string { @@ -30,10 +31,12 @@ enum PendingBroadcastTestConnectionUnitEnum class PendingBroadcastTest extends TestCase { + use VerifiesDoubles; + public function testViaAcceptsStringBackedEnum(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch'); $event = new TestPendingBroadcastEvent; $pending = new PendingBroadcast($dispatcher, $event); @@ -46,8 +49,8 @@ public function testViaAcceptsStringBackedEnum(): void public function testViaAcceptsUnitEnum(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch'); $event = new TestPendingBroadcastEvent; $pending = new PendingBroadcast($dispatcher, $event); @@ -59,8 +62,8 @@ public function testViaAcceptsUnitEnum(): void public function testViaNormalizesIntegerBackedEnumImmediately(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch'); $event = new TestPendingBroadcastEvent; $pending = new PendingBroadcast($dispatcher, $event); @@ -72,8 +75,8 @@ public function testViaNormalizesIntegerBackedEnumImmediately(): void public function testViaAcceptsNull(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch'); $event = new TestPendingBroadcastEvent; $pending = new PendingBroadcast($dispatcher, $event); @@ -85,8 +88,8 @@ public function testViaAcceptsNull(): void public function testViaAcceptsString(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once(); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch'); $event = new TestPendingBroadcastEvent; $pending = new PendingBroadcast($dispatcher, $event); diff --git a/tests/Bus/BusDebounceLockTest.php b/tests/Bus/BusDebounceLockTest.php index e3f52c0e8f..5a058b0be8 100644 --- a/tests/Bus/BusDebounceLockTest.php +++ b/tests/Bus/BusDebounceLockTest.php @@ -11,7 +11,9 @@ use Hypervel\Engine\Channel; use Hypervel\Queue\Attributes\DebounceFor; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -21,6 +23,8 @@ class BusDebounceLockTest extends TestCase { + use VerifiesDoubles; + public function testCurrentOwnerMayBeRetrievedWithOneCacheRead(): void { $cache = new CacheRepository(new ConcurrentDebounceStore); @@ -50,9 +54,9 @@ public function testConcurrentFirstDispatchesDoNotOverwriteTheMaxWaitAnchor(): v public function testReleaseProbeFailureDoesNotRemoveEitherDebounceRecord(): void { $failure = new RuntimeException('Owner probe failed.'); - $cache = m::mock(Cache::class); - $cache->shouldReceive('get')->once()->with('debounce-key')->andThrow($failure); - $cache->shouldReceive('forget')->never(); + $cache = Double::for(Cache::class); + $cache->expects('get')->with('debounce-key')->throws($failure); + $cache->expects('forget')->never(); try { DebounceLock::releaseOwned($cache, 'debounce-key', 'owner'); @@ -70,11 +74,11 @@ public function testAcquisitionFailureRemainsPrimaryWhenCleanupProbeFails(bool $ $key = DebounceLock::getKey($job); $failure = new RuntimeException('Maximum-wait read failed.'); $cleanupFailure = new RuntimeException('Cleanup owner probe failed.', previous: $canceled ? new CanceledException : null); - $cache = m::mock(Cache::class); - $cache->shouldReceive('put')->once()->with($key, m::type('string'), 300)->andReturnTrue(); - $cache->shouldReceive('get')->once()->with($key . ':first_dispatched_at')->andThrow($failure); - $cache->shouldReceive('get')->once()->with($key)->andThrow($cleanupFailure); - $cache->shouldReceive('forget')->never(); + $cache = Double::for(Cache::class); + $cache->expects('put')->with($key, Argument::type('string'), 300)->returns(true); + $cache->expects('get')->with($key . ':first_dispatched_at')->throws($failure); + $cache->expects('get')->with($key)->throws($cleanupFailure); + $cache->expects('forget')->never(); try { (new DebounceLock($cache))->acquire($job); @@ -87,9 +91,9 @@ public function testAcquisitionFailureRemainsPrimaryWhenCleanupProbeFails(bool $ public function testReleasePreservesCancellationFromSecondCleanup(): void { $failure = new RuntimeException('Cache cleanup failed.', previous: new CanceledException); - $cache = m::mock(Cache::class); - $cache->shouldReceive('forget')->once()->with('key')->andThrow(new RuntimeException('First deletion failed.')); - $cache->shouldReceive('forget')->once()->with('key:first_dispatched_at')->andThrow($failure); + $cache = Double::for(Cache::class); + $cache->expects('forget')->with('key')->throws(new RuntimeException('First deletion failed.')); + $cache->expects('forget')->with('key:first_dispatched_at')->throws($failure); $caught = null; try { diff --git a/tests/Bus/DispatchLockContextTest.php b/tests/Bus/DispatchLockContextTest.php index ec2550c54e..3e974c1951 100644 --- a/tests/Bus/DispatchLockContextTest.php +++ b/tests/Bus/DispatchLockContextTest.php @@ -13,6 +13,7 @@ use Hypervel\Cache\WorkerArrayStore; use Hypervel\Container\Container; use Hypervel\Contracts\Cache\Lock; +use Hypervel\Contracts\Cache\LockProvider; use Hypervel\Contracts\Cache\Repository as Cache; use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Contracts\Events\Dispatcher as EventDispatcher; @@ -24,7 +25,8 @@ use Hypervel\Queue\DeferredQueue; use Hypervel\Queue\SyncQueue; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -34,17 +36,19 @@ class DispatchLockContextTest extends TestCase { + use VerifiesDoubles; + public function testReleaseAttemptsBothLocksAndPreservesCancellationFromDebounceCleanup(): void { $failure = new RuntimeException('Debounce cleanup failed.', previous: new CanceledException); - $unique = m::mock(Cache::class); - $lock = m::mock(Lock::class); - $unique->shouldReceive('lock')->once()->with('unique')->andReturn($lock); - $lock->shouldReceive('forceRelease')->once()->andThrow(new RuntimeException('Unique release failed.')); - $debounce = m::mock(Cache::class); - $debounce->shouldReceive('get')->once()->with('debounce')->andReturn('owner'); - $debounce->shouldReceive('forget')->once()->with('debounce')->andThrow($failure); - $debounce->shouldReceive('forget')->once()->with('debounce:first_dispatched_at')->andReturnTrue(); + $unique = Double::for(Cache::class, LockProvider::class); + $lock = Double::for(Lock::class); + $unique->expects('lock')->with('unique')->returns($lock); + $lock->expects('forceRelease')->throws(new RuntimeException('Unique release failed.')); + $debounce = Double::for(Cache::class); + $debounce->expects('get')->with('debounce')->returns('owner'); + $debounce->expects('forget')->with('debounce')->throws($failure); + $debounce->expects('forget')->with('debounce:first_dispatched_at')->returns(true); $job = new DispatchLockContextJob('cleanup'); DispatchLockContext::registerUnique($job, $unique, null, 'unique', ''); DispatchLockContext::registerDebounce($job, $debounce, 'debounce', 'owner'); @@ -200,17 +204,16 @@ public function testStaleDispatchReleaseCannotRemoveNewerOwnersLock(): void public function testMetadataSurvivesUntilAfterCommitPayloadCreation(string $queueClass, bool $delayed): void { $container = new Container; - $container->instance(Cache::class, m::mock(Cache::class)); + $container->instance(Cache::class, Double::for(Cache::class)); $container->instance(ContainerContract::class, $container); $container->instance(EventDispatcher::class, new EventsDispatcher($container)); Container::setInstance($container); - $transactionManager = m::mock(DatabaseTransactionsManager::class); - $transactionManager->expects('hasApplicableTransaction')->with(null)->andReturnTrue(); - $transactionManager->shouldReceive('addCallback') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback()); - $transactionManager->shouldReceive('addCallbackForRollback')->once()->andReturnNull(); + $transactionManager = Double::for(DatabaseTransactionsManager::class); + $transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true); + $transactionManager->expects('addCallback') + ->resolves(fn (callable $callback) => $callback()); + $transactionManager->expects('addCallbackForRollback')->returns(null); $container->instance('db.transactions', $transactionManager); $metadata = null; diff --git a/tests/Bus/OutboxOptionsTest.php b/tests/Bus/OutboxOptionsTest.php index 637308076b..be3c9f4093 100644 --- a/tests/Bus/OutboxOptionsTest.php +++ b/tests/Bus/OutboxOptionsTest.php @@ -13,10 +13,14 @@ use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class OutboxOptionsTest extends TestCase { + use VerifiesDoubles; + public function testUnusedOutboxPropertiesAreNotSerialized(): void { foreach ([new OutboxQueueableJob, new OutboxBatchableJob, new OutboxCombinedJob] as $job) { @@ -43,9 +47,9 @@ public function testUnusedOutboxPropertiesAreNotSerialized(): void public function testPendingDispatchForwardsOutboxOptions(): void { $job = new OutboxQueueableJob; - $dispatcher = m::mock(Dispatcher::class); + $dispatcher = Double::for(Dispatcher::class); Container::getInstance()->instance(Dispatcher::class, $dispatcher); - $dispatcher->expects('dispatch')->with($job)->andReturnNull(); + $dispatcher->expects('dispatch')->with(Argument::same($job))->returns(null); $pending = new PendingDispatch($job); $this->assertSame($pending, $pending->onOutboxDatabase('billing')); diff --git a/tests/Bus/QueueableTest.php b/tests/Bus/QueueableTest.php index 9bd044d798..cf8f2d32a9 100644 --- a/tests/Bus/QueueableTest.php +++ b/tests/Bus/QueueableTest.php @@ -10,12 +10,16 @@ use Hypervel\Queue\Attributes\Connection; use Hypervel\Queue\Attributes\Queue as QueueAttribute; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Laravel\SerializableClosure\SerializableClosure; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class QueueableTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('connectionDataProvider')] public function testOnConnection(mixed $connection, ?string $expected): void { @@ -157,8 +161,8 @@ public function testDispatchNextJobPreservesExplicitZeroIdentifiers(): void $job->chainConnection = 'default-connection'; $job->chainQueue = 'default-queue'; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on(function (FakeJob $next): bool { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->with(Argument::satisfies(function (FakeJob $next): bool { $this->assertSame('0', $next->connection); $this->assertSame('0', $next->queue); @@ -176,8 +180,8 @@ public function testDispatchNextJobInheritsChainIdentifiersForEmptyStrings(): vo $job->chainConnection = 'default-connection'; $job->chainQueue = 'default-queue'; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on(function (FakeJob $next): bool { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->with(Argument::satisfies(function (FakeJob $next): bool { $this->assertSame('default-connection', $next->connection); $this->assertSame('default-queue', $next->queue); @@ -195,8 +199,8 @@ public function testDispatchNextJobKeepsItsAttributesOverChainDefaults(): void $job->chainConnection = 'default-connection'; $job->chainQueue = 'default-queue'; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once()->with(m::on(function (AttributedFakeJob $next): bool { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->with(Argument::satisfies(function (AttributedFakeJob $next): bool { $this->assertNull($next->connection); $this->assertNull($next->queue); $this->assertSame('default-connection', $next->chainConnection); diff --git a/tests/Cache/CacheDatabaseLockTest.php b/tests/Cache/CacheDatabaseLockTest.php index 6a34276ff0..404a6b3251 100644 --- a/tests/Cache/CacheDatabaseLockTest.php +++ b/tests/Cache/CacheDatabaseLockTest.php @@ -17,23 +17,28 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PDO; use PDOException; use PHPUnit\Framework\Attributes\TestWith; class CacheDatabaseLockTest extends TestCase { + use VerifiesDoubles; + public function testLockCanBeAcquired(): void { [$lock, $table] = $this->getLock(); - $table->shouldReceive('insertOrIgnore')->once()->with(m::on(function ($arg) { + $table->expects('insertOrIgnore')->with(Argument::satisfies(function ($arg) { return is_array($arg) && $arg['key'] === 'foo' && isset($arg['owner']) && is_int($arg['expiration']); - }))->andReturn(1); + }))->returns(1); $this->assertTrue($lock->acquire()); } @@ -50,8 +55,8 @@ public function testOwnershipAndLifetimeReadTheWriterInsteadOfAStaleReplica(): v $reader->exec("insert into cache_locks values ('key', 'stale', 1010)"); $connection = new SQLiteConnection($writer, ':memory:'); $connection->setReadPdo($reader); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->andReturn($connection); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); $lock = new DatabaseLock($resolver, null, 'key', 'cache_locks', 60, 'fresh', null); $this->assertTrue($lock->isOwnedByCurrentProcess()); @@ -65,18 +70,18 @@ public function testFractionalSecondAcquireAndRefreshNeverExpireBeforeRequestedD [$lock, $table] = $this->getLock(seconds: 1); $owner = $lock->owner(); - $table->shouldReceive('insertOrIgnore')->once()->with([ + $table->expects('insertOrIgnore')->with([ 'key' => 'foo', 'owner' => $owner, 'expiration' => 1002, - ])->andReturn(1); + ])->returns(1); $this->assertTrue($lock->acquire()); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('owner', $owner)->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', 1000)->andReturn($table); - $table->shouldReceive('update')->once()->with(['expiration' => 1002])->andReturn(1); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('owner', $owner)->returns($table); + $table->expects('where')->with('expiration', '>', 1000)->returns($table); + $table->expects('update')->with(['expiration' => 1002])->returns(1); $this->assertTrue($lock->refresh()); } @@ -87,22 +92,22 @@ public function testLockCanBeAcquiredIfAlreadyOwnedBySameOwner(): void $owner = $lock->owner(); // First attempt inserts nothing because the key exists. - $table->shouldReceive('insertOrIgnore')->once()->andReturn(0); + $table->expects('insertOrIgnore')->returns(0); // So it tries to update - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->andReturnUsing(function ($callback) use ($table, $owner) { - $query = m::mock(Builder::class); - $query->shouldReceive('where')->once()->with('owner', $owner)->andReturn($query); - $query->shouldReceive('orWhere')->once()->with('expiration', '<=', m::type('int'))->andReturn($query); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with(Argument::type(Closure::class))->resolves(function ($callback) use ($table, $owner) { + $query = Double::for(Builder::class); + $query->expects('where')->with('owner', $owner)->returns($query); + $query->expects('orWhere')->with('expiration', '<=', Argument::type('int'))->returns($query); $callback($query); return $table; }); - $table->shouldReceive('update')->once()->with(m::on(function ($arg) use ($owner) { + $table->expects('update')->with(Argument::satisfies(function ($arg) use ($owner) { return is_array($arg) && $arg['owner'] === $owner && is_int($arg['expiration']); - }))->andReturn(1); + }))->returns(1); $this->assertTrue($lock->acquire()); } @@ -112,14 +117,14 @@ public function testLockCannotBeAcquiredIfAlreadyHeld(): void [$lock, $table] = $this->getLock(); // Insert finds the existing key. - $table->shouldReceive('insertOrIgnore')->once()->andReturn(0); + $table->expects('insertOrIgnore')->returns(0); // Update fails too (someone else owns it) - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->andReturnUsing(function ($callback) use ($table, $lock) { - $query = m::mock(Builder::class); - $query->shouldReceive('where')->once()->with('owner', $lock->owner())->andReturn($query); - $query->shouldReceive('orWhere')->once()->with('expiration', '<=', m::type('int'))->andReturn($query); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with(Argument::type(Closure::class))->resolves(function ($callback) use ($table, $lock) { + $query = Double::for(Builder::class); + $query->expects('where')->with('owner', $lock->owner())->returns($query); + $query->expects('orWhere')->with('expiration', '<=', Argument::type('int'))->returns($query); // The callback should return the query $result = $callback($query); @@ -129,7 +134,7 @@ public function testLockCannotBeAcquiredIfAlreadyHeld(): void return $table; }); - $table->shouldReceive('update')->once()->andReturn(0); + $table->expects('update')->returns(0); $this->assertFalse($lock->acquire()); } @@ -139,8 +144,8 @@ public function testInsertFailureOtherThanAnExistingLockPropagatesWithoutTakingO [$lock, $table] = $this->getLock(); $failure = new QueryException('default', 'insert into "cache_locks"', [], new PDOException('SQLSTATE[HY000]: General error: 5 database is locked')); - $table->shouldReceive('insertOrIgnore')->once()->andThrow($failure); - $table->shouldNotReceive('update'); + $table->expects('insertOrIgnore')->throws($failure); + $table->expects('update')->never(); try { $lock->acquire(); @@ -153,15 +158,15 @@ public function testInsertFailureOtherThanAnExistingLockPropagatesWithoutTakingO public function testSqliteLockHeldByAnotherOwnerIsRefusedWithoutWriting(): void { // The lottery always prunes, so any write, including pruning, fails the unexpected call. - [$lock] = $this->getLock(lockLottery: [1, 1], driver: 'sqlite', tables: [$this->liveOwnerRead(static fn (): string => 'other-owner')]); + [$lock] = $this->getLock(lockLottery: [1, 1], driver: 'sqlite', tables: [$this->liveOwnerRead(static fn (): string => 'other-owner')->strict()]); $this->assertFalse($lock->acquire()); } public function testSqliteLockIsInsertedWhenNoLiveLockExists(): void { - $insert = m::mock(Builder::class); - $insert->shouldReceive('insertOrIgnore')->once()->andReturn(1); + $insert = Double::for(Builder::class); + $insert->expects('insertOrIgnore')->returns(1); [$lock] = $this->getLock(driver: 'sqlite', tables: [$this->liveOwnerRead(static fn (): null => null), $insert]); @@ -177,12 +182,12 @@ public function testSqliteExpiredOrOwnLockIsTakenOverByTheConditionalUpdate(bool $read = $this->liveOwnerRead(static function () use (&$lock, $own): ?string { return $own ? $lock->owner() : null; }); - $insert = m::mock(Builder::class); - $insert->shouldReceive('insertOrIgnore')->once()->andReturn(0); - $update = m::mock(Builder::class); - $update->shouldReceive('where')->once()->with('key', 'foo')->andReturnSelf(); - $update->shouldReceive('where')->once()->with(m::type(Closure::class))->andReturnSelf(); - $update->shouldReceive('update')->once()->andReturn(1); + $insert = Double::for(Builder::class); + $insert->expects('insertOrIgnore')->returns(0); + $update = Double::for(Builder::class); + $update->expects('where')->with('key', 'foo'); + $update->expects('where')->with(Argument::type(Closure::class)); + $update->expects('update')->returns(1); [$lock] = $this->getLock(driver: 'sqlite', tables: [$read, $insert, $update]); @@ -194,13 +199,13 @@ public function testSqliteExpiredOrOwnLockIsTakenOverByTheConditionalUpdate(bool #[TestWith(['mariadb', true])] public function testATakeoverThatChangedNoRowIsConfirmedWithACurrentReadWhereOnlyChangedRowsCount(string $driver, bool $owned): void { - $insert = m::mock(Builder::class); - $insert->shouldReceive('insert')->once()->andThrow(new UniqueConstraintViolationException('', '', [], new Exception)); - $update = m::mock(Builder::class); - $update->shouldReceive('where')->once()->with('key', 'foo')->andReturnSelf(); - $update->shouldReceive('where')->once()->with(m::type(Closure::class))->andReturnSelf(); - $update->shouldReceive('update')->once()->andReturn(0); - $read = m::mock(Builder::class); + $insert = Double::for(Builder::class); + $insert->expects('insert')->throws(new UniqueConstraintViolationException('', '', [], new Exception)); + $update = Double::for(Builder::class); + $update->expects('where')->with('key', 'foo'); + $update->expects('where')->with(Argument::type(Closure::class)); + $update->expects('update')->returns(0); + $read = Double::for(Builder::class); // A lock object that never acquired: a lost-connection retry can still meet the row its first insert committed. [$lock] = $this->getLock(driver: $driver, tables: [$insert, $update, $read]); @@ -213,12 +218,12 @@ public function testATakeoverThatChangedNoRowIsConfirmedWithACurrentReadWhereOnl #[TestWith([false])] public function testARefreshThatChangedNoRowIsConfirmedWithACurrentReadWhereOnlyChangedRowsCount(bool $owned): void { - $update = m::mock(Builder::class); - $update->shouldReceive('where')->once()->with('key', 'foo')->andReturnSelf(); - $update->shouldReceive('where')->once()->with('owner', m::type('string'))->andReturnSelf(); - $update->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturnSelf(); - $update->shouldReceive('update')->once()->andReturn(0); - $read = m::mock(Builder::class); + $update = Double::for(Builder::class); + $update->expects('where')->with('key', 'foo'); + $update->expects('where')->with('owner', Argument::type('string')); + $update->expects('where')->with('expiration', '>', Argument::type('int')); + $update->expects('update')->returns(0); + $read = Double::for(Builder::class); [$lock] = $this->getLock(driver: 'mysql', tables: [$update, $read]); $this->expectLiveOwnerCurrentRead($read, $lock->owner(), $owned); @@ -230,11 +235,11 @@ public function testExpiredLocksAreDeletedDuringAcquisition(): void { [$lock, $table] = $this->getLock(lockLottery: [1, 1]); // Always hit lottery - $table->shouldReceive('insertOrIgnore')->once()->andReturn(1); + $table->expects('insertOrIgnore')->returns(1); // Lottery cleanup - $table->shouldReceive('where')->once()->with('expiration', '<=', m::type('int'))->andReturn($table); - $table->shouldReceive('delete')->once(); + $table->expects('where')->with('expiration', '<=', Argument::type('int'))->returns($table); + $table->expects('delete'); $this->assertTrue($lock->acquire()); } @@ -245,7 +250,7 @@ public function testLockCanBeAcquiredWithoutAutomaticPruning(?array $lottery): v { [$lock, $table] = $this->getLock(lockLottery: $lottery); - $table->shouldReceive('insertOrIgnore')->once()->andReturn(1); + $table->expects('insertOrIgnore')->returns(1); $this->assertTrue($lock->acquire()); } @@ -255,9 +260,9 @@ public function testLockCanBeReleased(): void [$lock, $table] = $this->getLock(); $owner = $lock->owner(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('owner', $owner)->andReturn($table); - $table->shouldReceive('delete')->once()->andReturn(1); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('owner', $owner)->returns($table); + $table->expects('delete')->returns(1); $this->assertTrue($lock->release()); } @@ -266,9 +271,9 @@ public function testReleaseReturnsFalseWhenNoOwnedRowMatches(): void { [$lock, $table] = $this->getLock(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('owner', $lock->owner())->andReturn($table); - $table->shouldReceive('delete')->once()->andReturn(0); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('owner', $lock->owner())->returns($table); + $table->expects('delete')->returns(0); $this->assertFalse($lock->release()); } @@ -277,9 +282,9 @@ public function testExpiredLockIsNotLockedOrOwned(): void { [$lock, $table] = $this->getLock(); - $table->shouldReceive('where')->twice()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->twice()->with('expiration', '>', m::type('int'))->andReturn($table); - $table->shouldReceive('first')->twice()->andReturn(null); + $table->expects('where')->times(2)->with('key', 'foo')->returns($table); + $table->expects('where')->times(2)->with('expiration', '>', Argument::type('int'))->returns($table); + $table->expects('first')->times(2)->returns(null); $this->assertFalse($lock->isLocked()); $this->assertFalse($lock->isOwnedByCurrentProcess()); @@ -289,11 +294,10 @@ public function testLockCanBeForceReleased(): void { [$lock, $table] = $this->getLock(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('delete')->once(); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('delete'); $lock->forceRelease(); - $this->assertTrue(true); // Just verify no exceptions } public function testLockWithDefaultTimeout(): void @@ -302,12 +306,12 @@ public function testLockWithDefaultTimeout(): void [$lock, $table] = $this->getLock(seconds: 0); - $table->shouldReceive('insertOrIgnore')->once()->with(m::on(function ($arg) use ($now) { + $table->expects('insertOrIgnore')->with(Argument::satisfies(function ($arg) use ($now) { return is_array($arg) && $arg['key'] === 'foo' && isset($arg['owner']) && $arg['expiration'] === $now->getTimestamp() + 86400; // Default timeout - }))->andReturn(1); + }))->returns(1); $this->assertTrue($lock->acquire()); } @@ -326,13 +330,13 @@ public function testRefreshExtendsLockExpiration(): void [$lock, $table] = $this->getLock(); $owner = $lock->owner(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('owner', $owner)->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturn($table); - $table->shouldReceive('update')->once()->with(m::on(function ($arg) use ($now) { + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('owner', $owner)->returns($table); + $table->expects('where')->with('expiration', '>', Argument::type('int'))->returns($table); + $table->expects('update')->with(Argument::satisfies(function ($arg) use ($now) { return is_array($arg) && $arg['expiration'] === $now->getTimestamp() + 10; - }))->andReturn(1); + }))->returns(1); $this->assertTrue($lock->refresh()); } @@ -344,13 +348,13 @@ public function testRefreshWithCustomTtl(): void [$lock, $table] = $this->getLock(); $owner = $lock->owner(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('owner', $owner)->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturn($table); - $table->shouldReceive('update')->once()->with(m::on(function ($arg) use ($now) { + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('owner', $owner)->returns($table); + $table->expects('where')->with('expiration', '>', Argument::type('int'))->returns($table); + $table->expects('update')->with(Argument::satisfies(function ($arg) use ($now) { return is_array($arg) && $arg['expiration'] === $now->getTimestamp() + 30; - }))->andReturn(1); + }))->returns(1); $this->assertTrue($lock->refresh(30)); } @@ -360,10 +364,10 @@ public function testRefreshReturnsFalseWhenNotOwned(): void [$lock, $table] = $this->getLock(); $owner = $lock->owner(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('owner', $owner)->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturn($table); - $table->shouldReceive('update')->once()->andReturn(0); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('owner', $owner)->returns($table); + $table->expects('where')->with('expiration', '>', Argument::type('int'))->returns($table); + $table->expects('update')->returns(0); $this->assertFalse($lock->refresh()); } @@ -375,13 +379,13 @@ public function testRefreshOnDefaultTimeoutLockReappliesDefaultTimeout(): void [$lock, $table] = $this->getLock(seconds: 0); $owner = $lock->owner(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('owner', $owner)->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturn($table); - $table->shouldReceive('update')->once()->with(m::on(function ($arg) use ($now) { + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('owner', $owner)->returns($table); + $table->expects('where')->with('expiration', '>', Argument::type('int'))->returns($table); + $table->expects('update')->with(Argument::satisfies(function ($arg) use ($now) { return is_array($arg) && $arg['expiration'] === $now->getTimestamp() + 86400; - }))->andReturn(1); + }))->returns(1); $this->assertTrue($lock->refresh()); } @@ -391,10 +395,10 @@ public function testRefreshReturnsFalseWhenExpired(): void [$lock, $table] = $this->getLock(); $owner = $lock->owner(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('owner', $owner)->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturn($table); - $table->shouldReceive('update')->once()->andReturn(0); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('owner', $owner)->returns($table); + $table->expects('where')->with('expiration', '>', Argument::type('int'))->returns($table); + $table->expects('update')->returns(0); $this->assertFalse($lock->refresh()); } @@ -425,9 +429,9 @@ public function testGetRemainingLifetimeReturnsSeconds(): void [$lock, $table] = $this->getLock(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', $now->getTimestamp())->andReturn($table); - $table->shouldReceive('first')->once()->andReturn((object) [ + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('expiration', '>', $now->getTimestamp())->returns($table); + $table->expects('first')->returns((object) [ 'expiration' => $now->getTimestamp() + 5, ]); @@ -438,9 +442,9 @@ public function testGetRemainingLifetimeReturnsNullWhenLockDoesNotExist(): void { [$lock, $table] = $this->getLock(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturn($table); - $table->shouldReceive('first')->once()->andReturn(null); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('expiration', '>', Argument::type('int'))->returns($table); + $table->expects('first')->returns(null); $this->assertNull($lock->getRemainingLifetime()); } @@ -451,9 +455,9 @@ public function testGetRemainingLifetimeReturnsNullWhenExpired(): void [$lock, $table] = $this->getLock(); - $table->shouldReceive('where')->once()->with('key', 'foo')->andReturn($table); - $table->shouldReceive('where')->once()->with('expiration', '>', $now->getTimestamp())->andReturn($table); - $table->shouldReceive('first')->once()->andReturn(null); + $table->expects('where')->with('key', 'foo')->returns($table); + $table->expects('where')->with('expiration', '>', $now->getTimestamp())->returns($table); + $table->expects('first')->returns(null); $this->assertNull($lock->getRemainingLifetime()); } @@ -462,7 +466,7 @@ public function testGetConnectionNameReturnsConnectionName(): void { [$lock,, $connection] = $this->getLock(); - $connection->shouldReceive('getName')->once()->andReturn('default'); + $connection->expects('getName')->returns('default'); $this->assertSame('default', $lock->getConnectionName()); } @@ -471,7 +475,7 @@ public function testGetConnectionNameCanReturnNull(): void { [$lock,, $connection] = $this->getLock(connectionName: null); - $connection->shouldReceive('getName')->once()->andReturn(null); + $connection->expects('getName')->returns(null); $this->assertNull($lock->getConnectionName()); } @@ -483,14 +487,14 @@ public function testGetConnectionNameCanReturnNull(): void */ protected function getLock(int $seconds = 10, ?array $lockLottery = [0, 1], ?string $connectionName = 'default', string $driver = 'pgsql', array $tables = []): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $connection = m::mock(Connection::class); - $table = m::mock(Builder::class); - $table->shouldReceive('useWritePdo')->andReturnSelf()->byDefault(); + $resolver = Double::for(ConnectionResolverInterface::class); + $connection = Double::for(Connection::class); + $table = Double::for(Builder::class); + $table->allows('useWritePdo'); - $resolver->shouldReceive('connection')->with($connectionName)->andReturn($connection); - $connection->shouldReceive('getDriverName')->andReturn($driver); - $connection->shouldReceive('table')->with('cache_locks')->andReturn(...($tables === [] ? [$table] : $tables)); + $resolver->allows('connection')->with($connectionName)->returns($connection); + $connection->allows('getDriverName')->returns($driver); + $connection->allows('table')->with('cache_locks')->returns(...($tables === [] ? [$table] : $tables)); $lock = new DatabaseLock( $resolver, @@ -510,11 +514,11 @@ protected function getLock(int $seconds = 10, ?array $lockLottery = [0, 1], ?str */ protected function expectLiveOwnerCurrentRead(Builder $read, string $owner, bool $owned): void { - $read->shouldReceive('sharedLock')->once()->andReturnSelf(); - $read->shouldReceive('where')->once()->with('key', 'foo')->andReturnSelf(); - $read->shouldReceive('where')->once()->with('owner', $owner)->andReturnSelf(); - $read->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturnSelf(); - $read->shouldReceive('exists')->once()->andReturn($owned); + $read->expects('sharedLock'); + $read->expects('where')->with('key', 'foo'); + $read->expects('where')->with('owner', $owner); + $read->expects('where')->with('expiration', '>', Argument::type('int')); + $read->expects('exists')->returns($owned); } /** @@ -522,13 +526,13 @@ protected function expectLiveOwnerCurrentRead(Builder $read, string $owner, bool * * @param Closure(): ?string $owner */ - protected function liveOwnerRead(Closure $owner): Builder + protected function liveOwnerRead(Closure $owner): Builder&DoubleInterface { - $read = m::mock(Builder::class); - $read->shouldReceive('useWritePdo')->once()->andReturnSelf(); - $read->shouldReceive('where')->once()->with('key', 'foo')->andReturnSelf(); - $read->shouldReceive('where')->once()->with('expiration', '>', m::type('int'))->andReturnSelf(); - $read->shouldReceive('value')->once()->with('owner')->andReturnUsing($owner); + $read = Double::for(Builder::class); + $read->expects('useWritePdo'); + $read->expects('where')->with('key', 'foo'); + $read->expects('where')->with('expiration', '>', Argument::type('int')); + $read->expects('value')->with('owner')->resolves($owner); return $read; } diff --git a/tests/Cache/CacheMemoizedStoreTest.php b/tests/Cache/CacheMemoizedStoreTest.php index 51ce91a06d..9b0f115779 100644 --- a/tests/Cache/CacheMemoizedStoreTest.php +++ b/tests/Cache/CacheMemoizedStoreTest.php @@ -24,13 +24,16 @@ use Hypervel\Session\Store as Session; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use stdClass; class CacheMemoizedStoreTest extends TestCase { + use VerifiesDoubles; + public function testExposesTheUnderlyingStore(): void { $innerStore = new ArrayStore; @@ -145,8 +148,8 @@ public function testIncompleteClassHandlerRunsOnceAcrossMemoizedRepositories(): public function testPutManyWithEmptyInputReturnsDelegatedRepositoryResult(): void { - $repository = m::mock(Repository::class); - $repository->shouldReceive('putMany')->once()->with([], 60)->andReturn(false); + $repository = Double::for(Repository::class); + $repository->expects('putMany')->with([], 60)->returns(false); $store = new MemoizedStore('memoized', $repository); @@ -208,7 +211,7 @@ public static function addTtls(): array public function testTagSupportDelegatesToTheUnderlyingStore(): void { $taggable = new MemoizedStore('array', new Repository(new ArrayStore)); - $nonTaggable = new MemoizedStore('test', new Repository(m::mock(Store::class))); + $nonTaggable = new MemoizedStore('test', new Repository(Double::for(Store::class))); $this->assertTrue($taggable->supportsTags()); $this->assertSame(TagMode::All, $taggable->getTagMode()); @@ -388,10 +391,10 @@ public function testManyFiresCacheHitNotCacheMissedForSentinelThroughMemoizedSto // Capture only the many() read-path events by attaching the dispatcher // after the write. $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); $outerRepo->setEventDispatcher($events); @@ -410,7 +413,7 @@ public function testManyFiresCacheHitNotCacheMissedForSentinelThroughMemoizedSto public function testLockFlushCapabilityDelegatesToUnderlyingStore(): void { $flushable = new MemoizedStore('test', new Repository(new ArrayStore)); - $nonFlushableStore = m::mock(Store::class); + $nonFlushableStore = Double::for(Store::class); $nonFlushable = new MemoizedStore('test', new Repository($nonFlushableStore)); $this->assertTrue($flushable->supportsFlushingLocks()); @@ -425,9 +428,9 @@ public function testLocksCanBeFlushedWhenUnderlyingStoreSupportsIt(): void public function testFlushLocksDelegatesToUnderlyingStore(): void { - $store = m::mock(Store::class, CanFlushLocks::class); - $store->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $store->shouldReceive('flushLocks')->once()->andReturnTrue(); + $store = Double::for(Store::class, CanFlushLocks::class); + $store->expects('supportsFlushingLocks')->returns(true); + $store->expects('flushLocks')->returns(true); $memoized = new MemoizedStore('test', new Repository($store)); @@ -449,9 +452,9 @@ public function testFlushLocksThrowsWhenUnderlyingStoreDoesNotSupportIt(): void public function testFlushLocksRejectsUnsupportedUnderlyingStore(): void { - $store = m::mock(Store::class, CanFlushLocks::class); - $store->shouldReceive('supportsFlushingLocks')->once()->andReturnFalse(); - $store->shouldNotReceive('flushLocks'); + $store = Double::for(Store::class, CanFlushLocks::class); + $store->expects('supportsFlushingLocks')->returns(false); + $store->expects('flushLocks')->never(); $this->expectException(BadMethodCallException::class); $this->expectExceptionMessageIs(sprintf( diff --git a/tests/Cache/CacheNullStoreTest.php b/tests/Cache/CacheNullStoreTest.php index dc96a7302c..809e0582d5 100644 --- a/tests/Cache/CacheNullStoreTest.php +++ b/tests/Cache/CacheNullStoreTest.php @@ -11,10 +11,13 @@ use Hypervel\Contracts\Cache\CanFlushLocks; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CacheNullStoreTest extends TestCase { + use VerifiesDoubles; + public function testItemsCanNotBeCached(): void { $store = new NullStore; @@ -68,9 +71,9 @@ public function testRememberNullableAlwaysReRunsCallbackOnNullStore(): void public function testTaggedFlushReportsRejectedTagIdentifierWrites(): void { $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $events->shouldReceive('dispatch')->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch')->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); diff --git a/tests/Cache/CacheRedisLockTest.php b/tests/Cache/CacheRedisLockTest.php index c6b8bc553b..cef402c206 100644 --- a/tests/Cache/CacheRedisLockTest.php +++ b/tests/Cache/CacheRedisLockTest.php @@ -10,10 +10,17 @@ use Hypervel\Redis\RedisProxy; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; +use Redis; +use RedisCluster; +use RuntimeException; class CacheRedisLockTest extends TestCase { + use VerifiesDoubles; + public function testLockImplementsRefreshableLock(): void { [$lock] = $this->getLock(); @@ -25,76 +32,179 @@ public function testLockCanBeAcquired(): void { [$lock, $redis] = $this->getLock(); - $redis->shouldReceive('set') - ->once() - ->with('foo', m::type('string'), 'EX', 10, 'NX') - ->andReturn(true); + $redis->expects('set') + ->with('foo', Argument::type('string'), 'EX', 10, 'NX') + ->returns(true); $this->assertTrue($lock->acquire()); } + public function testAcquireWithExpirationReturnsFalseWhenLockExists(): void + { + [$lock, $redis] = $this->getLock(seconds: 60); + $redis->expects('set') + ->with('foo', Argument::type('string'), 'EX', 60, 'NX') + ->returns(false); + + $this->assertFalse($lock->acquire()); + } + public function testLockCanBeAcquiredWithoutExpiration(): void { [$lock, $redis] = $this->getLock(seconds: 0); - $redis->shouldReceive('setnx') - ->once() - ->with('foo', m::type('string')) - ->andReturn(1); + $redis->expects('setnx') + ->with('foo', Argument::type('string')) + ->returns(1); $this->assertTrue($lock->acquire()); } + public function testAcquireWithoutExpirationReturnsFalseWhenLockExists(): void + { + [$lock, $redis] = $this->getLock(seconds: 0); + $redis->expects('setnx') + ->with('foo', Argument::type('string')) + ->returns(0); + + $this->assertFalse($lock->acquire()); + } + public function testLockCanBeReleased(): void { [$lock, $redis] = $this->getLock(); - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('pack') - ->once() + $connection = Double::for(CacheLockRedisConnection::class); + $connection->expects('pack') ->with([$lock->owner()]) - ->andReturn(['packed-owner']); - $connection->shouldReceive('eval') - ->once() - ->with(m::type('string'), 1, 'foo', 'packed-owner') - ->andReturn(1); + ->returns(['packed-owner']); + $connection->expects('eval') + ->with(Argument::type('string'), 1, 'foo', 'packed-owner') + ->returns(1); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection)); + $redis->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection)); $this->assertTrue($lock->release()); } + public function testReleaseReturnsFalseWhenNotOwner(): void + { + [$lock, $redis] = $this->getLock(seconds: 60); + $connection = Double::for(CacheLockRedisConnection::class); + $connection->expects('pack') + ->with([$lock->owner()]) + ->returns(['packed-owner']); + $connection->expects('eval') + ->with(Argument::type('string'), 1, 'foo', 'packed-owner') + ->returns(0); + + $redis->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection)); + + $this->assertFalse($lock->release()); + } + public function testLockCanBeForceReleased(): void { [$lock, $redis] = $this->getLock(); - $redis->shouldReceive('del') - ->once() + $redis->expects('del') ->with('foo'); $lock->forceRelease(); - $this->assertTrue(true); + } + + public function testOwnerReturnsTheOwnerIdentifier(): void + { + $redis = Double::for(CacheLockRedisProxy::class); + + $lock = new RedisLock($redis, 'lock:foo', 60, 'my-owner-id'); + + $this->assertSame('my-owner-id', $lock->owner()); + } + + public function testOwnerIsAutoGeneratedWhenNotProvided(): void + { + [$lock] = $this->getLock(); + + $this->assertNotEmpty($lock->owner()); + } + + public function testGetCallsAcquireAndExecutesCallbackOnSuccess(): void + { + [$lock, $redis] = $this->getLock(seconds: 60); + $connection = Double::for(CacheLockRedisConnection::class); + $connection->expects('pack') + ->with([$lock->owner()]) + ->returns(['packed-owner']); + $connection->expects('eval') + ->returns(1); + + $redis->expects('set') + ->with('foo', Argument::type('string'), 'EX', 60, 'NX') + ->returns(true); + $redis->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection)); + + $result = $lock->get(fn () => 'callback-result'); + + $this->assertSame('callback-result', $result); + } + + public function testGetReturnsFalseWhenLockNotAcquired(): void + { + [$lock, $redis] = $this->getLock(seconds: 60); + $redis->expects('set') + ->with('foo', Argument::type('string'), 'EX', 60, 'NX') + ->returns(false); + + $redis->expects('withConnection')->never(); + + $result = $lock->get(fn () => $this->fail('A failed acquisition must not run the callback.')); + + $this->assertFalse($result); + } + + public function testGetReleasesLockAfterCallbackEvenOnException(): void + { + [$lock, $redis] = $this->getLock(seconds: 60); + $connection = Double::for(CacheLockRedisConnection::class); + $connection->expects('pack') + ->with([$lock->owner()]) + ->returns(['packed-owner']); + $connection->expects('eval') + ->returns(1); + + $redis->expects('set') + ->returns(true); + $redis->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection)); + + $failure = new RuntimeException('test exception'); + + try { + $lock->get(static fn () => throw $failure); + $this->fail('The callback failure was not thrown.'); + } catch (RuntimeException $exception) { + $this->assertSame($failure, $exception); + } } public function testRefreshExtendsLockTtl(): void { [$lock, $redis] = $this->getLock(); - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('pack') - ->once() + $connection = Double::for(CacheLockRedisConnection::class); + $connection->expects('pack') ->with([$lock->owner()]) - ->andReturn(['packed-owner']); - $connection->shouldReceive('eval') - ->once() - ->with(m::type('string'), 1, 'foo', 'packed-owner', 10) - ->andReturn(1); + ->returns(['packed-owner']); + $connection->expects('eval') + ->with(Argument::type('string'), 1, 'foo', 'packed-owner', 10) + ->returns(1); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection)); + $redis->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection)); $this->assertTrue($lock->refresh()); } @@ -103,19 +213,16 @@ public function testRefreshWithCustomTtl(): void { [$lock, $redis] = $this->getLock(); - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('pack') - ->once() + $connection = Double::for(CacheLockRedisConnection::class); + $connection->expects('pack') ->with([$lock->owner()]) - ->andReturn(['packed-owner']); - $connection->shouldReceive('eval') - ->once() - ->with(m::type('string'), 1, 'foo', 'packed-owner', 30) - ->andReturn(1); + ->returns(['packed-owner']); + $connection->expects('eval') + ->with(Argument::type('string'), 1, 'foo', 'packed-owner', 30) + ->returns(1); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection)); + $redis->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection)); $this->assertTrue($lock->refresh(30)); } @@ -124,19 +231,16 @@ public function testRefreshReturnsFalseWhenNotOwned(): void { [$lock, $redis] = $this->getLock(); - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('pack') - ->once() + $connection = Double::for(CacheLockRedisConnection::class); + $connection->expects('pack') ->with([$lock->owner()]) - ->andReturn(['packed-owner']); - $connection->shouldReceive('eval') - ->once() - ->with(m::type('string'), 1, 'foo', 'packed-owner', 10) - ->andReturn(0); + ->returns(['packed-owner']); + $connection->expects('eval') + ->with(Argument::type('string'), 1, 'foo', 'packed-owner', 10) + ->returns(0); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection)); + $redis->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection)); $this->assertFalse($lock->refresh()); } @@ -145,10 +249,9 @@ public function testRefreshOnPermanentLockReturnsTrueWhenStillOwned(): void { [$lock, $redis] = $this->getLock(seconds: 0); - $redis->shouldReceive('get') - ->once() + $redis->expects('get') ->with('foo') - ->andReturn($lock->owner()); + ->returns($lock->owner()); $this->assertTrue($lock->refresh()); } @@ -157,10 +260,9 @@ public function testRefreshOnPermanentLockReturnsFalseWhenNotOwned(): void { [$lock, $redis] = $this->getLock(seconds: 0); - $redis->shouldReceive('get') - ->once() + $redis->expects('get') ->with('foo') - ->andReturn('other-owner'); + ->returns('other-owner'); $this->assertFalse($lock->refresh()); } @@ -169,10 +271,9 @@ public function testIsLockedReturnsTrueWhenLockExists(): void { [$lock, $redis] = $this->getLock(); - $redis->shouldReceive('get') - ->once() + $redis->expects('get') ->with('foo') - ->andReturn('owner'); + ->returns('owner'); $this->assertTrue($lock->isLocked()); } @@ -181,10 +282,9 @@ public function testIsLockedReturnsFalseWhenLockDoesNotExist(): void { [$lock, $redis] = $this->getLock(); - $redis->shouldReceive('get') - ->once() + $redis->expects('get') ->with('foo') - ->andReturn(null); + ->returns(null); $this->assertFalse($lock->isLocked()); } @@ -213,10 +313,9 @@ public function testGetRemainingLifetimeReturnsSeconds(): void { [$lock, $redis] = $this->getLock(); - $redis->shouldReceive('ttl') - ->once() + $redis->expects('ttl') ->with('foo') - ->andReturn(5); + ->returns(5); $this->assertSame(5.0, $lock->getRemainingLifetime()); } @@ -225,10 +324,9 @@ public function testGetRemainingLifetimeReturnsNullWhenKeyDoesNotExist(): void { [$lock, $redis] = $this->getLock(); - $redis->shouldReceive('ttl') - ->once() + $redis->expects('ttl') ->with('foo') - ->andReturn(-2); + ->returns(-2); $this->assertNull($lock->getRemainingLifetime()); } @@ -237,10 +335,9 @@ public function testGetRemainingLifetimeReturnsNullWhenNoExpiry(): void { [$lock, $redis] = $this->getLock(); - $redis->shouldReceive('ttl') - ->once() + $redis->expects('ttl') ->with('foo') - ->andReturn(-1); + ->returns(-1); $this->assertNull($lock->getRemainingLifetime()); } @@ -249,23 +346,67 @@ public function testGetRemainingLifetimeReturnsZeroWhenExpired(): void { [$lock, $redis] = $this->getLock(); - $redis->shouldReceive('ttl') - ->once() + $redis->expects('ttl') ->with('foo') - ->andReturn(0); + ->returns(0); $this->assertSame(0.0, $lock->getRemainingLifetime()); } + public function testGetConnectionNameReturnsConnectionName(): void + { + [$lock, $redis] = $this->getLock(seconds: 60); + $redis->expects('getName')->returns('default'); + + $this->assertSame('default', $lock->getConnectionName()); + } + /** * Get a RedisLock instance with mocked dependencies. */ protected function getLock(int $seconds = 10): array { - $redis = m::mock(RedisProxy::class); + $redis = Double::for(CacheLockRedisProxy::class); $lock = new RedisLock($redis, 'foo', $seconds); return [$lock, $redis]; } } + +// Declare the dynamic commands so Double can verify their arguments and calls. +abstract class CacheLockRedisProxy extends RedisProxy +{ + /** + * Store a value with optional expiration and existence conditions. + */ + abstract public function set(string $key, mixed $value, mixed $expireResolution = null, ?int $expireTTL = null, ?string $flag = null): mixed; + + /** + * Store a value only when the key does not exist. + */ + abstract public function setnx(string $key, mixed $value): int; + + /** + * Retrieve a value. + */ + abstract public function get(string $key): mixed; + + /** + * Delete the given keys. + */ + abstract public function del(array|string $key, string ...$otherKeys): Redis|RedisCluster|int|false; + + /** + * Get the remaining key lifetime. + */ + abstract public function ttl(string $key): Redis|RedisCluster|int|false; +} + +abstract class CacheLockRedisConnection extends PhpRedisConnection +{ + /** + * Execute a Lua script with separate keys and arguments. + */ + abstract public function eval(string $script, int $numberOfKeys, mixed ...$arguments): mixed; +} diff --git a/tests/Cache/CacheRepositoryEnumTest.php b/tests/Cache/CacheRepositoryEnumTest.php index 44969d06f0..75201d9e64 100644 --- a/tests/Cache/CacheRepositoryEnumTest.php +++ b/tests/Cache/CacheRepositoryEnumTest.php @@ -12,7 +12,9 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use stdClass; enum CacheRepositoryEnumTestKeyBackedEnum: string @@ -54,10 +56,12 @@ enum CacheRepositoryEnumTestTagIntBackedEnum: int class CacheRepositoryEnumTest extends TestCase { + use VerifiesDoubles; + public function testGetWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('user-profile')->andReturn('cached-value'); + $repo->getStore()->expects('get')->with('user-profile')->returns('cached-value'); $this->assertSame('cached-value', $repo->get(CacheRepositoryEnumTestKeyBackedEnum::UserProfile)); } @@ -65,7 +69,7 @@ public function testGetWithBackedEnum(): void public function testGetWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('Dashboard')->andReturn('dashboard-data'); + $repo->getStore()->expects('get')->with('Dashboard')->returns('dashboard-data'); $this->assertSame('dashboard-data', $repo->get(CacheRepositoryEnumTestKeyUnitEnum::Dashboard)); } @@ -73,7 +77,7 @@ public function testGetWithUnitEnum(): void public function testGetWithIntBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('1')->andReturn('counter-value'); + $repo->getStore()->expects('get')->with('1')->returns('counter-value'); $this->assertSame('counter-value', $repo->get(CacheRepositoryEnumTestKeyIntBackedEnum::Counter)); } @@ -163,7 +167,7 @@ public function testCacheEventsNormalizeIntegerBackedEnumKeys(): void public function testHasWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('user-profile')->andReturn('value'); + $repo->getStore()->expects('get')->with('user-profile')->returns('value'); $this->assertTrue($repo->has(CacheRepositoryEnumTestKeyBackedEnum::UserProfile)); } @@ -171,7 +175,7 @@ public function testHasWithBackedEnum(): void public function testHasWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('Dashboard')->andReturn(null); + $repo->getStore()->expects('get')->with('Dashboard')->returns(null); $this->assertFalse($repo->has(CacheRepositoryEnumTestKeyUnitEnum::Dashboard)); } @@ -179,7 +183,7 @@ public function testHasWithUnitEnum(): void public function testMissingWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('settings')->andReturn(null); + $repo->getStore()->expects('get')->with('settings')->returns(null); $this->assertTrue($repo->missing(CacheRepositoryEnumTestKeyBackedEnum::Settings)); } @@ -187,7 +191,7 @@ public function testMissingWithBackedEnum(): void public function testPutWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('put')->once()->with('user-profile', 'value', 60)->andReturn(true); + $repo->getStore()->expects('put')->with('user-profile', 'value', 60)->returns(true); $this->assertTrue($repo->put(CacheRepositoryEnumTestKeyBackedEnum::UserProfile, 'value', 60)); } @@ -195,7 +199,7 @@ public function testPutWithBackedEnum(): void public function testPutWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('put')->once()->with('Dashboard', 'data', 120)->andReturn(true); + $repo->getStore()->expects('put')->with('Dashboard', 'data', 120)->returns(true); $this->assertTrue($repo->put(CacheRepositoryEnumTestKeyUnitEnum::Dashboard, 'data', 120)); } @@ -203,7 +207,7 @@ public function testPutWithUnitEnum(): void public function testSetWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('put')->once()->with('settings', 'config', 300)->andReturn(true); + $repo->getStore()->expects('put')->with('settings', 'config', 300)->returns(true); $this->assertTrue($repo->set(CacheRepositoryEnumTestKeyBackedEnum::Settings, 'config', 300)); } @@ -211,8 +215,8 @@ public function testSetWithBackedEnum(): void public function testAddWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('user-profile')->andReturn(null); - $repo->getStore()->shouldReceive('put')->once()->with('user-profile', 'new-value', 60)->andReturn(true); + $repo->getStore()->expects('get')->with('user-profile')->returns(null); + $repo->getStore()->expects('put')->with('user-profile', 'new-value', 60)->returns(true); $this->assertTrue($repo->add(CacheRepositoryEnumTestKeyBackedEnum::UserProfile, 'new-value', 60)); } @@ -220,8 +224,8 @@ public function testAddWithBackedEnum(): void public function testAddWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('Analytics')->andReturn(null); - $repo->getStore()->shouldReceive('put')->once()->with('Analytics', 'data', 60)->andReturn(true); + $repo->getStore()->expects('get')->with('Analytics')->returns(null); + $repo->getStore()->expects('put')->with('Analytics', 'data', 60)->returns(true); $this->assertTrue($repo->add(CacheRepositoryEnumTestKeyUnitEnum::Analytics, 'data', 60)); } @@ -229,7 +233,7 @@ public function testAddWithUnitEnum(): void public function testIncrementWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('increment')->once()->with('user-profile', 1)->andReturn(2); + $repo->getStore()->expects('increment')->with('user-profile', 1)->returns(2); $this->assertSame(2, $repo->increment(CacheRepositoryEnumTestKeyBackedEnum::UserProfile)); } @@ -237,7 +241,7 @@ public function testIncrementWithBackedEnum(): void public function testIncrementWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('increment')->once()->with('Dashboard', 5)->andReturn(10); + $repo->getStore()->expects('increment')->with('Dashboard', 5)->returns(10); $this->assertSame(10, $repo->increment(CacheRepositoryEnumTestKeyUnitEnum::Dashboard, 5)); } @@ -245,7 +249,7 @@ public function testIncrementWithUnitEnum(): void public function testDecrementWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('decrement')->once()->with('settings', 1)->andReturn(4); + $repo->getStore()->expects('decrement')->with('settings', 1)->returns(4); $this->assertSame(4, $repo->decrement(CacheRepositoryEnumTestKeyBackedEnum::Settings)); } @@ -253,7 +257,7 @@ public function testDecrementWithBackedEnum(): void public function testDecrementWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('decrement')->once()->with('Analytics', 3)->andReturn(7); + $repo->getStore()->expects('decrement')->with('Analytics', 3)->returns(7); $this->assertSame(7, $repo->decrement(CacheRepositoryEnumTestKeyUnitEnum::Analytics, 3)); } @@ -261,7 +265,7 @@ public function testDecrementWithUnitEnum(): void public function testForeverWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('forever')->once()->with('user-profile', 'permanent')->andReturn(true); + $repo->getStore()->expects('forever')->with('user-profile', 'permanent')->returns(true); $this->assertTrue($repo->forever(CacheRepositoryEnumTestKeyBackedEnum::UserProfile, 'permanent')); } @@ -269,7 +273,7 @@ public function testForeverWithBackedEnum(): void public function testForeverWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('forever')->once()->with('Dashboard', 'forever-data')->andReturn(true); + $repo->getStore()->expects('forever')->with('Dashboard', 'forever-data')->returns(true); $this->assertTrue($repo->forever(CacheRepositoryEnumTestKeyUnitEnum::Dashboard, 'forever-data')); } @@ -277,8 +281,8 @@ public function testForeverWithUnitEnum(): void public function testRememberWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('settings')->andReturn(null); - $repo->getStore()->shouldReceive('put')->once()->with('settings', 'computed', 60)->andReturn(true); + $repo->getStore()->expects('get')->with('settings')->returns(null); + $repo->getStore()->expects('put')->with('settings', 'computed', 60)->returns(true); $result = $repo->remember(CacheRepositoryEnumTestKeyBackedEnum::Settings, 60, fn () => 'computed'); @@ -288,8 +292,8 @@ public function testRememberWithBackedEnum(): void public function testRememberWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('Analytics')->andReturn(null); - $repo->getStore()->shouldReceive('put')->once()->with('Analytics', 'analytics-data', 120)->andReturn(true); + $repo->getStore()->expects('get')->with('Analytics')->returns(null); + $repo->getStore()->expects('put')->with('Analytics', 'analytics-data', 120)->returns(true); $result = $repo->remember(CacheRepositoryEnumTestKeyUnitEnum::Analytics, 120, fn () => 'analytics-data'); @@ -299,8 +303,8 @@ public function testRememberWithUnitEnum(): void public function testRememberForeverWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('user-profile')->andReturn(null); - $repo->getStore()->shouldReceive('forever')->once()->with('user-profile', 'forever-value')->andReturn(true); + $repo->getStore()->expects('get')->with('user-profile')->returns(null); + $repo->getStore()->expects('forever')->with('user-profile', 'forever-value')->returns(true); $result = $repo->rememberForever(CacheRepositoryEnumTestKeyBackedEnum::UserProfile, fn () => 'forever-value'); @@ -310,8 +314,8 @@ public function testRememberForeverWithBackedEnum(): void public function testSearWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('Dashboard')->andReturn(null); - $repo->getStore()->shouldReceive('forever')->once()->with('Dashboard', 'seared')->andReturn(true); + $repo->getStore()->expects('get')->with('Dashboard')->returns(null); + $repo->getStore()->expects('forever')->with('Dashboard', 'seared')->returns(true); $result = $repo->sear(CacheRepositoryEnumTestKeyUnitEnum::Dashboard, fn () => 'seared'); @@ -321,7 +325,7 @@ public function testSearWithUnitEnum(): void public function testForgetWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('forget')->once()->with('user-profile')->andReturn(true); + $repo->getStore()->expects('forget')->with('user-profile')->returns(true); $this->assertTrue($repo->forget(CacheRepositoryEnumTestKeyBackedEnum::UserProfile)); } @@ -329,7 +333,7 @@ public function testForgetWithBackedEnum(): void public function testForgetWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('forget')->once()->with('Dashboard')->andReturn(true); + $repo->getStore()->expects('forget')->with('Dashboard')->returns(true); $this->assertTrue($repo->forget(CacheRepositoryEnumTestKeyUnitEnum::Dashboard)); } @@ -337,7 +341,7 @@ public function testForgetWithUnitEnum(): void public function testDeleteWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('forget')->once()->with('settings')->andReturn(true); + $repo->getStore()->expects('forget')->with('settings')->returns(true); $this->assertTrue($repo->delete(CacheRepositoryEnumTestKeyBackedEnum::Settings)); } @@ -345,8 +349,8 @@ public function testDeleteWithBackedEnum(): void public function testPullWithBackedEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('user-profile')->andReturn('pulled-value'); - $repo->getStore()->shouldReceive('forget')->once()->with('user-profile')->andReturn(true); + $repo->getStore()->expects('get')->with('user-profile')->returns('pulled-value'); + $repo->getStore()->expects('forget')->with('user-profile')->returns(true); $this->assertSame('pulled-value', $repo->pull(CacheRepositoryEnumTestKeyBackedEnum::UserProfile)); } @@ -354,8 +358,8 @@ public function testPullWithBackedEnum(): void public function testPullWithUnitEnum(): void { $repo = $this->getRepository(); - $repo->getStore()->shouldReceive('get')->once()->with('Analytics')->andReturn('analytics'); - $repo->getStore()->shouldReceive('forget')->once()->with('Analytics')->andReturn(true); + $repo->getStore()->expects('get')->with('Analytics')->returns('analytics'); + $repo->getStore()->expects('forget')->with('Analytics')->returns(true); $this->assertSame('analytics', $repo->pull(CacheRepositoryEnumTestKeyUnitEnum::Analytics)); } @@ -438,24 +442,24 @@ public function testTagsWithMixedEnumsAndStrings(): void public function testTagsWithBackedEnumVariadicArgs(): void { - $store = m::mock(ArrayStore::class); + $store = Double::for(ArrayStore::class); $repo = new Repository($store); - $taggedCache = m::mock(TaggedCache::class); - $taggedCache->shouldReceive('setDefaultCacheTime')->andReturnSelf(); - $store->shouldReceive('tags')->once()->with(['users', 'posts'])->andReturn($taggedCache); + $taggedCache = Double::for(TaggedCache::class); + $taggedCache->allows('setDefaultCacheTime'); + $store->expects('tags')->with(['users', 'posts'])->returns($taggedCache); $repo->tags(CacheRepositoryEnumTestTagBackedEnum::Users, CacheRepositoryEnumTestTagBackedEnum::Posts); } public function testTagsWithUnitEnumVariadicArgs(): void { - $store = m::mock(ArrayStore::class); + $store = Double::for(ArrayStore::class); $repo = new Repository($store); - $taggedCache = m::mock(TaggedCache::class); - $taggedCache->shouldReceive('setDefaultCacheTime')->andReturnSelf(); - $store->shouldReceive('tags')->once()->with(['Reports', 'Exports'])->andReturn($taggedCache); + $taggedCache = Double::for(TaggedCache::class); + $taggedCache->allows('setDefaultCacheTime'); + $store->expects('tags')->with(['Reports', 'Exports'])->returns($taggedCache); $repo->tags(CacheRepositoryEnumTestTagUnitEnum::Reports, CacheRepositoryEnumTestTagUnitEnum::Exports); } @@ -506,10 +510,10 @@ public function testOffsetAccessWithUnitEnum(): void protected function getRepository(): Repository { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $dispatcher->shouldReceive('dispatch')->with(m::any())->andReturnNull(); - $repository = new Repository(m::mock(Store::class)); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(true); + $dispatcher->allows('dispatch')->with(Argument::any())->returns(null); + $repository = new Repository(Double::for(Store::class)); $repository->setEventDispatcher($dispatcher); diff --git a/tests/Cache/CacheServiceProviderTest.php b/tests/Cache/CacheServiceProviderTest.php index 9048a4ccf9..aa26ddc990 100644 --- a/tests/Cache/CacheServiceProviderTest.php +++ b/tests/Cache/CacheServiceProviderTest.php @@ -17,48 +17,44 @@ use Hypervel\ServerProcess\Events\BeforeProcessHandle; use Hypervel\Support\Facades\Cache; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use Swoole\Server as SwooleServer; class CacheServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testConsoleFinalizationRunsAfterEveryProviderCanContribute(): void { $manager = $this->manager(); $manager->allowSerializableClassesUsing( static fn (): array => [CachePolicyEarlyContribution::class], ); - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class); $listeners = []; - $events->shouldReceive('listen') + $events->expects('listen') ->times(2) - ->andReturnUsing(function (mixed $event, mixed $listener) use (&$listeners): void { + ->resolves(function (mixed $event, mixed $listener) use (&$listeners): void { $listeners[$event][] = $listener; }); $bootedCallback = null; - $application = m::mock(Application::class); - $application->shouldReceive('make') - ->once() + $application = Double::for(Application::class, override: true); + $application->expects('make') ->with(CacheManager::class) - ->andReturn($manager); - $application->shouldReceive('make') - ->once() + ->returns($manager); + $application->expects('make') ->with('events') - ->andReturn($events); - $application->shouldReceive('runningInConsole') - ->once() - ->andReturnTrue(); - $application->shouldReceive('booted') - ->once() - ->with(m::on(function (mixed $callback) use (&$bootedCallback): bool { - $bootedCallback = $callback; - - return $callback instanceof Closure; - })); + ->returns($events); + $application->expects('runningInConsole') + ->returns(true); + $application->expects('booted') + ->with(Argument::capture($bootedCallback)); - (new CacheServiceProvider($application))->boot(); + (new CacheServiceProvider($application->instance()))->boot(); $manager->allowSerializableClassesUsing( static fn (): array => [CachePolicyLateContribution::class], @@ -89,29 +85,26 @@ public function testConsoleFinalizationRunsAfterEveryProviderCanContribute(): vo public function testServerFinalizationResolvesTheWorkerManagerAtEventTime(bool $customProcess): void { $workerManager = $this->manager(); - $events = m::mock(Dispatcher::class); + $events = Double::for(Dispatcher::class); $listeners = []; - $events->shouldReceive('listen') + $events->expects('listen') ->times(3) - ->andReturnUsing(function (mixed $event, mixed $listener) use (&$listeners): void { + ->resolves(function (mixed $event, mixed $listener) use (&$listeners): void { foreach ((array) $event as $name) { $listeners[$name][] = $listener; } }); - $application = m::mock(Application::class); - $application->shouldReceive('make') - ->once() + $application = Double::for(Application::class, override: true); + $application->expects('make') ->with(CacheManager::class) - ->andReturn($workerManager); - $application->shouldReceive('make') - ->once() + ->returns($workerManager); + $application->expects('make') ->with('events') - ->andReturn($events); - $application->shouldReceive('runningInConsole') - ->once() - ->andReturnFalse(); - $application->shouldNotReceive('booted'); - $provider = new CacheServiceProviderFixture($application); + ->returns($events); + $application->expects('runningInConsole') + ->returns(false); + $application->expects('booted')->never(); + $provider = new CacheServiceProviderFixture($application->instance()); $provider->boot(); @@ -120,9 +113,9 @@ public function testServerFinalizationResolvesTheWorkerManagerAtEventTime(bool $ $this->assertCount(2, $listeners[AfterWorkerStart::class]); if ($customProcess) { - $event = new BeforeProcessHandle(m::mock(AbstractProcess::class), 0); + $event = new BeforeProcessHandle(Double::for(AbstractProcess::class), 0); } else { - $server = m::mock(SwooleServer::class); + $server = Double::for(SwooleServer::class); // Policy finalization runs in request workers and taskworkers, unlike Swoole timer registration. $server->taskworker = true; $event = new AfterWorkerStart($server, 9); @@ -138,12 +131,10 @@ public function testServerFinalizationResolvesTheWorkerManagerAtEventTime(bool $ public function testFacadeCallsTheManagerExtensionWithoutResolvingAStore(): void { $resolver = static fn (): array => [CachePolicyEarlyContribution::class]; - $manager = m::mock(CacheManager::class); - $manager->shouldReceive('allowSerializableClassesUsing') - ->once() - ->with($resolver) - ->andReturnSelf(); - $manager->shouldNotReceive('store'); + $manager = Double::for(CacheManager::class); + $manager->expects('allowSerializableClassesUsing') + ->with(Argument::same($resolver)); + $manager->expects('store')->never(); Cache::setFacadeApplication(null); Cache::swap($manager); diff --git a/tests/Cache/CacheStackStoreLocksTest.php b/tests/Cache/CacheStackStoreLocksTest.php index ac1b77430d..a06085b9f7 100644 --- a/tests/Cache/CacheStackStoreLocksTest.php +++ b/tests/Cache/CacheStackStoreLocksTest.php @@ -11,16 +11,20 @@ use Hypervel\Contracts\Cache\LockProvider; use Hypervel\Contracts\Cache\Store; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CacheStackStoreLocksTest extends TestCase { + use VerifiesDoubles; + public function testLockDelegatesToBottomLayer(): void { - $bottom = m::mock(Store::class, LockProvider::class); - $lock = m::mock(Lock::class); + $bottom = Double::for(Store::class, LockProvider::class); + $lock = Double::for(Lock::class); - $bottom->shouldReceive('lock')->once()->with('name', 30, 'owner')->andReturn($lock); + $bottom->expects('lock')->with('name', 30, 'owner')->returns($lock); $stack = new StackStore([$this->plainStore(), $bottom]); @@ -29,10 +33,10 @@ public function testLockDelegatesToBottomLayer(): void public function testRestoreLockDelegatesToBottomLayer(): void { - $bottom = m::mock(Store::class, LockProvider::class); - $lock = m::mock(Lock::class); + $bottom = Double::for(Store::class, LockProvider::class); + $lock = Double::for(Lock::class); - $bottom->shouldReceive('restoreLock')->once()->with('name', 'owner')->andReturn($lock); + $bottom->expects('restoreLock')->with('name', 'owner')->returns($lock); $stack = new StackStore([$this->plainStore(), $bottom]); @@ -51,16 +55,16 @@ public function testLockThrowsWhenBottomLayerDoesNotSupportLocks(): void public function testSupportsFlushingLocksReflectsBottomLayerProbe(): void { - $bottom = m::mock(Store::class, CanFlushLocks::class); - $bottom->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); + $bottom = Double::for(Store::class, CanFlushLocks::class); + $bottom->expects('supportsFlushingLocks')->returns(true); $this->assertTrue((new StackStore([$this->plainStore(), $bottom]))->supportsFlushingLocks()); } public function testSupportsFlushingLocksReturnsFalseWhenBottomLayerProbeIsFalse(): void { - $bottom = m::mock(Store::class, CanFlushLocks::class); - $bottom->shouldReceive('supportsFlushingLocks')->once()->andReturnFalse(); + $bottom = Double::for(Store::class, CanFlushLocks::class); + $bottom->expects('supportsFlushingLocks')->returns(false); $this->assertFalse((new StackStore([$this->plainStore(), $bottom]))->supportsFlushingLocks()); } @@ -72,18 +76,18 @@ public function testSupportsFlushingLocksReturnsFalseWhenBottomLayerDoesNotImple public function testFlushLocksDelegatesToBottomLayer(): void { - $bottom = m::mock(Store::class, CanFlushLocks::class); - $bottom->shouldReceive('supportsFlushingLocks')->once()->andReturnTrue(); - $bottom->shouldReceive('flushLocks')->once()->andReturnTrue(); + $bottom = Double::for(Store::class, CanFlushLocks::class); + $bottom->expects('supportsFlushingLocks')->returns(true); + $bottom->expects('flushLocks')->returns(true); $this->assertTrue((new StackStore([$this->plainStore(), $bottom]))->flushLocks()); } public function testFlushLocksThrowsWhenBottomLayerCannotFlushLocks(): void { - $bottom = m::mock(Store::class, CanFlushLocks::class); - $bottom->shouldReceive('supportsFlushingLocks')->once()->andReturnFalse(); - $bottom->shouldNotReceive('flushLocks'); + $bottom = Double::for(Store::class, CanFlushLocks::class); + $bottom->expects('supportsFlushingLocks')->returns(false); + $bottom->expects('flushLocks')->never(); $stack = new StackStore([$this->plainStore(), $bottom]); @@ -95,14 +99,17 @@ public function testFlushLocksThrowsWhenBottomLayerCannotFlushLocks(): void public function testHasSeparateLockStoreDelegatesToBottomLayer(): void { - $bottom = m::mock(Store::class, CanFlushLocks::class); - $bottom->shouldReceive('hasSeparateLockStore')->once()->andReturnTrue(); + $bottom = Double::for(Store::class, CanFlushLocks::class); + $bottom->expects('hasSeparateLockStore')->returns(true); $this->assertTrue((new StackStore([$this->plainStore(), $bottom]))->hasSeparateLockStore()); } - private function plainStore(): Store|m\MockInterface + /** + * Create a store without lock capabilities. + */ + private function plainStore(): Store&DoubleInterface { - return m::mock(Store::class); + return Double::for(Store::class); } } diff --git a/tests/Cache/CacheStackStoreTagsTest.php b/tests/Cache/CacheStackStoreTagsTest.php index e63f3ed72e..1d683f6189 100644 --- a/tests/Cache/CacheStackStoreTagsTest.php +++ b/tests/Cache/CacheStackStoreTagsTest.php @@ -32,7 +32,10 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use stdClass; @@ -41,6 +44,8 @@ class CacheStackStoreTagsTest extends TestCase { + use VerifiesDoubles; + public function testValidCompositionsSupportTags(): void { foreach ([ @@ -92,9 +97,9 @@ public function testStringKeyedLayersUseZeroBasedIndexesInCompositionErrors(): v public function testInvalidNestedStackDoesNotCallGetTagMode(): void { - $taggable = m::mock(TaggableStore::class); - $taggable->shouldReceive('supportsTags')->once()->andReturnFalse(); - $taggable->shouldNotReceive('getTagMode'); + $taggable = Double::for(TaggableStore::class); + $taggable->expects('supportsTags')->returns(false); + $taggable->expects('getTagMode')->never(); $stack = new StackStore([$taggable]); @@ -103,9 +108,9 @@ public function testInvalidNestedStackDoesNotCallGetTagMode(): void public function testValidationRunsOnce(): void { - $taggable = m::mock(TaggableStore::class); - $taggable->shouldReceive('supportsTags')->once()->andReturnTrue(); - $taggable->shouldReceive('getTagMode')->once()->andReturn(TagMode::Any); + $taggable = Double::for(TaggableStore::class); + $taggable->expects('supportsTags')->returns(true); + $taggable->expects('getTagMode')->returns(TagMode::Any); $stack = new StackStore([$taggable]); @@ -118,17 +123,15 @@ public function testTaggedPutWritesPlainUpperLayersAndTaggedLowerLayersWithTtlCl { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); - - $plain->shouldReceive('put') - ->once() - ->with('key', m::on(fn (array $record): bool => $record['value'] === 'value' && isset($record['expiration'])), 3) - ->andReturnTrue(); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put') - ->once() - ->with('key', m::on(fn (array $record): bool => $record['value'] === 'value' && isset($record['expiration'])), 60) - ->andReturnTrue(); + $taggedCache = Double::for(TaggedCache::class); + + $plain->expects('put') + ->with('key', Argument::satisfies(fn (array $record): bool => $record['value'] === 'value' && isset($record['expiration'])), 3) + ->returns(true); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put') + ->with('key', Argument::satisfies(fn (array $record): bool => $record['value'] === 'value' && isset($record['expiration'])), 60) + ->returns(true); $stack = new StackStore([ new StackStoreProxy($plain, 3), @@ -142,11 +145,11 @@ public function testTaggedForeverHonorsLayerTtlClamp(): void { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); - $plain->shouldReceive('put')->once()->with('key', ['value' => 'value'], 3)->andReturnTrue(); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('forever')->once()->with('key', ['value' => 'value'])->andReturnTrue(); + $plain->expects('put')->with('key', ['value' => 'value'], 3)->returns(true); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('forever')->with('key', ['value' => 'value'])->returns(true); $stack = new StackStore([ new StackStoreProxy($plain, 3), @@ -159,13 +162,12 @@ public function testTaggedForeverHonorsLayerTtlClamp(): void public function testTaggedPutClampsTtlOnTaggableLayer(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put') - ->once() - ->with('key', m::on(fn (array $record): bool => $record['value'] === 'value' && isset($record['expiration'])), 3) - ->andReturnTrue(); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put') + ->with('key', Argument::satisfies(fn (array $record): bool => $record['value'] === 'value' && isset($record['expiration'])), 3) + ->returns(true); $stack = new StackStore([ new StackStoreProxy($taggable, 3), @@ -177,11 +179,11 @@ public function testTaggedPutClampsTtlOnTaggableLayer(): void public function testTaggedForeverClampsToPutOnTaggableLayerWithTtlOverride(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->once()->with('key', ['value' => 'value'], 3)->andReturnTrue(); - $taggedCache->shouldNotReceive('forever'); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->with('key', ['value' => 'value'], 3)->returns(true); + $taggedCache->expects('forever')->never(); $stack = new StackStore([ new StackStoreProxy($taggable, 3), @@ -194,12 +196,12 @@ public function testTaggedWriteRollsBackWrittenLayersOnFailure(): void { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); - $plain->shouldReceive('put')->once()->andReturnTrue(); - $plain->shouldReceive('forget')->once()->with('key')->andReturnTrue(); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->once()->andReturnFalse(); + $plain->expects('put')->returns(true); + $plain->expects('forget')->with('key')->returns(true); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->returns(false); $stack = new StackStore([ new StackStoreProxy($plain), @@ -213,14 +215,23 @@ public function testTaggedWriteRollsBackWrittenLayersWhenLowerLayerThrows(): voi { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); $exception = new RuntimeException('write failed'); - $plain->shouldReceive('put')->once()->andReturnTrue(); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->once()->andThrow($exception); - $taggable->shouldReceive('forget')->once()->with('key')->globally()->ordered()->andReturnTrue(); - $plain->shouldReceive('forget')->once()->with('key')->globally()->ordered()->andReturnTrue(); + $plain->expects('put')->returns(true); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->throws($exception); + $released = []; + $taggable->expects('forget')->with('key')->resolves(function () use (&$released): bool { + $released[] = 'taggable'; + + return true; + }); + $plain->expects('forget')->with('key')->resolves(function () use (&$released): bool { + $released[] = 'plain'; + + return true; + }); $stack = new StackStore([ new StackStoreProxy($plain), @@ -233,16 +244,18 @@ public function testTaggedWriteRollsBackWrittenLayersWhenLowerLayerThrows(): voi } catch (RuntimeException $throwable) { $this->assertSame($exception, $throwable); } + + $this->assertSame(['taggable', 'plain'], $released); } public function testTaggedIncrementWritesThroughTaggedPath(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); - $taggable->shouldReceive('get')->once()->with('counter')->andReturn(['value' => 1]); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('forever')->once()->with('counter', ['value' => 3])->andReturnTrue(); + $taggable->expects('get')->with('counter')->returns(['value' => 1]); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('forever')->with('counter', ['value' => 3])->returns(true); $stack = new StackStore([$taggable]); @@ -256,13 +269,13 @@ public function testTaggedIncrementForgetsRecordThatExpiredDuringItsRead(): void $taggable = $this->anyModeTaggableStore(); $record = ['value' => 1, 'expiration' => CarbonImmutable::now()->getTimestamp() + 1]; - $taggable->shouldReceive('get')->once()->with('counter')->andReturnUsing(function () use ($record): array { + $taggable->expects('get')->with('counter')->resolves(function () use ($record): array { CarbonImmutable::setTestNow(CarbonImmutable::now()->addSeconds(2)); return $record; }); - $taggable->shouldReceive('forget')->once()->with('counter')->andReturnTrue(); - $taggable->shouldNotReceive('tags'); + $taggable->expects('forget')->with('counter')->returns(true); + $taggable->expects('tags')->never(); $stack = new StackStore([$taggable]); @@ -273,18 +286,18 @@ public function testTaggedIncrementDoesNotTreatFailedRepairAsMissingAndPreserves { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); $record = ['value' => 5]; $incrementedRecord = ['value' => 6]; - $plain->shouldReceive('get')->twice()->with('counter')->andReturnNull(); - $taggable->shouldReceive('get')->twice()->with('counter')->andReturn($record); - $plain->shouldReceive('forever')->twice()->with('counter', $record)->andReturnFalse(); + $plain->expects('get')->times(2)->with('counter')->returns(null); + $taggable->expects('get')->times(2)->with('counter')->returns($record); + $plain->expects('forever')->times(2)->with('counter', $record)->returns(false); - $plain->shouldReceive('forever')->once()->with('counter', $incrementedRecord)->andReturnTrue(); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('forever')->once()->with('counter', $incrementedRecord)->andReturnFalse(); - $plain->shouldReceive('forget')->once()->with('counter')->andReturnTrue(); + $plain->expects('forever')->with('counter', $incrementedRecord)->returns(true); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('forever')->with('counter', $incrementedRecord)->returns(false); + $plain->expects('forget')->with('counter')->returns(true); $stack = new StackStore([$plain, $taggable]); @@ -295,11 +308,11 @@ public function testTaggedIncrementDoesNotTreatFailedRepairAsMissingAndPreserves public function testTaggedRememberReadsPlainAndWritesTaggedOnMiss(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); - $taggable->shouldReceive('get')->once()->with('0')->andReturnNull(); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->once()->with('0', m::type('array'), 60)->andReturnTrue(); + $taggable->expects('get')->with('0')->returns(null); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->with('0', Argument::type('array'), 60)->returns(true); $stack = new StackStore([$taggable]); @@ -310,8 +323,8 @@ public function testTaggedRememberHitReadsPlainWithoutTaggedWrite(): void { $taggable = $this->anyModeTaggableStore(); - $taggable->shouldReceive('get')->once()->with('key')->andReturn(['value' => 'cached']); - $taggable->shouldNotReceive('tags'); + $taggable->expects('get')->with('key')->returns(['value' => 'cached']); + $taggable->expects('tags')->never(); $stack = new StackStore([$taggable]); @@ -321,10 +334,10 @@ public function testTaggedRememberHitReadsPlainWithoutTaggedWrite(): void public function testTaggedRememberHandlesIncompleteClassBeforeDispatchingHitEvent(): void { $taggable = $this->anyModeTaggableStore(); - $taggable->shouldReceive('get')->once()->with('key')->andReturn([ + $taggable->expects('get')->with('key')->returns([ 'value' => unserialize(serialize(new stdClass), ['allowed_classes' => false]), ]); - $taggable->shouldNotReceive('tags'); + $taggable->expects('tags')->never(); $sequence = []; @@ -348,11 +361,11 @@ public function testTaggedRememberHandlesIncompleteClassBeforeDispatchingHitEven public function testTaggedRememberMissDispatchesRepositoryReadAndWriteEvents(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); - $taggable->shouldReceive('get')->once()->with('key')->andReturnNull(); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->once()->with('key', m::type('array'), 60)->andReturnTrue(); + $taggable->expects('get')->with('key')->returns(null); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->with('key', Argument::type('array'), 60)->returns(true); $captured = []; $stack = new StackStore([$taggable]); @@ -375,10 +388,10 @@ public function testTaggedRememberMissDispatchesRepositoryReadAndWriteEvents(): public function testTaggedPutDispatchesRepositoryWriteFailureEvents(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->once()->with('key', m::type('array'), 60)->andReturnFalse(); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->with('key', Argument::type('array'), 60)->returns(false); $captured = []; $stack = new StackStore([$taggable]); @@ -398,10 +411,10 @@ public function testTaggedPutDispatchesRepositoryWriteFailureEvents(): void public function testStackAnyModeTaggedCacheSkipsEventDispatchSeamWithoutListenersAndEntersItWithListeners(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); - $taggable->shouldReceive('get')->twice()->andReturnNull(); - $taggable->shouldReceive('tags')->twice()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->twice()->with(m::type('string'), m::type('array'), 60)->andReturnTrue(); + $taggedCache = Double::for(TaggedCache::class); + $taggable->expects('get')->times(2)->returns(null); + $taggable->expects('tags')->times(2)->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->times(2)->with(Argument::type('string'), Argument::type('array'), 60)->returns(true); $stack = new StackStore([$taggable]); $cache = new class($stack, new StackTagSet($stack, ['tag'])) extends StackTaggedCache { @@ -414,9 +427,9 @@ protected function event(object $event): void parent::event($event); } }; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(false); + $dispatcher->expects('dispatch')->never(); $cache->setEventDispatcher($dispatcher); $this->assertTrue($cache->add('first', 'value', 60)); @@ -441,7 +454,7 @@ public function testTaggedRememberDispatchesRepositoryReadFailureEventWhenTheSto { $exception = new RuntimeException('read failed'); $taggable = $this->anyModeTaggableStore(); - $taggable->shouldReceive('get')->once()->with('key')->andThrow($exception); + $taggable->expects('get')->with('key')->throws($exception); $captured = []; $stack = new StackStore([$taggable]); @@ -472,7 +485,7 @@ public function testTaggedRememberDoesNotDispatchFailureEventWhenTheStoreIsCance $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } $taggable = $this->anyModeTaggableStore(); - $taggable->shouldReceive('get')->once()->with('key')->andThrow($cancellation); + $taggable->expects('get')->with('key')->throws($cancellation); $captured = []; $stack = new StackStore([$taggable]); @@ -493,10 +506,10 @@ public function testTaggedPutDispatchesRepositoryWriteFailureEventWhenTheStoreTh { $exception = new RuntimeException('write failed'); $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->once()->with('key', m::type('array'), 60)->andThrow($exception); - $taggable->shouldReceive('forget')->once()->with('key')->andReturnTrue(); + $taggedCache = Double::for(TaggedCache::class); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->with('key', Argument::type('array'), 60)->throws($exception); + $taggable->expects('forget')->with('key')->returns(true); $captured = []; $stack = new StackStore([$taggable]); @@ -524,10 +537,10 @@ public function testTaggedPutDoesNotDispatchFailureEventWhenTheStoreIsCanceled(b $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('put')->once()->with('key', m::type('array'), 60)->andThrow($cancellation); - $taggable->shouldReceive('forget')->once()->with('key')->andReturnTrue(); + $taggedCache = Double::for(TaggedCache::class); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('put')->with('key', Argument::type('array'), 60)->throws($cancellation); + $taggable->expects('forget')->with('key')->returns(true); $captured = []; $stack = new StackStore([$taggable]); @@ -548,10 +561,10 @@ public function testTaggedForeverDispatchesRepositoryWriteFailureEventWhenTheSto { $exception = new RuntimeException('forever write failed'); $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('forever')->once()->with('key', ['value' => 'value'])->andThrow($exception); - $taggable->shouldReceive('forget')->once()->with('key')->andReturnTrue(); + $taggedCache = Double::for(TaggedCache::class); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('forever')->with('key', ['value' => 'value'])->throws($exception); + $taggable->expects('forget')->with('key')->returns(true); $captured = []; $stack = new StackStore([$taggable]); @@ -580,10 +593,10 @@ public function testTaggedForeverDoesNotDispatchFailureEventWhenTheStoreIsCancel $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } $taggable = $this->anyModeTaggableStore(); - $taggedCache = m::mock(TaggedCache::class); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('forever')->once()->with('key', ['value' => 'value'])->andThrow($cancellation); - $taggable->shouldReceive('forget')->once()->with('key')->andReturnTrue(); + $taggedCache = Double::for(TaggedCache::class); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('forever')->with('key', ['value' => 'value'])->throws($cancellation); + $taggable->expects('forget')->with('key')->returns(true); $captured = []; $stack = new StackStore([$taggable]); @@ -604,7 +617,7 @@ public function testTaggedExpiredPutDispatchesRepositoryForgetFailureEventWhenTh { $exception = new RuntimeException('forget failed'); $taggable = $this->anyModeTaggableStore(); - $taggable->shouldReceive('forget')->once()->with('key')->andThrow($exception); + $taggable->expects('forget')->with('key')->throws($exception); $captured = []; $stack = new StackStore([$taggable]); @@ -632,7 +645,7 @@ public function testTaggedExpiredPutDoesNotDispatchFailureEventWhenTheStoreIsCan $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } $taggable = $this->anyModeTaggableStore(); - $taggable->shouldReceive('forget')->once()->with('key')->andThrow($cancellation); + $taggable->expects('forget')->with('key')->throws($cancellation); $captured = []; $stack = new StackStore([$taggable]); @@ -652,7 +665,7 @@ public function testTaggedExpiredPutDoesNotDispatchFailureEventWhenTheStoreIsCan public function testTaggedPutWithExpiredTtlDispatchesRepositoryDeleteEvents(): void { $taggable = $this->anyModeTaggableStore(); - $taggable->shouldReceive('forget')->once()->with('key')->andReturnTrue(); + $taggable->expects('forget')->with('key')->returns(true); $captured = []; $stack = new StackStore([$taggable]); @@ -693,33 +706,35 @@ public function testTaggedReadAndDeleteOperationsThrow(): void public function testClearFlushesTaggableLayersOnly(): void { $taggable = $this->anyModeTaggableStore(); - $tagSet = m::mock(TagSet::class); - $taggedCache = m::mock(TaggedCache::class); + $tagSet = Double::for(TagSet::class); + $taggedCache = Double::for(TaggedCache::class); - $taggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($taggedCache); - $taggedCache->shouldReceive('getTags')->once()->andReturn($tagSet); - $tagSet->shouldReceive('flush')->once()->andReturnTrue(); + $taggable->expects('tags')->with(['tag'])->returns($taggedCache); + $taggedCache->expects('getTags')->returns($tagSet); + $tagSet->expects('flush')->returns(true); - $stack = new StackStore([$this->nonTaggableStore(), $taggable]); + $plain = $this->nonTaggableStore(); + $stack = new StackStore([$plain, $taggable]); $this->assertTrue($stack->tags(['tag'])->clear()); + $plain->unused(); } public function testClearFlushesEveryTaggableLayerAndAggregatesFalseResults(): void { $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = m::mock(TaggedCache::class); - $secondTaggedCache = m::mock(TaggedCache::class); - $firstTagSet = m::mock(TagSet::class); - $secondTagSet = m::mock(TagSet::class); - - $firstTaggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($firstTaggedCache); - $secondTaggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($secondTaggedCache); - $firstTaggedCache->shouldReceive('getTags')->once()->andReturn($firstTagSet); - $secondTaggedCache->shouldReceive('getTags')->once()->andReturn($secondTagSet); - $firstTagSet->shouldReceive('flush')->once()->andReturnFalse(); - $secondTagSet->shouldReceive('flush')->once()->andReturnTrue(); + $firstTaggedCache = Double::for(TaggedCache::class); + $secondTaggedCache = Double::for(TaggedCache::class); + $firstTagSet = Double::for(TagSet::class); + $secondTagSet = Double::for(TagSet::class); + + $firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache); + $secondTaggable->expects('tags')->with(['tag'])->returns($secondTaggedCache); + $firstTaggedCache->expects('getTags')->returns($firstTagSet); + $secondTaggedCache->expects('getTags')->returns($secondTagSet); + $firstTagSet->expects('flush')->returns(false); + $secondTagSet->expects('flush')->returns(true); $stack = new StackStore([$firstTaggable, $secondTaggable]); @@ -731,17 +746,17 @@ public function testTagSetFlushAttemptsEveryLayerAndPreservesTheFirstException() $firstException = new RuntimeException('first tag flush failed'); $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = m::mock(TaggedCache::class); - $secondTaggedCache = m::mock(TaggedCache::class); - $firstTagSet = m::mock(TagSet::class); - $secondTagSet = m::mock(TagSet::class); - - $firstTaggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($firstTaggedCache); - $secondTaggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($secondTaggedCache); - $firstTaggedCache->shouldReceive('getTags')->once()->andReturn($firstTagSet); - $secondTaggedCache->shouldReceive('getTags')->once()->andReturn($secondTagSet); - $firstTagSet->shouldReceive('flush')->once()->andThrow($firstException); - $secondTagSet->shouldReceive('flush')->once()->andThrow(new RuntimeException('second tag flush failed')); + $firstTaggedCache = Double::for(TaggedCache::class); + $secondTaggedCache = Double::for(TaggedCache::class); + $firstTagSet = Double::for(TagSet::class); + $secondTagSet = Double::for(TagSet::class); + + $firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache); + $secondTaggable->expects('tags')->with(['tag'])->returns($secondTaggedCache); + $firstTaggedCache->expects('getTags')->returns($firstTagSet); + $secondTaggedCache->expects('getTags')->returns($secondTagSet); + $firstTagSet->expects('flush')->throws($firstException); + $secondTagSet->expects('flush')->throws(new RuntimeException('second tag flush failed')); try { (new StackStore([$firstTaggable, $secondTaggable]))->tags(['tag'])->getTags()->flush(); @@ -761,13 +776,13 @@ public function testTagSetFlushStopsImmediatelyOnCancellation(bool $cleanupThrow } $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = m::mock(TaggedCache::class); - $firstTagSet = m::mock(TagSet::class); + $firstTaggedCache = Double::for(TaggedCache::class); + $firstTagSet = Double::for(TagSet::class); - $firstTaggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($firstTaggedCache); - $firstTaggedCache->shouldReceive('getTags')->once()->andReturn($firstTagSet); - $firstTagSet->shouldReceive('flush')->once()->andThrow($cancellation); - $secondTaggable->shouldNotReceive('tags'); + $firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache); + $firstTaggedCache->expects('getTags')->returns($firstTagSet); + $firstTagSet->expects('flush')->throws($cancellation); + $secondTaggable->expects('tags')->never(); try { (new StackStore([$firstTaggable, $secondTaggable]))->tags(['tag'])->getTags()->flush(); @@ -782,16 +797,16 @@ public function testClearDispatchesFailureEventWithExactTagSetException(): void $exception = new RuntimeException('tag flush failed'); $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = m::mock(TaggedCache::class); - $secondTaggedCache = m::mock(TaggedCache::class); - $firstTagSet = m::mock(TagSet::class); - $secondTagSet = m::mock(TagSet::class); - $firstTaggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($firstTaggedCache); - $secondTaggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($secondTaggedCache); - $firstTaggedCache->shouldReceive('getTags')->once()->andReturn($firstTagSet); - $secondTaggedCache->shouldReceive('getTags')->once()->andReturn($secondTagSet); - $firstTagSet->shouldReceive('flush')->once()->andThrow($exception); - $secondTagSet->shouldReceive('flush')->once()->andThrow(new RuntimeException('second tag flush failed')); + $firstTaggedCache = Double::for(TaggedCache::class); + $secondTaggedCache = Double::for(TaggedCache::class); + $firstTagSet = Double::for(TagSet::class); + $secondTagSet = Double::for(TagSet::class); + $firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache); + $secondTaggable->expects('tags')->with(['tag'])->returns($secondTaggedCache); + $firstTaggedCache->expects('getTags')->returns($firstTagSet); + $secondTaggedCache->expects('getTags')->returns($secondTagSet); + $firstTagSet->expects('flush')->throws($exception); + $secondTagSet->expects('flush')->throws(new RuntimeException('second tag flush failed')); $captured = []; $cache = (new Repository(new StackStore([$firstTaggable, $secondTaggable]), ['store' => 'stack']))->tags(['tag']); @@ -818,12 +833,12 @@ public function testClearCancellationSkipsFailureEventAndRemainingTaggableLayers } $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = m::mock(TaggedCache::class); - $firstTagSet = m::mock(TagSet::class); - $firstTaggable->shouldReceive('tags')->once()->with(['tag'])->andReturn($firstTaggedCache); - $firstTaggedCache->shouldReceive('getTags')->once()->andReturn($firstTagSet); - $firstTagSet->shouldReceive('flush')->once()->andThrow($cancellation); - $secondTaggable->shouldNotReceive('tags'); + $firstTaggedCache = Double::for(TaggedCache::class); + $firstTagSet = Double::for(TagSet::class); + $firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache); + $firstTaggedCache->expects('getTags')->returns($firstTagSet); + $firstTagSet->expects('flush')->throws($cancellation); + $secondTaggable->expects('tags')->never(); $captured = []; $cache = (new Repository(new StackStore([$firstTaggable, $secondTaggable]), ['store' => 'stack']))->tags(['tag']); @@ -839,35 +854,47 @@ public function testClearCancellationSkipsFailureEventAndRemainingTaggableLayers $this->assertSame([CacheFlushing::class], array_map(get_class(...), $captured)); } - private function anyModeTaggableStore(): TaggableStore|m\MockInterface + /** + * Create an any-mode taggable store. + */ + private function anyModeTaggableStore(): TaggableStore&DoubleInterface { - $store = m::mock(TaggableStore::class); - $store->shouldReceive('supportsTags')->byDefault()->andReturnTrue(); - $store->shouldReceive('getTagMode')->byDefault()->andReturn(TagMode::Any); + $store = Double::for(TaggableStore::class); + $store->allows('supportsTags')->returns(true); + $store->allows('getTagMode')->returns(TagMode::Any); return $store; } - private function allModeTaggableStore(): TaggableStore|m\MockInterface + /** + * Create an all-mode taggable store. + */ + private function allModeTaggableStore(): TaggableStore&DoubleInterface { - $store = m::mock(TaggableStore::class); - $store->shouldReceive('supportsTags')->byDefault()->andReturnTrue(); - $store->shouldReceive('getTagMode')->byDefault()->andReturn(TagMode::All); + $store = Double::for(TaggableStore::class); + $store->allows('supportsTags')->returns(true); + $store->allows('getTagMode')->returns(TagMode::All); return $store; } - private function nonTaggableStore(): Store|m\MockInterface + /** + * Create a store without tag support. + */ + private function nonTaggableStore(): Store&DoubleInterface { - return m::mock(Store::class); + return Double::for(Store::class); } - private function capturingDispatcher(array &$captured): Dispatcher|m\MockInterface + /** + * Create a dispatcher that records emitted events. + */ + private function capturingDispatcher(array &$captured): Dispatcher&DoubleInterface { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $events->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); diff --git a/tests/Cache/CacheStackStoreTest.php b/tests/Cache/CacheStackStoreTest.php index f5f23204e5..b42df6259a 100644 --- a/tests/Cache/CacheStackStoreTest.php +++ b/tests/Cache/CacheStackStoreTest.php @@ -18,8 +18,10 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -30,11 +32,11 @@ class CacheStackStoreTest extends TestCase { - /** @var MockInterface|SwooleStore */ - private SwooleStore $swoole; + use VerifiesDoubles; - /** @var MockInterface|RedisStore */ - private RedisStore $redis; + private SwooleStore&DoubleInterface $swoole; + + private RedisStore&DoubleInterface $redis; private StackStore $store; @@ -55,21 +57,21 @@ public function testRetrieveItemFromStoreStacked(): void $expiration = CarbonImmutable::now()->getTimestamp() + $ttl; $record = compact('value', 'expiration'); - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(null); - $this->redis->shouldReceive('get')->once()->with($key)->andReturn($record); - $this->swoole->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); + $this->swoole->expects('get')->with($key)->returns(null); + $this->redis->expects('get')->with($key)->returns($record); + $this->swoole->expects('put')->with($key, $record, $ttl)->returns(true); $this->assertSame($value, $this->store->get($key)); } public function testAuthoritativeReadUsesBottomLayerWithoutRepairingUpperLayer(): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); - $bottom->shouldReceive('get')->once()->with('key')->andReturn(['value' => 'fresh']); - $top->shouldNotReceive('get'); - $top->shouldNotReceive('put'); - $top->shouldNotReceive('forever'); + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); + $bottom->expects('get')->with('key')->returns(['value' => 'fresh']); + $top->expects('get')->never(); + $top->expects('put')->never(); + $top->expects('forever')->never(); $store = new StackStore([$top, $bottom]); @@ -112,8 +114,8 @@ public function testFlexibleSkipsRefreshWhenBottomMarkerIsNewerThanUpperLayer(): #[DataProvider('authoritativeRecordProvider')] public function testAuthoritativeReadHandlesSingleLayerRecords(mixed $record, mixed $expected): void { - $store = m::mock(ArrayStore::class); - $store->shouldReceive('get')->once()->with('key')->andReturn($record); + $store = Double::for(ArrayStore::class); + $store->expects('get')->with('key')->returns($record); $this->assertSame($expected, (new StackStore([$store]))->getAuthoritativeRaw('key')); } @@ -131,14 +133,14 @@ public static function authoritativeRecordProvider(): array public function testAuthoritativeReadRecursesThroughBottomStack(): void { - $outerTop = m::mock(ArrayStore::class); - $innerTop = m::mock(ArrayStore::class); - $innerBottom = m::mock(ArrayStore::class); - $innerBottom->shouldReceive('get')->once()->with('key')->andReturn([ + $outerTop = Double::for(ArrayStore::class); + $innerTop = Double::for(ArrayStore::class); + $innerBottom = Double::for(ArrayStore::class); + $innerBottom->expects('get')->with('key')->returns([ 'value' => ['value' => 'fresh'], ]); - $outerTop->shouldNotReceive('get'); - $innerTop->shouldNotReceive('get'); + $outerTop->expects('get')->never(); + $innerTop->expects('get')->never(); $store = new StackStore([ $outerTop, @@ -150,14 +152,14 @@ public function testAuthoritativeReadRecursesThroughBottomStack(): void public function testAuthoritativeReadRecursesThroughBottomFailoverStore(): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); - $bottom->shouldReceive('get')->once()->with('key')->andReturn(['value' => 'fresh']); - $top->shouldNotReceive('get'); + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); + $bottom->expects('get')->with('key')->returns(['value' => 'fresh']); + $top->expects('get')->never(); - $cache = m::mock(CacheManager::class); - $cache->shouldReceive('store')->once()->with('bottom')->andReturn(new Repository($bottom)); - $failover = new FailoverStore($cache, m::mock(Dispatcher::class), ['bottom']); + $cache = Double::for(CacheManager::class); + $cache->expects('store')->with('bottom')->returns(new Repository($bottom)); + $failover = new FailoverStore($cache, Double::for(Dispatcher::class), ['bottom']); $this->assertSame('fresh', (new StackStore([$top, $failover]))->getAuthoritativeRaw('key')); } @@ -168,9 +170,9 @@ public function testReadReturnsLowerValueWhenUpperRepairFails(): void $record = ['value' => 'bar']; - $this->swoole->shouldReceive('get')->once()->with('foo')->andReturnNull(); - $this->redis->shouldReceive('get')->once()->with('foo')->andReturn($record); - $this->swoole->shouldReceive('forever')->once()->with('foo', $record)->andReturnFalse(); + $this->swoole->expects('get')->with('foo')->returns(null); + $this->redis->expects('get')->with('foo')->returns($record); + $this->swoole->expects('forever')->with('foo', $record)->returns(false); $this->assertSame('bar', $this->store->get('foo')); } @@ -179,8 +181,8 @@ public function testMalformedLowerRecordRemainsAMiss(): void { $this->createStores(); - $this->swoole->shouldReceive('get')->once()->with('foo')->andReturnNull(); - $this->redis->shouldReceive('get')->once()->with('foo')->andReturn(['expiration' => 123]); + $this->swoole->expects('get')->with('foo')->returns(null); + $this->redis->expects('get')->with('foo')->returns(['expiration' => 123]); $this->assertNull($this->store->get('foo')); } @@ -192,9 +194,9 @@ public function testReadRepairExceptionPropagates(): void $exception = new RuntimeException('repair failed'); $record = ['value' => 'bar']; - $this->swoole->shouldReceive('get')->once()->with('foo')->andReturnNull(); - $this->redis->shouldReceive('get')->once()->with('foo')->andReturn($record); - $this->swoole->shouldReceive('forever')->once()->with('foo', $record)->andThrow($exception); + $this->swoole->expects('get')->with('foo')->returns(null); + $this->redis->expects('get')->with('foo')->returns($record); + $this->swoole->expects('forever')->with('foo', $record)->throws($exception); try { $this->store->get('foo'); @@ -206,16 +208,16 @@ public function testReadRepairExceptionPropagates(): void public function testThreeLayerReadContinuesRepairAfterInnerFailure(): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $record = ['value' => 'bar']; - $top->shouldReceive('get')->once()->with('foo')->andReturnNull(); - $middle->shouldReceive('get')->once()->with('foo')->andReturnNull(); - $bottom->shouldReceive('get')->once()->with('foo')->andReturn($record); - $middle->shouldReceive('forever')->once()->with('foo', $record)->andReturnFalse(); - $top->shouldReceive('forever')->once()->with('foo', $record)->andReturnTrue(); + $top->expects('get')->with('foo')->returns(null); + $middle->expects('get')->with('foo')->returns(null); + $bottom->expects('get')->with('foo')->returns($record); + $middle->expects('forever')->with('foo', $record)->returns(false); + $top->expects('forever')->with('foo', $record)->returns(true); $this->assertSame('bar', (new StackStore([$top, $middle, $bottom]))->get('foo')); } @@ -240,9 +242,9 @@ public function testPutWithCorrectTTL(): void CarbonImmutable::setTestNow(CarbonImmutable::now()->addSeconds(50)); - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(null); - $this->redis->shouldReceive('get')->once()->with($key)->andReturn($record); - $this->swoole->shouldReceive('put')->once()->with($key, $record, $ttl - 50)->andReturn(true); + $this->swoole->expects('get')->with($key)->returns(null); + $this->redis->expects('get')->with($key)->returns($record); + $this->swoole->expects('put')->with($key, $record, $ttl - 50)->returns(true); $this->assertSame($value, $this->store->get($key)); } @@ -257,9 +259,11 @@ public function testAvoidRedundantCall(): void $expiration = CarbonImmutable::now()->getTimestamp() + $ttl; $record = compact('value', 'expiration'); - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn($record); + $this->swoole->expects('get')->with($key)->returns($record); $this->assertSame($value, $this->store->get($key)); + + $this->redis->unused(); } public function testMissingItemsReturnNull(): void @@ -268,8 +272,8 @@ public function testMissingItemsReturnNull(): void $key = 'foo'; - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(null); - $this->redis->shouldReceive('get')->once()->with($key)->andReturn(null); + $this->swoole->expects('get')->with($key)->returns(null); + $this->redis->expects('get')->with($key)->returns(null); $this->assertNull($this->store->get($key)); } @@ -309,8 +313,8 @@ public function testPutItemToStoreStacked(): void $expiration = CarbonImmutable::now()->getTimestamp() + $ttl; $record = compact('value', 'expiration'); - $this->swoole->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); - $this->redis->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); + $this->swoole->expects('put')->with($key, $record, $ttl)->returns(true); + $this->redis->expects('put')->with($key, $record, $ttl)->returns(true); $this->assertTrue($this->store->put($key, $value, $ttl)); } @@ -325,9 +329,11 @@ public function testPutItemToStoreFailed(): void $expiration = CarbonImmutable::now()->getTimestamp() + $ttl; $record = compact('value', 'expiration'); - $this->swoole->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(false); + $this->swoole->expects('put')->with($key, $record, $ttl)->returns(false); $this->assertFalse($this->store->put($key, $value, $ttl)); + + $this->redis->unused(); } public function testPutItemToStoreFailedAndRollback(): void @@ -340,25 +346,34 @@ public function testPutItemToStoreFailedAndRollback(): void $expiration = CarbonImmutable::now()->getTimestamp() + $ttl; $record = compact('value', 'expiration'); - $this->swoole->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); - $this->redis->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(false); - $this->swoole->shouldReceive('forget')->once()->with($key)->andReturn(true); + $this->swoole->expects('put')->with($key, $record, $ttl)->returns(true); + $this->redis->expects('put')->with($key, $record, $ttl)->returns(false); + $this->swoole->expects('forget')->with($key)->returns(true); $this->assertFalse($this->store->put($key, $value, $ttl)); } public function testPutCompensatesEarlierLayerWhenLowerLayerThrows(): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $sequence = []; + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $exception = new RuntimeException('write failed'); - $top->shouldReceive('put')->once()->andReturnTrue(); - $middle->shouldReceive('put')->once()->andThrow($exception); - $bottom->shouldNotReceive('put'); - $middle->shouldReceive('forget')->once()->with('foo')->globally()->ordered()->andReturnTrue(); - $top->shouldReceive('forget')->once()->with('foo')->globally()->ordered()->andReturnTrue(); + $top->expects('put')->returns(true); + $middle->expects('put')->throws($exception); + $bottom->expects('put')->never(); + $middle->expects('forget')->with('foo')->resolves(function () use (&$sequence): bool { + $sequence[] = 'middle'; + + return true; + }); + $top->expects('forget')->with('foo')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top'; + + return true; + }); try { (new StackStore([$top, $middle, $bottom]))->put('foo', 'bar', 60); @@ -366,45 +381,58 @@ public function testPutCompensatesEarlierLayerWhenLowerLayerThrows(): void } catch (RuntimeException $throwable) { $this->assertSame($exception, $throwable); } + + $this->assertSame(['middle', 'top'], $sequence); } public function testPutCompensatesCompletedLayersInReverseOrder(): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $sequence = []; + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); + + $top->expects('put')->returns(true); + $middle->expects('put')->returns(true); + $bottom->expects('put')->returns(false); + $middle->expects('forget')->with('foo')->resolves(function () use (&$sequence): bool { + $sequence[] = 'middle'; + + return true; + }); + $top->expects('forget')->with('foo')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top'; - $top->shouldReceive('put')->once()->andReturnTrue(); - $middle->shouldReceive('put')->once()->andReturnTrue(); - $bottom->shouldReceive('put')->once()->andReturnFalse(); - $middle->shouldReceive('forget')->once()->with('foo')->globally()->ordered()->andReturnTrue(); - $top->shouldReceive('forget')->once()->with('foo')->globally()->ordered()->andReturnTrue(); + return true; + }); $this->assertFalse((new StackStore([$top, $middle, $bottom]))->put('foo', 'bar', 60)); + + $this->assertSame(['middle', 'top'], $sequence); } public function testPutPreservesFalseResultWhenCompensationThrows(): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); - $top->shouldReceive('put')->once()->andReturnTrue(); - $bottom->shouldReceive('put')->once()->andReturnFalse(); - $top->shouldReceive('forget')->once()->with('foo')->andThrow(new RuntimeException('cleanup failed')); + $top->expects('put')->returns(true); + $bottom->expects('put')->returns(false); + $top->expects('forget')->with('foo')->throws(new RuntimeException('cleanup failed')); $this->assertFalse((new StackStore([$top, $bottom]))->put('foo', 'bar', 60)); } public function testPutPreservesWriteFailureWhenCompensationAlsoThrows(): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $exception = new RuntimeException('write failed'); - $top->shouldReceive('put')->once()->andReturnTrue(); - $bottom->shouldReceive('put')->once()->andThrow($exception); - $bottom->shouldReceive('forget')->once()->with('foo')->andThrow(new RuntimeException('current cleanup failed')); - $top->shouldReceive('forget')->once()->with('foo')->andThrow(new RuntimeException('cleanup failed')); + $top->expects('put')->returns(true); + $bottom->expects('put')->throws($exception); + $bottom->expects('forget')->with('foo')->throws(new RuntimeException('current cleanup failed')); + $top->expects('forget')->with('foo')->throws(new RuntimeException('cleanup failed')); try { (new StackStore([$top, $bottom]))->put('foo', 'bar', 60); @@ -416,13 +444,13 @@ public function testPutPreservesWriteFailureWhenCompensationAlsoThrows(): void public function testPutCompensatesLayerWhoseWriteThrows(): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $exception = new RuntimeException('write failed'); - $top->shouldReceive('put')->once()->andThrow($exception); - $top->shouldReceive('forget')->once()->with('foo')->andReturnTrue(); - $bottom->shouldNotReceive('put'); + $top->expects('put')->throws($exception); + $top->expects('forget')->with('foo')->returns(true); + $bottom->expects('put')->never(); try { (new StackStore([$top, $bottom]))->put('foo', 'bar', 60); @@ -494,18 +522,27 @@ public function put(string $key, mixed $value, int $seconds): bool #[TestWith([true])] public function testPutPreservesOriginalCancellationAndCompletesCompensation(bool $cleanupThrows): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $sequence = []; + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $cancellation = new CanceledException('write canceled'); if ($cleanupThrows) { $cancellation = new RuntimeException('Write cleanup failed.', previous: $cancellation); } $cleanupCancellation = new CanceledException('cleanup canceled'); - $top->shouldReceive('put')->once()->andReturnTrue(); - $bottom->shouldReceive('put')->once()->andThrow($cancellation); - $bottom->shouldReceive('forget')->once()->with('foo')->globally()->ordered()->andThrow($cleanupCancellation); - $top->shouldReceive('forget')->once()->with('foo')->globally()->ordered()->andReturnTrue(); + $top->expects('put')->returns(true); + $bottom->expects('put')->throws($cancellation); + $bottom->expects('forget')->with('foo')->resolves(function () use (&$sequence, $cleanupCancellation): never { + $sequence[] = 'bottom'; + + throw $cleanupCancellation; + }); + $top->expects('forget')->with('foo')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top'; + + return true; + }); try { (new StackStore([$top, $bottom]))->put('foo', 'bar', 60); @@ -513,23 +550,34 @@ public function testPutPreservesOriginalCancellationAndCompletesCompensation(boo } catch (Throwable $exception) { $this->assertSame($cancellation, $exception); } + + $this->assertSame(['bottom', 'top'], $sequence); } #[TestWith([false])] #[TestWith([true])] public function testPutCleanupCancellationSupersedesOrdinaryWriteFailure(bool $cleanupThrows): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $sequence = []; + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $cleanupCancellation = new CanceledException('cleanup canceled'); if ($cleanupThrows) { $cleanupCancellation = new RuntimeException('Release cleanup failed.', previous: $cleanupCancellation); } - $top->shouldReceive('put')->once()->andReturnTrue(); - $bottom->shouldReceive('put')->once()->andThrow(new RuntimeException('write failed')); - $bottom->shouldReceive('forget')->once()->with('foo')->globally()->ordered()->andThrow($cleanupCancellation); - $top->shouldReceive('forget')->once()->with('foo')->globally()->ordered()->andReturnTrue(); + $top->expects('put')->returns(true); + $bottom->expects('put')->throws(new RuntimeException('write failed')); + $bottom->expects('forget')->with('foo')->resolves(function () use (&$sequence, $cleanupCancellation): never { + $sequence[] = 'bottom'; + + throw $cleanupCancellation; + }); + $top->expects('forget')->with('foo')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top'; + + return true; + }); try { (new StackStore([$top, $bottom]))->put('foo', 'bar', 60); @@ -537,22 +585,24 @@ public function testPutCleanupCancellationSupersedesOrdinaryWriteFailure(bool $c } catch (Throwable $exception) { $this->assertSame($cleanupCancellation, $exception); } + + $this->assertSame(['bottom', 'top'], $sequence); } #[TestWith([false])] #[TestWith([true])] public function testPutCleanupCancellationSupersedesFalseWriteResult(bool $cleanupThrows): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $cleanupCancellation = new CanceledException('cleanup canceled'); if ($cleanupThrows) { $cleanupCancellation = new RuntimeException('Release cleanup failed.', previous: $cleanupCancellation); } - $top->shouldReceive('put')->once()->andReturnTrue(); - $bottom->shouldReceive('put')->once()->andReturnFalse(); - $top->shouldReceive('forget')->once()->with('foo')->andThrow($cleanupCancellation); + $top->expects('put')->returns(true); + $bottom->expects('put')->returns(false); + $top->expects('forget')->with('foo')->throws($cleanupCancellation); try { (new StackStore([$top, $bottom]))->put('foo', 'bar', 60); @@ -566,20 +616,21 @@ public function testMany(): void { $this->createStores(); - $this->swoole->shouldReceive('many')->once()->with(['foo', 'bar'])->andReturn([ + $this->swoole->expects('many')->with(['foo', 'bar'])->returns([ 'foo' => ['value' => 'bar'], 'bar' => ['value' => 'baz'], ]); - $this->redis->shouldNotReceive('many'); + $this->redis->expects('many')->never(); $this->assertEquals(['foo' => 'bar', 'bar' => 'baz'], $this->store->many(['foo', 'bar'])); } public function testManyReadsEachLayerOnceAndRestoresLowerHitsWithBatchedWrites(): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $sequence = []; + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $expiration = CarbonImmutable::now()->getTimestamp() + 100; $shorterExpiration = CarbonImmutable::now()->getTimestamp() + 50; $middleRecord = ['value' => 'middle', 'expiration' => $expiration]; @@ -589,7 +640,7 @@ public function testManyReadsEachLayerOnceAndRestoresLowerHitsWithBatchedWrites( CarbonImmutable::setTestNow(CarbonImmutable::now()->addSeconds(30)); - $top->shouldReceive('many')->once()->with(['top', 'middle', 'bottom', 'shorter', 'forever', 'missing', 'malformed'])->andReturn([ + $top->expects('many')->with(['top', 'middle', 'bottom', 'shorter', 'forever', 'missing', 'malformed'])->returns([ 'top' => ['value' => 'top'], 'middle' => null, 'bottom' => null, @@ -598,7 +649,7 @@ public function testManyReadsEachLayerOnceAndRestoresLowerHitsWithBatchedWrites( 'missing' => null, 'malformed' => null, ]); - $middle->shouldReceive('many')->once()->with(['middle', 'bottom', 'shorter', 'forever', 'missing', 'malformed'])->andReturn([ + $middle->expects('many')->with(['middle', 'bottom', 'shorter', 'forever', 'missing', 'malformed'])->returns([ 'middle' => $middleRecord, 'bottom' => null, 'shorter' => null, @@ -606,19 +657,27 @@ public function testManyReadsEachLayerOnceAndRestoresLowerHitsWithBatchedWrites( 'missing' => null, 'malformed' => ['expiration' => 123], ]); - $bottom->shouldReceive('many')->once()->with(['bottom', 'shorter', 'forever', 'missing'])->andReturn([ + $bottom->expects('many')->with(['bottom', 'shorter', 'forever', 'missing'])->returns([ 'bottom' => $bottomRecord, 'shorter' => $shorterRecord, 'forever' => $foreverRecord, 'missing' => null, ]); - $middle->shouldReceive('putMany')->once()->with(['bottom' => $bottomRecord], 70)->globally()->ordered()->andReturnTrue(); - $middle->shouldReceive('putMany')->once()->with(['shorter' => $shorterRecord], 20)->andReturnTrue(); - $middle->shouldReceive('forever')->once()->with('forever', $foreverRecord)->andReturnTrue(); - $top->shouldReceive('putMany')->once()->with(['middle' => $middleRecord, 'bottom' => $bottomRecord], 70)->globally()->ordered()->andReturnTrue(); - $top->shouldReceive('putMany')->once()->with(['shorter' => $shorterRecord], 20)->andReturnTrue(); - $top->shouldReceive('forever')->once()->with('forever', $foreverRecord)->andReturnTrue(); + $middle->expects('putMany')->with(['bottom' => $bottomRecord], 70)->resolves(function () use (&$sequence): bool { + $sequence[] = 'middle'; + + return true; + }); + $middle->expects('putMany')->with(['shorter' => $shorterRecord], 20)->returns(true); + $middle->expects('forever')->with('forever', $foreverRecord)->returns(true); + $top->expects('putMany')->with(['middle' => $middleRecord, 'bottom' => $bottomRecord], 70)->resolves(function () use (&$sequence): bool { + $sequence[] = 'top'; + + return true; + }); + $top->expects('putMany')->with(['shorter' => $shorterRecord], 20)->returns(true); + $top->expects('forever')->with('forever', $foreverRecord)->returns(true); $this->assertSame([ 'top' => 'top', @@ -629,13 +688,15 @@ public function testManyReadsEachLayerOnceAndRestoresLowerHitsWithBatchedWrites( 'missing' => null, 'malformed' => null, ], (new StackStore([$top, $middle, $bottom]))->many(['top', 'middle', 'bottom', 'shorter', 'forever', 'missing', 'malformed'])); + + $this->assertSame(['middle', 'top'], $sequence); } public function testManyMeasuresRemainingTtlBeforeEachRestoreAndSkipsRecordsThatExpired(): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $expiringRecord = ['value' => 'expiring', 'expiration' => CarbonImmutable::now()->getTimestamp() + 1]; $bottomRecord = ['value' => 'bottom', 'expiration' => CarbonImmutable::now()->getTimestamp() + 100]; $advance = static function (int $seconds, mixed $result): Closure { @@ -646,12 +707,12 @@ public function testManyMeasuresRemainingTtlBeforeEachRestoreAndSkipsRecordsThat }; }; - $top->shouldReceive('many')->once()->with(['expiring', 'bottom'])->andReturn(['expiring' => null, 'bottom' => null]); - $middle->shouldReceive('many')->once()->with(['expiring', 'bottom'])->andReturn(['expiring' => $expiringRecord, 'bottom' => null]); - $bottom->shouldReceive('many')->once()->with(['bottom'])->andReturnUsing($advance(5, ['bottom' => $bottomRecord])); - $middle->shouldReceive('putMany')->once()->with(['bottom' => $bottomRecord], 95)->andReturnUsing($advance(10, true)); - $top->shouldReceive('putMany')->once()->with(['bottom' => $bottomRecord], 85)->andReturnTrue(); - $top->shouldNotReceive('forever'); + $top->expects('many')->with(['expiring', 'bottom'])->returns(['expiring' => null, 'bottom' => null]); + $middle->expects('many')->with(['expiring', 'bottom'])->returns(['expiring' => $expiringRecord, 'bottom' => null]); + $bottom->expects('many')->with(['bottom'])->resolves($advance(5, ['bottom' => $bottomRecord])); + $middle->expects('putMany')->with(['bottom' => $bottomRecord], 95)->resolves($advance(10, true)); + $top->expects('putMany')->with(['bottom' => $bottomRecord], 85)->returns(true); + $top->expects('forever')->never(); $this->assertSame( ['expiring' => 'expiring', 'bottom' => 'bottom'], @@ -665,14 +726,14 @@ public function testReadForgetsUpperLayerInsteadOfRestoringRecordThatExpiredDuri $record = ['value' => 'bar', 'expiration' => CarbonImmutable::now()->getTimestamp() + 1]; - $this->swoole->shouldReceive('get')->once()->with('foo')->andReturnNull(); - $this->redis->shouldReceive('get')->once()->with('foo')->andReturnUsing(function () use ($record): array { + $this->swoole->expects('get')->with('foo')->returns(null); + $this->redis->expects('get')->with('foo')->resolves(function () use ($record): array { CarbonImmutable::setTestNow(CarbonImmutable::now()->addSeconds(2)); return $record; }); - $this->swoole->shouldReceive('forget')->once()->with('foo')->andReturnTrue(); - $this->swoole->shouldNotReceive('put'); + $this->swoole->expects('forget')->with('foo')->returns(true); + $this->swoole->expects('put')->never(); $this->assertSame('bar', $this->store->get('foo')); } @@ -688,8 +749,8 @@ public function testPutMany(): void 'bar' => ['value' => 'baz', 'expiration' => $expiration], ]; - $this->swoole->shouldReceive('putMany')->once()->with($records, $ttl)->andReturn(true); - $this->redis->shouldReceive('putMany')->once()->with($records, $ttl)->andReturn(true); + $this->swoole->expects('putMany')->with($records, $ttl)->returns(true); + $this->redis->expects('putMany')->with($records, $ttl)->returns(true); $this->assertTrue($this->store->putMany(['foo' => 'bar', 'bar' => 'baz'], $ttl)); } @@ -701,12 +762,12 @@ public function testPutManyStartsEachLayersExpirationWhenThatLayerIsWritten(): v $ttl = 100; $now = CarbonImmutable::now()->getTimestamp(); - $this->swoole->shouldReceive('putMany')->once()->with(['foo' => ['value' => 'bar', 'expiration' => $now + $ttl]], $ttl)->andReturnUsing(function (): bool { + $this->swoole->expects('putMany')->with(['foo' => ['value' => 'bar', 'expiration' => $now + $ttl]], $ttl)->resolves(function (): bool { CarbonImmutable::setTestNow(CarbonImmutable::now()->addSeconds(5)); return true; }); - $this->redis->shouldReceive('putMany')->once()->with(['foo' => ['value' => 'bar', 'expiration' => $now + 5 + $ttl]], $ttl)->andReturnTrue(); + $this->redis->expects('putMany')->with(['foo' => ['value' => 'bar', 'expiration' => $now + 5 + $ttl]], $ttl)->returns(true); $this->assertTrue($this->store->putMany(['foo' => 'bar'], $ttl)); } @@ -716,23 +777,45 @@ public function testPutManyReturnsTrueForEmptyInput(): void $this->createStores(); $this->assertTrue($this->store->putMany([], 100)); + + $this->swoole->unused(); + $this->redis->unused(); } public function testPutManyFailureForgetsTheBatchFromTheFailedAndCompletedLayersDeepestFirst(): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $sequence = []; + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); - $top->shouldReceive('putMany')->once()->andReturnTrue(); - $middle->shouldReceive('putMany')->once()->andReturnFalse(); - $bottom->shouldNotReceive('putMany'); - $middle->shouldReceive('forget')->once()->with('first')->globally()->ordered()->andReturnTrue(); - $middle->shouldReceive('forget')->once()->with('second')->globally()->ordered()->andReturnTrue(); - $top->shouldReceive('forget')->once()->with('first')->globally()->ordered()->andReturnTrue(); - $top->shouldReceive('forget')->once()->with('second')->globally()->ordered()->andReturnTrue(); + $top->expects('putMany')->returns(true); + $middle->expects('putMany')->returns(false); + $bottom->expects('putMany')->never(); + $middle->expects('forget')->with('first')->resolves(function () use (&$sequence): bool { + $sequence[] = 'middle:first'; + + return true; + }); + $middle->expects('forget')->with('second')->resolves(function () use (&$sequence): bool { + $sequence[] = 'middle:second'; + + return true; + }); + $top->expects('forget')->with('first')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top:first'; + + return true; + }); + $top->expects('forget')->with('second')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top:second'; + + return true; + }); $this->assertFalse((new StackStore([$top, $middle, $bottom]))->putMany(['first' => 'one', 'second' => 'two'], 60)); + + $this->assertSame(['middle:first', 'middle:second', 'top:first', 'top:second'], $sequence); } public function testPutManyForgetsKeysALayerStoredBeforeThrowing(): void @@ -772,21 +855,42 @@ public function putMany(array $values, int $seconds): bool #[TestWith([true])] public function testPutManyCleanupContinuesAfterCancellationStopsAtOrdinaryFailureAndKeepsCancellation(bool $cleanupThrows): void { - $top = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $sequence = []; + $top = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $cleanupCancellation = new CanceledException('cleanup canceled'); if ($cleanupThrows) { $cleanupCancellation = new RuntimeException('Release cleanup failed.', previous: $cleanupCancellation); } - $top->shouldReceive('putMany')->once()->andReturnTrue(); - $bottom->shouldReceive('putMany')->once()->andThrow(new RuntimeException('write failed')); - $bottom->shouldReceive('forget')->once()->with('first')->globally()->ordered()->andThrow($cleanupCancellation); - $bottom->shouldReceive('forget')->once()->with('second')->globally()->ordered()->andThrow(new RuntimeException('cleanup failed')); - $bottom->shouldNotReceive('forget')->with('third'); - $top->shouldReceive('forget')->once()->with('first')->globally()->ordered()->andReturnTrue(); - $top->shouldReceive('forget')->once()->with('second')->globally()->ordered()->andReturnTrue(); - $top->shouldReceive('forget')->once()->with('third')->globally()->ordered()->andReturnTrue(); + $top->expects('putMany')->returns(true); + $bottom->expects('putMany')->throws(new RuntimeException('write failed')); + $bottom->expects('forget')->with('first')->resolves(function () use (&$sequence, $cleanupCancellation): never { + $sequence[] = 'bottom:first'; + + throw $cleanupCancellation; + }); + $bottom->expects('forget')->with('second')->resolves(function () use (&$sequence): never { + $sequence[] = 'bottom:second'; + + throw new RuntimeException('cleanup failed'); + }); + $bottom->expects('forget')->never()->with('third'); + $top->expects('forget')->with('first')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top:first'; + + return true; + }); + $top->expects('forget')->with('second')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top:second'; + + return true; + }); + $top->expects('forget')->with('third')->resolves(function () use (&$sequence): bool { + $sequence[] = 'top:third'; + + return true; + }); try { (new StackStore([$top, $bottom]))->putMany(['first' => 'one', 'second' => 'two', 'third' => 'three'], 60); @@ -794,13 +898,15 @@ public function testPutManyCleanupContinuesAfterCancellationStopsAtOrdinaryFailu } catch (Throwable $exception) { $this->assertSame($cleanupCancellation, $exception); } + + $this->assertSame(['bottom:first', 'bottom:second', 'top:first', 'top:second', 'top:third'], $sequence); } #[DataProvider('proxyPutManyTtlProvider')] public function testProxyPutManyAppliesLayerTtl(?int $layerTtl, int $requestedTtl, int $expectedTtl): void { - $store = m::mock(ArrayStore::class); - $store->shouldReceive('putMany')->once()->with(['key' => 'value'], $expectedTtl)->andReturnTrue(); + $store = Double::for(ArrayStore::class); + $store->expects('putMany')->with(['key' => 'value'], $expectedTtl)->returns(true); $proxy = new StackStoreProxy($store, $layerTtl); @@ -819,8 +925,8 @@ public static function proxyPutManyTtlProvider(): array public function testProxyPutManyReturnsUnderlyingResult(): void { - $store = m::mock(ArrayStore::class); - $store->shouldReceive('putMany')->once()->with(['key' => 'value'], 60)->andReturnFalse(); + $store = Double::for(ArrayStore::class); + $store->expects('putMany')->with(['key' => 'value'], 60)->returns(false); $this->assertFalse((new StackStoreProxy($store, 60))->putMany(['key' => 'value'], 90)); } @@ -831,13 +937,12 @@ public function testIncrement(): void $key = 'foo'; - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(null); - $this->redis->shouldReceive('get')->once()->with($key)->andReturn(null); - $this->swoole->shouldReceive('forever')->once()->with($key, ['value' => 1])->andReturn(true); - $this->redis->shouldReceive('forever')->once()->with($key, ['value' => 1])->andReturn(true); - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(['value' => 1]); - $this->swoole->shouldReceive('forever')->once()->with($key, ['value' => 3])->andReturn(true); - $this->redis->shouldReceive('forever')->once()->with($key, ['value' => 3])->andReturn(true); + $this->swoole->expects('get')->times(2)->with($key)->returns(null, ['value' => 1]); + $this->redis->expects('get')->with($key)->returns(null); + $this->swoole->expects('forever')->with($key, ['value' => 1])->returns(true); + $this->redis->expects('forever')->with($key, ['value' => 1])->returns(true); + $this->swoole->expects('forever')->with($key, ['value' => 3])->returns(true); + $this->redis->expects('forever')->with($key, ['value' => 3])->returns(true); $this->assertSame(1, $this->store->increment($key)); $this->assertSame(3, $this->store->increment($key, 2)); @@ -851,9 +956,9 @@ public function testIncrementWithTTL(): void $ttl = 100; $expiration = CarbonImmutable::now()->getTimestamp() + $ttl; - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(['value' => 1, 'expiration' => $expiration]); - $this->swoole->shouldReceive('put')->once()->with($key, ['value' => 2, 'expiration' => $expiration], $ttl)->andReturn(true); - $this->redis->shouldReceive('put')->once()->with($key, ['value' => 2, 'expiration' => $expiration], $ttl)->andReturn(true); + $this->swoole->expects('get')->with($key)->returns(['value' => 1, 'expiration' => $expiration]); + $this->swoole->expects('put')->with($key, ['value' => 2, 'expiration' => $expiration], $ttl)->returns(true); + $this->redis->expects('put')->with($key, ['value' => 2, 'expiration' => $expiration], $ttl)->returns(true); $this->assertSame(2, $this->store->increment($key)); } @@ -865,13 +970,13 @@ public function testIncrementDoesNotTreatFailedRepairAsMissingAndPreservesLowerV $record = ['value' => 5]; $incrementedRecord = ['value' => 6]; - $this->swoole->shouldReceive('get')->twice()->with('counter')->andReturnNull(); - $this->redis->shouldReceive('get')->twice()->with('counter')->andReturn($record); - $this->swoole->shouldReceive('forever')->twice()->with('counter', $record)->andReturnFalse(); + $this->swoole->expects('get')->times(2)->with('counter')->returns(null); + $this->redis->expects('get')->times(2)->with('counter')->returns($record); + $this->swoole->expects('forever')->times(2)->with('counter', $record)->returns(false); - $this->swoole->shouldReceive('forever')->once()->with('counter', $incrementedRecord)->andReturnTrue(); - $this->redis->shouldReceive('forever')->once()->with('counter', $incrementedRecord)->andReturnFalse(); - $this->swoole->shouldReceive('forget')->once()->with('counter')->andReturnTrue(); + $this->swoole->expects('forever')->with('counter', $incrementedRecord)->returns(true); + $this->redis->expects('forever')->with('counter', $incrementedRecord)->returns(false); + $this->swoole->expects('forget')->with('counter')->returns(true); $this->assertFalse($this->store->increment('counter')); $this->assertSame(5, $this->store->get('counter')); @@ -883,13 +988,12 @@ public function testDecrement(): void $key = 'foo'; - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(null); - $this->redis->shouldReceive('get')->once()->with($key)->andReturn(null); - $this->swoole->shouldReceive('forever')->once()->with($key, ['value' => -1])->andReturn(true); - $this->redis->shouldReceive('forever')->once()->with($key, ['value' => -1])->andReturn(true); - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(['value' => -1]); - $this->swoole->shouldReceive('forever')->once()->with($key, ['value' => -3])->andReturn(true); - $this->redis->shouldReceive('forever')->once()->with($key, ['value' => -3])->andReturn(true); + $this->swoole->expects('get')->times(2)->with($key)->returns(null, ['value' => -1]); + $this->redis->expects('get')->with($key)->returns(null); + $this->swoole->expects('forever')->with($key, ['value' => -1])->returns(true); + $this->redis->expects('forever')->with($key, ['value' => -1])->returns(true); + $this->swoole->expects('forever')->with($key, ['value' => -3])->returns(true); + $this->redis->expects('forever')->with($key, ['value' => -3])->returns(true); $this->assertSame(-1, $this->store->decrement($key)); $this->assertSame(-3, $this->store->decrement($key, 2)); @@ -903,9 +1007,9 @@ public function testDecrementWithTTL(): void $ttl = 100; $expiration = CarbonImmutable::now()->getTimestamp() + $ttl; - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(['value' => 2, 'expiration' => $expiration]); - $this->swoole->shouldReceive('put')->once()->with($key, ['value' => 1, 'expiration' => $expiration], $ttl)->andReturn(true); - $this->redis->shouldReceive('put')->once()->with($key, ['value' => 1, 'expiration' => $expiration], $ttl)->andReturn(true); + $this->swoole->expects('get')->with($key)->returns(['value' => 2, 'expiration' => $expiration]); + $this->swoole->expects('put')->with($key, ['value' => 1, 'expiration' => $expiration], $ttl)->returns(true); + $this->redis->expects('put')->with($key, ['value' => 1, 'expiration' => $expiration], $ttl)->returns(true); $this->assertSame(1, $this->store->decrement($key)); } @@ -914,8 +1018,8 @@ public function testForever(): void { $this->createStores(); - $this->swoole->shouldReceive('forever')->once()->with('foo', ['value' => 'bar'])->andReturn(true); - $this->redis->shouldReceive('forever')->once()->with('foo', ['value' => 'bar'])->andReturn(true); + $this->swoole->expects('forever')->with('foo', ['value' => 'bar'])->returns(true); + $this->redis->expects('forever')->with('foo', ['value' => 'bar'])->returns(true); $this->assertTrue($this->store->forever('foo', 'bar')); } @@ -924,18 +1028,20 @@ public function testForeverFailed(): void { $this->createStores(); - $this->swoole->shouldReceive('forever')->once()->with('foo', ['value' => 'bar'])->andReturn(false); + $this->swoole->expects('forever')->with('foo', ['value' => 'bar'])->returns(false); $this->assertFalse($this->store->forever('foo', 'bar')); + + $this->redis->unused(); } public function testForeverFailedWithRollback(): void { $this->createStores(); - $this->swoole->shouldReceive('forever')->once()->with('foo', ['value' => 'bar'])->andReturn(true); - $this->redis->shouldReceive('forever')->once()->with('foo', ['value' => 'bar'])->andReturn(false); - $this->swoole->shouldReceive('forget')->once()->with('foo')->andReturn(true); + $this->swoole->expects('forever')->with('foo', ['value' => 'bar'])->returns(true); + $this->redis->expects('forever')->with('foo', ['value' => 'bar'])->returns(false); + $this->swoole->expects('forget')->with('foo')->returns(true); $this->assertFalse($this->store->forever('foo', 'bar')); } @@ -944,8 +1050,8 @@ public function testForget(): void { $this->createStores(); - $this->swoole->shouldReceive('forget')->once()->with('foo')->andReturn(true); - $this->redis->shouldReceive('forget')->once()->with('foo')->andReturn(true); + $this->swoole->expects('forget')->with('foo')->returns(true); + $this->redis->expects('forget')->with('foo')->returns(true); $this->assertTrue($this->store->forget('foo')); } @@ -954,22 +1060,22 @@ public function testForgetFailed(): void { $this->createStores(); - $this->swoole->shouldReceive('forget')->once()->with('foo')->andReturn(false); - $this->redis->shouldReceive('forget')->once()->with('foo')->andReturn(true); + $this->swoole->expects('forget')->with('foo')->returns(false); + $this->redis->expects('forget')->with('foo')->returns(true); $this->assertFalse($this->store->forget('foo')); } public function testForgetAttemptsEveryLayerAndPreservesTheEarliestFailure(): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $exception = new RuntimeException('first failure'); - $top->shouldReceive('forget')->once()->with('foo')->andThrow($exception); - $middle->shouldReceive('forget')->once()->with('foo')->andReturnFalse(); - $bottom->shouldReceive('forget')->once()->with('foo')->andThrow(new RuntimeException('second failure')); + $top->expects('forget')->with('foo')->throws($exception); + $middle->expects('forget')->with('foo')->returns(false); + $bottom->expects('forget')->with('foo')->throws(new RuntimeException('second failure')); try { (new StackStore([$top, $middle, $bottom]))->forget('foo'); @@ -983,17 +1089,17 @@ public function testForgetAttemptsEveryLayerAndPreservesTheEarliestFailure(): vo #[TestWith([true])] public function testForgetCancellationSupersedesEarlierFailureAndStopsFurtherLayers(bool $cleanupThrows): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $cancellation = new CanceledException('forget canceled'); if ($cleanupThrows) { $cancellation = new RuntimeException('Forget cleanup failed.', previous: $cancellation); } - $top->shouldReceive('forget')->once()->with('foo')->andThrow(new RuntimeException('first failure')); - $middle->shouldReceive('forget')->once()->with('foo')->andThrow($cancellation); - $bottom->shouldNotReceive('forget'); + $top->expects('forget')->with('foo')->throws(new RuntimeException('first failure')); + $middle->expects('forget')->with('foo')->throws($cancellation); + $bottom->expects('forget')->never(); try { (new StackStore([$top, $middle, $bottom]))->forget('foo'); @@ -1007,8 +1113,8 @@ public function testFlush(): void { $this->createStores(); - $this->swoole->shouldReceive('flush')->once()->withNoArgs()->andReturn(true); - $this->redis->shouldReceive('flush')->once()->withNoArgs()->andReturn(true); + $this->swoole->expects('flush')->with(Argument::none())->returns(true); + $this->redis->expects('flush')->with(Argument::none())->returns(true); $this->assertTrue($this->store->flush()); } @@ -1017,22 +1123,22 @@ public function testFlushFailed(): void { $this->createStores(); - $this->swoole->shouldReceive('flush')->once()->withNoArgs()->andReturn(false); - $this->redis->shouldReceive('flush')->once()->withNoArgs()->andReturn(true); + $this->swoole->expects('flush')->with(Argument::none())->returns(false); + $this->redis->expects('flush')->with(Argument::none())->returns(true); $this->assertFalse($this->store->flush()); } public function testFlushAttemptsEveryLayerAndPreservesTheEarliestFailure(): void { - $top = m::mock(ArrayStore::class); - $middle = m::mock(ArrayStore::class); - $bottom = m::mock(ArrayStore::class); + $top = Double::for(ArrayStore::class); + $middle = Double::for(ArrayStore::class); + $bottom = Double::for(ArrayStore::class); $exception = new RuntimeException('first failure'); - $top->shouldReceive('flush')->once()->withNoArgs()->andThrow($exception); - $middle->shouldReceive('flush')->once()->withNoArgs()->andReturnFalse(); - $bottom->shouldReceive('flush')->once()->withNoArgs()->andThrow(new RuntimeException('second failure')); + $top->expects('flush')->with(Argument::none())->throws($exception); + $middle->expects('flush')->with(Argument::none())->returns(false); + $bottom->expects('flush')->with(Argument::none())->throws(new RuntimeException('second failure')); try { (new StackStore([$top, $middle, $bottom]))->flush(); @@ -1044,12 +1150,9 @@ public function testFlushAttemptsEveryLayerAndPreservesTheEarliestFailure(): voi public function testThreeStores(): void { - /** @var ArrayStore|MockInterface $array */ - $array = m::mock(ArrayStore::class); - /** @var MockInterface|SwooleStore $swoole */ - $swoole = m::mock(SwooleStore::class); - /** @var MockInterface|RedisStore $redis */ - $redis = m::mock(RedisStore::class); + $array = Double::for(ArrayStore::class); + $swoole = Double::for(SwooleStore::class); + $redis = Double::for(RedisStore::class); $store = new StackStore([$array, $swoole, $redis]); @@ -1059,36 +1162,25 @@ public function testThreeStores(): void $expiration = CarbonImmutable::now()->getTimestamp() + $ttl; $record = compact('value', 'expiration'); - $array->shouldReceive('get')->once()->with($key)->andReturn($record); + $array->expects('get')->times(4)->with($key)->returns($record, null, null, null); + $swoole->expects('get')->times(3)->with($key)->returns($record, null, null); + $redis->expects('get')->times(2)->with($key)->returns($record, null); + $array->expects('put')->times(4)->with($key, $record, $ttl)->returns(true); + $swoole->expects('put')->times(3)->with($key, $record, $ttl)->returns(true); + $redis->expects('put')->times(2)->with($key, $record, $ttl)->returns(true, false); + $swoole->expects('forget')->with($key)->returns(true); + $array->expects('forget')->with($key)->returns(true); + $this->assertSame($value, $store->get($key)); - $array->shouldReceive('get')->once()->with($key)->andReturn(null); - $swoole->shouldReceive('get')->once()->with($key)->andReturn($record); - $array->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); $this->assertSame($value, $store->get($key)); - $array->shouldReceive('get')->once()->with($key)->andReturn(null); - $swoole->shouldReceive('get')->once()->with($key)->andReturn(null); - $redis->shouldReceive('get')->once()->with($key)->andReturn($record); - $array->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); - $swoole->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); $this->assertSame($value, $store->get($key)); - $array->shouldReceive('get')->once()->with($key)->andReturn(null); - $swoole->shouldReceive('get')->once()->with($key)->andReturn(null); - $redis->shouldReceive('get')->once()->with($key)->andReturn(null); $this->assertNull($store->get($key)); - $array->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); - $swoole->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); - $redis->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); $this->assertTrue($store->put($key, $value, $ttl)); - $array->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); - $swoole->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); - $redis->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(false); - $swoole->shouldReceive('forget')->once()->with($key)->andReturn(true); - $array->shouldReceive('forget')->once()->with($key)->andReturn(true); $this->assertFalse($store->put($key, $value, $ttl)); } @@ -1098,20 +1190,17 @@ public function testInvalidRecord(): void $key = 'foo'; - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn('invalid record'); + $this->swoole->expects('get')->times(2)->with($key)->returns('invalid record', null); $this->assertNull($this->store->get($key)); - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn(null); - $this->redis->shouldReceive('get')->once()->with($key)->andReturn('invalid record'); + $this->redis->expects('get')->with($key)->returns('invalid record'); $this->assertNull($this->store->get($key)); } public function testProxyMaxTTL(): void { - /** @var MockInterface|SwooleStore $swoole */ - $swoole = m::mock(SwooleStore::class); - /** @var MockInterface|RedisStore $redis */ - $redis = m::mock(RedisStore::class); + $swoole = Double::for(SwooleStore::class); + $redis = Double::for(RedisStore::class); $key = 'foo'; $value = 'bar'; @@ -1125,18 +1214,16 @@ public function testProxyMaxTTL(): void new StackStoreProxy($redis), ]); - $swoole->shouldReceive('put')->once()->with($key, $record, $maxTTL)->andReturn(true); - $redis->shouldReceive('put')->once()->with($key, $record, $ttl)->andReturn(true); + $swoole->expects('put')->with($key, $record, $maxTTL)->returns(true); + $redis->expects('put')->with($key, $record, $ttl)->returns(true); $this->assertTrue($store->put($key, $value, $ttl)); } public function testProxyMaxTTLWithForever(): void { - /** @var MockInterface|SwooleStore $swoole */ - $swoole = m::mock(SwooleStore::class); - /** @var MockInterface|RedisStore $redis */ - $redis = m::mock(RedisStore::class); + $swoole = Double::for(SwooleStore::class); + $redis = Double::for(RedisStore::class); $key = 'foo'; $value = 'bar'; @@ -1148,8 +1235,8 @@ public function testProxyMaxTTLWithForever(): void new StackStoreProxy($redis), ]); - $swoole->shouldReceive('put')->once()->with($key, $record, $maxTTL)->andReturn(true); - $redis->shouldReceive('forever')->once()->with($key, $record)->andReturn(true); + $swoole->expects('put')->with($key, $record, $maxTTL)->returns(true); + $redis->expects('forever')->with($key, $record)->returns(true); $this->assertTrue($store->forever($key, $value)); } @@ -1163,9 +1250,9 @@ public function testTouchPropagatesThroughAllLayers(): void $value = 'bar'; $record = ['value' => $value, 'ttl' => 30]; - $this->swoole->shouldReceive('get')->once()->with($key)->andReturn($record); - $this->swoole->shouldReceive('put')->once()->with($key, m::on(fn ($r) => $r['value'] === $value && isset($r['expiration'])), 60)->andReturn(true); - $this->redis->shouldReceive('put')->once()->with($key, m::on(fn ($r) => $r['value'] === $value && isset($r['expiration'])), 60)->andReturn(true); + $this->swoole->expects('get')->with($key)->returns($record); + $this->swoole->expects('put')->with($key, Argument::satisfies(fn ($r) => $r['value'] === $value && isset($r['expiration'])), 60)->returns(true); + $this->redis->expects('put')->with($key, Argument::satisfies(fn ($r) => $r['value'] === $value && isset($r['expiration'])), 60)->returns(true); $this->assertTrue($this->store->touch($key, 60)); } @@ -1174,8 +1261,8 @@ public function testTouchReturnsFalseWhenKeyDoesNotExist(): void { $this->createStores(); - $this->swoole->shouldReceive('get')->once()->with('nonexistent')->andReturn(null); - $this->redis->shouldReceive('get')->once()->with('nonexistent')->andReturn(null); + $this->swoole->expects('get')->with('nonexistent')->returns(null); + $this->redis->expects('get')->with('nonexistent')->returns(null); $this->assertFalse($this->store->touch('nonexistent', 60)); } @@ -1184,10 +1271,8 @@ public function testTouchProxyCapsMaxTTL(): void { CarbonImmutable::setTestNow(CarbonImmutable::now()); - /** @var MockInterface|SwooleStore $swoole */ - $swoole = m::mock(SwooleStore::class); - /** @var MockInterface|RedisStore $redis */ - $redis = m::mock(RedisStore::class); + $swoole = Double::for(SwooleStore::class); + $redis = Double::for(RedisStore::class); $key = 'foo'; $value = 'bar'; @@ -1199,17 +1284,20 @@ public function testTouchProxyCapsMaxTTL(): void new StackStoreProxy($redis), ]); - $swoole->shouldReceive('get')->once()->with($key)->andReturn($record); - $swoole->shouldReceive('put')->once()->with($key, m::on(fn ($r) => $r['value'] === $value && isset($r['expiration'])), $maxTTL)->andReturn(true); - $redis->shouldReceive('put')->once()->with($key, m::on(fn ($r) => $r['value'] === $value && isset($r['expiration'])), 60)->andReturn(true); + $swoole->expects('get')->with($key)->returns($record); + $swoole->expects('put')->with($key, Argument::satisfies(fn ($r) => $r['value'] === $value && isset($r['expiration'])), $maxTTL)->returns(true); + $redis->expects('put')->with($key, Argument::satisfies(fn ($r) => $r['value'] === $value && isset($r['expiration'])), 60)->returns(true); $this->assertTrue($store->touch($key, 60)); } - private function createStores() + /** + * Create a stack with isolated cache layer doubles. + */ + private function createStores(): void { - $this->redis = m::mock(RedisStore::class); - $this->swoole = m::mock(SwooleStore::class); + $this->redis = Double::for(RedisStore::class); + $this->swoole = Double::for(SwooleStore::class); $this->store = new StackStore([$this->swoole, $this->redis]); } } diff --git a/tests/Cache/CacheSwooleStoreConcurrencyTest.php b/tests/Cache/CacheSwooleStoreConcurrencyTest.php index 6ba3564d84..af6d32830f 100644 --- a/tests/Cache/CacheSwooleStoreConcurrencyTest.php +++ b/tests/Cache/CacheSwooleStoreConcurrencyTest.php @@ -7,10 +7,9 @@ use Hypervel\Cache\SwooleStore; use Hypervel\Cache\SwooleTableManager; use Hypervel\Cache\SwooleTableState; -use Hypervel\Contracts\Container\Container; +use Hypervel\Container\Container; use Hypervel\Foundation\Testing\Concerns\InteractsWithSwooleTables; use Hypervel\Tests\TestCase; -use Mockery as m; use ReflectionMethod; use RuntimeException; use Swoole\Atomic; @@ -498,7 +497,7 @@ private function reapIfExited(int $pid, array &$reaped): bool private function createState(): SwooleTableState { - $state = (new SwooleTableManager(m::mock(Container::class))) + $state = (new SwooleTableManager(new Container)) ->createState(128, 10240, 0.2, 12345); $this->trackSwooleTable($state->table()); diff --git a/tests/Cache/CacheSwooleStoreIntervalTest.php b/tests/Cache/CacheSwooleStoreIntervalTest.php index c9792dc417..09a89d2070 100644 --- a/tests/Cache/CacheSwooleStoreIntervalTest.php +++ b/tests/Cache/CacheSwooleStoreIntervalTest.php @@ -15,8 +15,10 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Laravel\SerializableClosure\SerializableClosure; -use Mockery as m; use ReflectionMethod; use ReflectionProperty; use RuntimeException; @@ -27,6 +29,7 @@ class CacheSwooleStoreIntervalTest extends TestCase { use InteractsWithSwooleTables; + use VerifiesDoubles; protected string $tempDir; @@ -591,7 +594,7 @@ public function testStaleCleanupAndEvictionSkipIntervalControlRows(): void public function testThrowingTimerResolverIsReportedAndCanRetry(): void { $container = new Container; - $handler = m::spy(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); @@ -615,10 +618,10 @@ public function testThrowingTimerResolverIsReportedAndCanRetry(): void $store->refreshIntervalCaches(); - $handler->shouldHaveReceived('report')->with(m::on( + $handler->received('report')->with(Argument::satisfies( fn (Throwable $e): bool => $e::class === $exception::class && $e->getMessage() === $exception->getMessage() - ))->once(); + ))->times(1); $this->assertFalse($this->userRow($state, $readerStore, 'foo')); $this->assertNull($this->metadata($state, $metadataKey)['lastRefreshedAt']); $this->assertNull($this->metadata($state, $metadataKey)['refreshingAt']); @@ -653,7 +656,7 @@ public function testThrowingSameInstanceFallbackRethrowsAndClearsClaim(): void public function testCanceledSameInstanceFallbackClearsClaimAndCanRetry(): void { $container = new Container; - $handler = m::spy(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); @@ -672,7 +675,7 @@ public function testCanceledSameInstanceFallbackClearsClaimAndCanRetry(): void $this->assertSame($cancellation, $exception); } - $handler->shouldNotHaveReceived('report'); + $handler->received('report')->never(); $this->assertNull($this->metadata($state, $metadataKey)['refreshingAt']); $this->assertSame('bar', $store->get('foo')); } @@ -680,7 +683,7 @@ public function testCanceledSameInstanceFallbackClearsClaimAndCanRetry(): void public function testTimerRefreshCleanupCancellationSupersedesOrdinaryFailureWithoutReporting(): void { $container = new Container; - $handler = m::spy(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); @@ -701,13 +704,13 @@ public function testTimerRefreshCleanupCancellationSupersedesOrdinaryFailureWith $this->assertSame($cleanupCancellation, $exception); } - $handler->shouldNotHaveReceived('report'); + $handler->received('report')->never(); } public function testRefreshCancellationRemainsPrimaryWhenClaimCleanupFails(): void { $container = new Container; - $handler = m::spy(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); @@ -728,7 +731,7 @@ public function testRefreshCancellationRemainsPrimaryWhenClaimCleanupFails(): vo $this->assertSame($cancellation, $exception); } - $handler->shouldNotHaveReceived('report'); + $handler->received('report')->never(); } public function testIntervalRegistrationCancellationRemovesMetadata(): void @@ -833,7 +836,7 @@ public function report(Throwable $e): void public function testFailedPublicValueWriteClearsClaimAndReportsFailure(): void { $container = new Container; - $handler = m::spy(ExceptionHandler::class); + $handler = Double::for(ExceptionHandler::class); $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); @@ -845,9 +848,9 @@ public function testFailedPublicValueWriteClearsClaimAndReportsFailure(): void $refresherStore->refreshIntervalCaches(); - $handler->shouldHaveReceived('report')->with(m::on( + $handler->received('report')->with(Argument::satisfies( fn (RuntimeException $e): bool => $e->getMessage() === 'Unable to refresh Swoole interval cache [foo].' - ))->once(); + ))->times(1); $metadata = $this->metadata($state, $this->metadataKey($workerStore, 'foo')); diff --git a/tests/Cache/CacheSwooleStoreTest.php b/tests/Cache/CacheSwooleStoreTest.php index 4c48112f7d..a6358c851f 100644 --- a/tests/Cache/CacheSwooleStoreTest.php +++ b/tests/Cache/CacheSwooleStoreTest.php @@ -12,17 +12,19 @@ use Hypervel\Cache\SwooleStore; use Hypervel\Cache\SwooleTableManager; use Hypervel\Cache\SwooleTableState; +use Hypervel\Container\Container; use Hypervel\Contracts\Cache\CanFlushLocks; use Hypervel\Contracts\Cache\LockProvider; use Hypervel\Contracts\Config\Repository as ConfigRepository; -use Hypervel\Contracts\Container\Container; +use Hypervel\Contracts\Container\Container as ContainerContract; use Hypervel\Foundation\Testing\Concerns\InteractsWithSwooleTables; use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Str; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use ReflectionMethod; use stdClass; use TypeError; @@ -30,6 +32,7 @@ class CacheSwooleStoreTest extends TestCase { use InteractsWithSwooleTables; + use VerifiesDoubles; public function testCanRetrieveItemsFromStore(): void { @@ -50,37 +53,35 @@ public function testMissingItemsReturnNull(): void public function testMissingSwooleTableConfigThrowsTableNotDefinedException(): void { - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('get') - ->once() + $config = Double::for(ConfigRepository::class); + $config->expects('get') ->with('cache.swoole_tables.missing') - ->andReturn(null); + ->returns(null); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('config')->andReturn($config); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('make')->with('config')->returns($config); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessageIs('Swoole table [missing] is not defined.'); - (new SwooleTableManager($container))->get('missing'); + (new SwooleTableManager($container->instance()))->get('missing'); } public function testSealingRetainsExistingTablesAndRejectsLateCreation(): void { - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('get') - ->once() + $config = Double::for(ConfigRepository::class); + $config->expects('get') ->with('cache.swoole_tables.first') - ->andReturn([ + ->returns([ 'rows' => 64, 'bytes' => 1024, 'conflict_proportion' => 0.2, ]); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('config')->andReturn($config); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('make')->with('config')->returns($config); - $manager = new SwooleTableManager($container); + $manager = new SwooleTableManager($container->instance()); $first = $manager->get('first'); $this->trackSwooleTable($first->table()); @@ -1001,7 +1002,7 @@ private function createState( float $conflictProportion = 0.2, int $hashSeed = 12345 ): SwooleTableState { - $state = (new SwooleTableManager(m::mock(Container::class))) + $state = (new SwooleTableManager(new Container)) ->createState($rows, $bytes, $conflictProportion, $hashSeed); $this->trackSwooleTable($state->table()); diff --git a/tests/Cache/CacheTaggedCacheTest.php b/tests/Cache/CacheTaggedCacheTest.php index 7893bdd3ef..da029792bb 100644 --- a/tests/Cache/CacheTaggedCacheTest.php +++ b/tests/Cache/CacheTaggedCacheTest.php @@ -14,7 +14,9 @@ use Hypervel\Cache\VersionedTagSet; use Hypervel\Contracts\Cache\Store; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -41,6 +43,8 @@ enum TaggedCacheTestKeyUnitEnum class CacheTaggedCacheTest extends TestCase { + use VerifiesDoubles; + public function testCacheCanBeSavedWithMultipleTags(): void { $store = new ArrayStore; @@ -106,31 +110,29 @@ public function testCacheSavedWithMultipleTagsCanBeFlushed(): void public function testVersionedTagResetAttemptsEveryTagAndAggregatesFalseResults(): void { - $store = m::mock(Store::class); - $store->shouldReceive('forever') - ->once() - ->with('tag:users:key', m::type('string')) - ->andReturnFalse(); - $store->shouldReceive('forever') - ->once() - ->with('tag:posts:key', m::type('string')) - ->andReturnTrue(); + $store = Double::for(Store::class); + $store->expects('forever') + ->with('tag:users:key', Argument::type('string')) + ->returns(false); + $store->expects('forever') + ->with('tag:posts:key', Argument::type('string')) + ->returns(true); $this->assertFalse((new VersionedTagSet($store, ['users', 'posts']))->reset()); } public function testVersionedTagFlushAttemptsEveryTagAndTreatsMissingTagKeysAsSuccess(): void { - $store = m::mock(Store::class); - $store->shouldReceive('forget')->once()->with('tag:users:key')->andReturnFalse(); - $store->shouldReceive('forget')->once()->with('tag:posts:key')->andReturnTrue(); + $store = Double::for(Store::class); + $store->expects('forget')->with('tag:users:key')->returns(false); + $store->expects('forget')->with('tag:posts:key')->returns(true); $this->assertTrue((new VersionedTagSet($store, ['users', 'posts']))->flush()); } public function testVersionedTagFlushUsesThePerTagExtensionPoint(): void { - $tagSet = new class(m::mock(Store::class), ['users', 'posts']) extends VersionedTagSet { + $tagSet = new class(Double::for(Store::class), ['users', 'posts']) extends VersionedTagSet { public array $flushed = []; public function flushTag(string $name): string @@ -147,15 +149,15 @@ public function flushTag(string $name): string public function testVersionedFlushTagReturnsItsKeyWhenTheTagDoesNotExist(): void { - $store = m::mock(Store::class); - $store->shouldReceive('forget')->once()->with('tag:users:key')->andReturnFalse(); + $store = Double::for(Store::class); + $store->expects('forget')->with('tag:users:key')->returns(false); $this->assertSame('tag:users:key', (new VersionedTagSet($store))->flushTag('users')); } public function testVersionedTagResetUsesTheWriteExtensionPoint(): void { - $tagSet = new class(m::mock(Store::class), ['users', 'posts']) extends VersionedTagSet { + $tagSet = new class(Double::for(Store::class), ['users', 'posts']) extends VersionedTagSet { public array $written = []; protected function writeTagId(string $name, string $id): bool @@ -173,19 +175,16 @@ protected function writeTagId(string $name, string $id): bool public function testVersionedTagResetAttemptsLaterTagsAndRethrowsTheFirstException(): void { $firstException = new RuntimeException('users failed'); - $store = m::mock(Store::class); - $store->shouldReceive('forever') - ->once() - ->with('tag:users:key', m::type('string')) - ->andThrow($firstException); - $store->shouldReceive('forever') - ->once() - ->with('tag:posts:key', m::type('string')) - ->andThrow(new RuntimeException('posts failed')); - $store->shouldReceive('forever') - ->once() - ->with('tag:comments:key', m::type('string')) - ->andReturnTrue(); + $store = Double::for(Store::class); + $store->expects('forever') + ->with('tag:users:key', Argument::type('string')) + ->throws($firstException); + $store->expects('forever') + ->with('tag:posts:key', Argument::type('string')) + ->throws(new RuntimeException('posts failed')); + $store->expects('forever') + ->with('tag:comments:key', Argument::type('string')) + ->returns(true); try { (new VersionedTagSet($store, ['users', 'posts', 'comments']))->reset(); @@ -198,13 +197,12 @@ public function testVersionedTagResetAttemptsLaterTagsAndRethrowsTheFirstExcepti public function testVersionedTagFlushAttemptsLaterTagsAndRethrowsTheFirstException(): void { $firstException = new RuntimeException('users failed'); - $store = m::mock(Store::class); - $store->shouldReceive('forget')->once()->with('tag:users:key')->andThrow($firstException); - $store->shouldReceive('forget') - ->once() + $store = Double::for(Store::class); + $store->expects('forget')->with('tag:users:key')->throws($firstException); + $store->expects('forget') ->with('tag:posts:key') - ->andThrow(new RuntimeException('posts failed')); - $store->shouldReceive('forget')->once()->with('tag:comments:key')->andReturnTrue(); + ->throws(new RuntimeException('posts failed')); + $store->expects('forget')->with('tag:comments:key')->returns(true); try { (new VersionedTagSet($store, ['users', 'posts', 'comments']))->flush(); @@ -222,12 +220,11 @@ public function testVersionedTagResetStopsImmediatelyOnCancellation(bool $cleanu if ($cleanupThrows) { $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } - $store = m::mock(Store::class); - $store->shouldReceive('forever') - ->once() - ->with('tag:users:key', m::type('string')) - ->andThrow($cancellation); - $store->shouldNotReceive('forever')->with('tag:posts:key', m::type('string')); + $store = Double::for(Store::class); + $store->expects('forever') + ->with('tag:users:key', Argument::type('string')) + ->throws($cancellation); + $store->expects('forever')->never()->with('tag:posts:key', Argument::type('string')); try { (new VersionedTagSet($store, ['users', 'posts']))->reset(); @@ -245,10 +242,10 @@ public function testVersionedTagFlushStopsImmediatelyOnCancellation(bool $cleanu if ($cleanupThrows) { $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } - $store = m::mock(Store::class); - $store->shouldReceive('forget')->once()->with('tag:earlier:key')->andThrow(new RuntimeException('Earlier tag failed.')); - $store->shouldReceive('forget')->once()->with('tag:users:key')->andThrow($cancellation); - $store->shouldNotReceive('forget')->with('tag:posts:key'); + $store = Double::for(Store::class); + $store->expects('forget')->with('tag:earlier:key')->throws(new RuntimeException('Earlier tag failed.')); + $store->expects('forget')->with('tag:users:key')->throws($cancellation); + $store->expects('forget')->never()->with('tag:posts:key'); try { (new VersionedTagSet($store, ['earlier', 'users', 'posts']))->flush(); diff --git a/tests/Cache/ConcurrencyLimiterTest.php b/tests/Cache/ConcurrencyLimiterTest.php index 8ba8a876a6..07d1a5f686 100644 --- a/tests/Cache/ConcurrencyLimiterTest.php +++ b/tests/Cache/ConcurrencyLimiterTest.php @@ -20,7 +20,8 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -28,6 +29,8 @@ class ConcurrencyLimiterTest extends TestCase { + use VerifiesDoubles; + protected Repository $repository; protected function setUp(): void @@ -644,9 +647,9 @@ protected function failingReleaseStore( ?LimiterFailingReleaseLock &$lock = null, ?Throwable $releaseFailure = null, ): Store&LockProvider { - $store = m::mock(Store::class, LockProvider::class); - $store->shouldReceive('lock') - ->andReturnUsing(function (string $name, int $seconds, ?string $owner) use (&$lock, $releaseFailure): LockContract { + $store = Double::for(Store::class, LockProvider::class); + $store->allows('lock') + ->resolves(function (string $name, int $seconds, ?string $owner) use (&$lock, $releaseFailure): LockContract { return $lock = new LimiterFailingReleaseLock($name, $seconds, $owner, $releaseFailure); }); diff --git a/tests/Cache/ForgetCommandTest.php b/tests/Cache/ForgetCommandTest.php index 809b61330b..a37e4199e0 100644 --- a/tests/Cache/ForgetCommandTest.php +++ b/tests/Cache/ForgetCommandTest.php @@ -9,19 +9,22 @@ use Hypervel\Contracts\Cache\Repository; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class ForgetCommandTest extends TestCase { + use VerifiesDoubles; + public function testForgetKeyFromDefaultStore(): void { - $cacheManager = m::mock(CacheManager::class); - $repository = m::mock(Repository::class); + $cacheManager = Double::for(CacheManager::class); + $repository = Double::for(Repository::class); - $cacheManager->shouldReceive('store')->once()->with(null)->andReturn($repository); - $repository->shouldReceive('forget')->once()->with('my-key'); + $cacheManager->expects('store')->with(null)->returns($repository); + $repository->expects('forget')->with('my-key'); $command = new ForgetCommand($cacheManager); $command->setHypervel(new Application); @@ -37,11 +40,11 @@ public function testForgetKeyFromDefaultStore(): void public function testForgetKeyFromSpecifiedStore(): void { - $cacheManager = m::mock(CacheManager::class); - $repository = m::mock(Repository::class); + $cacheManager = Double::for(CacheManager::class); + $repository = Double::for(Repository::class); - $cacheManager->shouldReceive('store')->once()->with('redis')->andReturn($repository); - $repository->shouldReceive('forget')->once()->with('my-key'); + $cacheManager->expects('store')->with('redis')->returns($repository); + $repository->expects('forget')->with('my-key'); $command = new ForgetCommand($cacheManager); $command->setHypervel(new Application); diff --git a/tests/Cache/ModelCacheCoordinatorTest.php b/tests/Cache/ModelCacheCoordinatorTest.php index bab73c771e..3738667880 100644 --- a/tests/Cache/ModelCacheCoordinatorTest.php +++ b/tests/Cache/ModelCacheCoordinatorTest.php @@ -27,13 +27,17 @@ use Hypervel\Engine\Channel; use Hypervel\Support\Sleep; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use function Hypervel\Coroutine\parallel; class ModelCacheCoordinatorTest extends TestCase { + use VerifiesDoubles; + protected Closure $source; protected Container $container; @@ -100,15 +104,15 @@ public function testColdFillDoubleChecksAfterLockAcquisition(): void $coordinator->fill($seedRepository, $this->source, 'seed', 300, fn (): string => 'published'); $envelope = $seedRepository->getStore()->get('seed'); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $lock = m::mock(RefreshableLock::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $lock = Double::for(RefreshableLock::class); - $repository->shouldReceive('get')->twice()->with('key')->andReturn(null, $envelope); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldNotReceive('put'); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); - $lock->shouldReceive('get')->once()->with(m::type(Closure::class))->andReturnUsing( + $repository->expects('get')->times(2)->with('key')->returns(null, $envelope); + $repository->expects('getStore')->returns($store); + $repository->expects('put')->never(); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); + $lock->expects('get')->with(Argument::type(Closure::class))->resolves( static fn (Closure $callback): mixed => $callback(), ); @@ -289,18 +293,18 @@ function () use (&$reads): null { public function testNonPublishingNullReadDoesNotRefreshTheLease(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $lock = m::mock(RefreshableLock::class); - - $repository->shouldReceive('get')->twice()->with('key')->andReturnNull(); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldNotReceive('put'); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); - $lock->shouldReceive('get')->once()->with(m::type(Closure::class))->andReturnUsing( + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $lock = Double::for(RefreshableLock::class); + + $repository->expects('get')->times(2)->with('key')->returns(null); + $repository->expects('getStore')->returns($store); + $repository->expects('put')->never(); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); + $lock->expects('get')->with(Argument::type(Closure::class))->resolves( static fn (Closure $callback): mixed => $callback(), ); - $lock->shouldNotReceive('refresh'); + $lock->expects('refresh')->never(); $this->assertNull($coordinator->fill( $repository, @@ -315,16 +319,16 @@ public function testNonPublishingNullReadDoesNotRefreshTheLease(): void public function testFailedLockAcquisitionReadsWithoutPublishingOrResolvingWriter(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $lock = m::mock(RefreshableLock::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $lock = Double::for(RefreshableLock::class); $writerResolutions = 0; - $repository->shouldReceive('get')->once()->with('key')->andReturnNull(); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldNotReceive('put'); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); - $lock->shouldReceive('get')->once()->with(m::type(Closure::class))->andReturnFalse(); + $repository->expects('get')->with('key')->returns(null); + $repository->expects('getStore')->returns($store); + $repository->expects('put')->never(); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); + $lock->expects('get')->with(Argument::type(Closure::class))->returns(false); $this->assertSame('database', $coordinator->fill( $repository, @@ -344,27 +348,27 @@ public function testFailedLockAcquisitionReadsWithoutPublishingOrResolvingWriter public function testColdFillRefreshesAfterReadingAndBeforeResolvingWriterOrPublishing(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $lock = m::mock(RefreshableLock::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $lock = Double::for(RefreshableLock::class); $operations = []; - $repository->shouldReceive('get')->twice()->with('key')->andReturnNull(); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldReceive('put')->once()->with( + $repository->expects('get')->times(2)->with('key')->returns(null); + $repository->expects('getStore')->returns($store); + $repository->expects('put')->with( 'key', - m::on(static fn (mixed $value): bool => is_array($value)), + Argument::satisfies(static fn (mixed $value): bool => is_array($value)), 300, - )->andReturnUsing(function () use (&$operations): bool { + )->resolves(function () use (&$operations): bool { $operations[] = 'put'; return true; }); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); - $lock->shouldReceive('get')->once()->with(m::type(Closure::class))->andReturnUsing( + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); + $lock->expects('get')->with(Argument::type(Closure::class))->resolves( static fn (Closure $callback): mixed => $callback(), ); - $lock->shouldReceive('refresh')->once()->withNoArgs()->andReturnUsing( + $lock->expects('refresh')->with(Argument::none())->resolves( function () use (&$operations): bool { $operations[] = 'refresh'; @@ -394,19 +398,19 @@ function () use (&$operations): string { public function testColdFillThatLostItsLeaseReturnsTheReadValueWithoutPublishing(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $lock = m::mock(RefreshableLock::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $lock = Double::for(RefreshableLock::class); $operations = []; - $repository->shouldReceive('get')->twice()->with('key')->andReturnNull(); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldNotReceive('put'); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); - $lock->shouldReceive('get')->once()->with(m::type(Closure::class))->andReturnUsing( + $repository->expects('get')->times(2)->with('key')->returns(null); + $repository->expects('getStore')->returns($store); + $repository->expects('put')->never(); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); + $lock->expects('get')->with(Argument::type(Closure::class))->resolves( static fn (Closure $callback): mixed => $callback(), ); - $lock->shouldReceive('refresh')->once()->withNoArgs()->andReturnUsing( + $lock->expects('refresh')->with(Argument::none())->resolves( function () use (&$operations): bool { $operations[] = 'refresh'; @@ -436,22 +440,22 @@ function () use (&$operations): string { public function testFalseCallbackResultIsNotMistakenForFailedAcquisition(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $lock = m::mock(RefreshableLock::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $lock = Double::for(RefreshableLock::class); - $repository->shouldReceive('get')->twice()->with('key')->andReturnNull(); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldReceive('put')->once()->with( + $repository->expects('get')->times(2)->with('key')->returns(null); + $repository->expects('getStore')->returns($store); + $repository->expects('put')->with( 'key', - m::on(static fn (mixed $value): bool => is_array($value)), + Argument::satisfies(static fn (mixed $value): bool => is_array($value)), 300, - )->andReturnTrue(); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); - $lock->shouldReceive('get')->once()->with(m::type(Closure::class))->andReturnUsing( + )->returns(true); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); + $lock->expects('get')->with(Argument::type(Closure::class))->resolves( static fn (Closure $callback): mixed => $callback(), ); - $lock->shouldReceive('refresh')->once()->withNoArgs()->andReturnTrue(); + $lock->expects('refresh')->with(Argument::none())->returns(true); $reads = 0; $this->assertFalse($coordinator->fill( @@ -471,14 +475,14 @@ function () use (&$reads): false { public function testFillPropagatesSourceFailureAndReleasesTheLock(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); $lock = new CoordinatorTestLock; - $repository->shouldReceive('get')->twice()->with('key')->andReturnNull(); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldNotReceive('put'); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); + $repository->expects('get')->times(2)->with('key')->returns(null); + $repository->expects('getStore')->returns($store); + $repository->expects('put')->never(); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); try { $coordinator->fill( @@ -500,25 +504,25 @@ public function testFillPropagatesSourceFailureAndReleasesTheLock(): void public function testInvalidationUsesTheSameBoundedLockAndForgetsInsideIt(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $fillLock = m::mock(RefreshableLock::class); - $invalidateLock = m::mock(RefreshableLock::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $fillLock = Double::for(RefreshableLock::class); + $invalidateLock = Double::for(RefreshableLock::class); $lockNames = []; - $repository->shouldReceive('get')->once()->with('a-very-long-data-key')->andReturnNull(); - $repository->shouldReceive('getStore')->twice()->andReturn($store); - $repository->shouldReceive('forget')->once()->with('a-very-long-data-key')->andReturnTrue(); - $store->shouldReceive('lock')->twice()->andReturnUsing( + $repository->expects('get')->with('a-very-long-data-key')->returns(null); + $repository->expects('getStore')->times(2)->returns($store); + $repository->expects('forget')->with('a-very-long-data-key')->returns(true); + $store->expects('lock')->times(2)->resolves( function (string $name, int $seconds) use (&$lockNames, $fillLock, $invalidateLock): LockContract { $lockNames[] = [$name, $seconds]; return count($lockNames) === 1 ? $fillLock : $invalidateLock; }, ); - $fillLock->shouldReceive('get')->once()->with(m::type(Closure::class))->andReturnFalse(); - $invalidateLock->shouldReceive('betweenBlockedAttemptsSleepFor')->once()->with(25)->andReturnSelf(); - $invalidateLock->shouldReceive('block')->once()->with(11, m::type(Closure::class))->andReturnUsing( + $fillLock->expects('get')->with(Argument::type(Closure::class))->returns(false); + $invalidateLock->expects('betweenBlockedAttemptsSleepFor')->with(25); + $invalidateLock->expects('block')->with(11, Argument::type(Closure::class))->resolves( static fn (int $seconds, Closure $callback): mixed => $callback(), ); @@ -583,13 +587,13 @@ public function testInvalidationRetriesBriefLockCollisionAfterTwentyFiveMillisec Sleep::fake(); $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); $lock = new CoordinatorTestLock(failFirstAcquisition: true); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldReceive('forget')->once()->with('key')->andReturnTrue(); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); + $repository->expects('getStore')->returns($store); + $repository->expects('forget')->with('key')->returns(true); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); $coordinator->invalidate($repository, 'key'); @@ -604,15 +608,15 @@ public function testInvalidationRetriesBriefLockCollisionAfterTwentyFiveMillisec public function testInvalidationPropagatesLockTimeoutWithoutForgetting(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $lock = m::mock(RefreshableLock::class); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $lock = Double::for(RefreshableLock::class); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldNotReceive('forget'); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); - $lock->shouldReceive('betweenBlockedAttemptsSleepFor')->once()->with(25)->andReturnSelf(); - $lock->shouldReceive('block')->once()->with(11, m::type(Closure::class))->andThrow(new LockTimeoutException); + $repository->expects('getStore')->returns($store); + $repository->expects('forget')->never(); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); + $lock->expects('betweenBlockedAttemptsSleepFor')->with(25); + $lock->expects('block')->with(11, Argument::type(Closure::class))->throws(new LockTimeoutException); $this->expectException(LockTimeoutException::class); @@ -626,9 +630,9 @@ public function testUnsupportedStoreIsRejectedOnlyAfterAMiss(): void $coordinator->fill($seedRepository, $this->source, 'seed', 300, fn (): string => 'cached'); $envelope = $seedRepository->getStore()->get('seed'); - $hitRepository = m::mock(CacheRepository::class); - $hitRepository->shouldReceive('get')->once()->with('key')->andReturn($envelope); - $hitRepository->shouldNotReceive('getStore'); + $hitRepository = Double::for(CacheRepository::class); + $hitRepository->expects('get')->with('key')->returns($envelope); + $hitRepository->expects('getStore')->never(); $this->assertSame('cached', $coordinator->fill( $hitRepository, @@ -638,10 +642,10 @@ public function testUnsupportedStoreIsRejectedOnlyAfterAMiss(): void fn () => throw new RuntimeException('The source must not be read on a cache hit.'), )); - $missRepository = m::mock(CacheRepository::class); - $unsupportedStore = m::mock(Store::class); - $missRepository->shouldReceive('get')->once()->with('key')->andReturnNull(); - $missRepository->shouldReceive('getStore')->once()->andReturn($unsupportedStore); + $missRepository = Double::for(CacheRepository::class); + $unsupportedStore = Double::for(Store::class); + $missRepository->expects('get')->with('key')->returns(null); + $missRepository->expects('getStore')->returns($unsupportedStore); $this->expectExceptionMessageIsOrContains('does not provide atomic locks'); @@ -650,9 +654,9 @@ public function testUnsupportedStoreIsRejectedOnlyAfterAMiss(): void public function testStackAndFailoverTopologiesAreRejectedThroughDirectAndMemoizedStores(): void { - $failoverStore = m::mock(FailoverStore::class); - $failoverStore->shouldReceive('getRaw')->twice()->with('key')->andReturnNull(); - $failoverStore->shouldReceive('getPrefix')->once()->andReturn(''); + $failoverStore = Double::for(FailoverStore::class); + $failoverStore->expects('getRaw')->times(2)->with('key')->returns(null); + $failoverStore->expects('getPrefix')->returns(''); $stores = [ 'stack' => new StackStore([new ArrayStore]), @@ -692,15 +696,15 @@ public function testStackAndFailoverTopologiesAreRejectedThroughDirectAndMemoize public function testNonRefreshableLockIsRejectedOnlyAfterAMiss(): void { $coordinator = new ModelCacheCoordinator($this->container); - $repository = m::mock(CacheRepository::class); - $store = m::mock(Store::class, LockProvider::class); - $lock = m::mock(LockContract::class); - - $repository->shouldReceive('get')->once()->with('key')->andReturnNull(); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldNotReceive('put'); - $store->shouldReceive('lock')->once()->with(m::type('string'), 10)->andReturn($lock); - $lock->shouldNotReceive('get'); + $repository = Double::for(CacheRepository::class); + $store = Double::for(Store::class, LockProvider::class); + $lock = Double::for(LockContract::class); + + $repository->expects('get')->with('key')->returns(null); + $repository->expects('getStore')->returns($store); + $repository->expects('put')->never(); + $store->expects('lock')->with(Argument::type('string'), 10)->returns($lock); + $lock->expects('get')->never(); $this->expectExceptionMessageIsOrContains('does not provide refreshable atomic locks'); diff --git a/tests/Cache/ModelCacheStoreValidatorTest.php b/tests/Cache/ModelCacheStoreValidatorTest.php index 155216e8cf..be4b6a8f31 100644 --- a/tests/Cache/ModelCacheStoreValidatorTest.php +++ b/tests/Cache/ModelCacheStoreValidatorTest.php @@ -25,19 +25,22 @@ use Hypervel\Contracts\Redis\Factory as RedisFactory; use Hypervel\Redis\RedisConfig; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Redis; class ModelCacheStoreValidatorTest extends TestCase { + use VerifiesDoubles; + public function testAcceptsSupportedStoresAndSubclasses(): void { $validator = $this->validator(); foreach ([ - m::mock(DatabaseStore::class), - m::mock(FileStore::class), - m::mock(SwooleStore::class), + Double::for(DatabaseStore::class), + Double::for(FileStore::class), + Double::for(SwooleStore::class), $this->redisStore(), ] as $store) { $validator->validate($this->repository($store), 'Auth user cache'); @@ -60,7 +63,7 @@ public function testAcceptsAnyModeTags(): void public function testAcceptsAnyModeTagsThroughAValidStack(): void { $store = new StackStore([ - m::mock(FileStore::class), + Double::for(FileStore::class), $this->redisStore()->setTagMode(TagMode::Any), ]); @@ -87,9 +90,9 @@ public function testRejectsAllModeTags(): void public function testRejectsStoresWithoutTagSupportBeforeReadingTheMode(): void { - $store = m::mock(StackStore::class); - $store->shouldReceive('supportsTags')->once()->andReturnFalse(); - $store->shouldNotReceive('getTagMode'); + $store = Double::for(StackStore::class); + $store->expects('supportsTags')->returns(false); + $store->expects('getTagMode')->never(); $this->expectException(UnsupportedModelCacheStoreException::class); $this->expectExceptionMessageIsOrContains('does not support tags'); @@ -108,9 +111,9 @@ public function testRejectsEveryUnsupportedStoreType(): void new ArrayStore, new WorkerArrayStore, new NullStore, - m::mock(SessionStore::class), - m::mock(FailoverStore::class), - m::mock(StorageStore::class), + Double::for(SessionStore::class), + Double::for(FailoverStore::class), + Double::for(StorageStore::class), ] as $store) { try { $validator->validate($this->repository($store), 'Sanctum token cache'); @@ -125,7 +128,7 @@ public function testRejectsEveryUnsupportedStoreType(): void public function testRejectsStacksBecauseOtherWorkersAndNodesCanRetainUpperLayerCopies(): void { $stack = new StackStore([ - m::mock(FileStore::class), + Double::for(FileStore::class), $this->redisStore(), ]); @@ -143,8 +146,8 @@ public function testAcceptsAbsentAndDisabledRedisSerializersWithoutOpeningAConne ['SeRiAlIzEr' => Redis::SERIALIZER_NONE, 'compression' => 1], [Redis::OPT_SERIALIZER => Redis::SERIALIZER_NONE], ] as $options) { - $redis = m::mock(RedisFactory::class); - $redis->shouldNotReceive('connection'); + $redis = Double::for(RedisFactory::class); + $redis->expects('connection')->never(); $store = new RedisStore($redis, connection: 'cache'); $this->validator(connectionOptions: $options)->validate( @@ -324,8 +327,8 @@ private function validator( */ private function redisStore(): RedisStore { - $redis = m::mock(RedisFactory::class); - $redis->shouldNotReceive('connection'); + $redis = Double::for(RedisFactory::class); + $redis->expects('connection')->never(); return new RedisStore($redis, connection: 'cache'); } diff --git a/tests/Cache/PruneStaleTagsCommandTest.php b/tests/Cache/PruneStaleTagsCommandTest.php index a4e227f101..34d143de7b 100644 --- a/tests/Cache/PruneStaleTagsCommandTest.php +++ b/tests/Cache/PruneStaleTagsCommandTest.php @@ -11,33 +11,33 @@ use Hypervel\Contracts\Cache\Repository; use Hypervel\Contracts\Cache\Store; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class PruneStaleTagsCommandTest extends TestCase { + use VerifiesDoubles; + public function testPruneCallsFlushStaleTagsOnStore(): void { - $store = m::mock(RedisStore::class); - $store->shouldReceive('flushStaleTags') - ->once() - ->andReturn([ + $store = Double::for(RedisStore::class); + $store->expects('flushStaleTags') + ->returns([ 'tags_scanned' => 10, 'entries_removed' => 5, 'empty_sets_deleted' => 2, ]); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore') - ->once() - ->andReturn($store); + $repository = Double::for(Repository::class); + $repository->expects('getStore') + ->returns($store); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->expects('store') ->with(null) - ->once() - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); @@ -50,25 +50,22 @@ public function testPruneCallsFlushStaleTagsOnStore(): void public function testPruneUsesSpecifiedStore(): void { - $store = m::mock(RedisStore::class); - $store->shouldReceive('flushStaleTags') - ->once() - ->andReturn([ + $store = Double::for(RedisStore::class); + $store->expects('flushStaleTags') + ->returns([ 'tags_scanned' => 0, 'entries_removed' => 0, 'empty_sets_deleted' => 0, ]); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore') - ->once() - ->andReturn($store); + $repository = Double::for(Repository::class); + $repository->expects('getStore') + ->returns($store); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->expects('store') ->with('custom-redis') - ->once() - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); @@ -81,18 +78,16 @@ public function testPruneUsesSpecifiedStore(): void public function testPruneHandlesNonSupportedStoreGracefully(): void { - $nonRedisStore = m::mock(Store::class); + $nonRedisStore = Double::for(Store::class); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore') - ->once() - ->andReturn($nonRedisStore); + $repository = Double::for(Repository::class); + $repository->expects('getStore') + ->returns($nonRedisStore); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->expects('store') ->with('file') - ->once() - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); diff --git a/tests/Cache/RedisLockTest.php b/tests/Cache/RedisLockTest.php deleted file mode 100644 index e1559ce41a..0000000000 --- a/tests/Cache/RedisLockTest.php +++ /dev/null @@ -1,220 +0,0 @@ -shouldReceive('set') - ->once() - ->with('lock:foo', m::type('string'), 'EX', 60, 'NX') - ->andReturn(true); - - $lock = new RedisLock($redis, 'lock:foo', 60); - - $this->assertTrue($lock->acquire()); - } - - public function testAcquireWithExpirationReturnsFalseWhenLockExists(): void - { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('set') - ->once() - ->with('lock:foo', m::type('string'), 'EX', 60, 'NX') - ->andReturn(false); - - $lock = new RedisLock($redis, 'lock:foo', 60); - - $this->assertFalse($lock->acquire()); - } - - public function testAcquireWithoutExpirationUsesSETNX(): void - { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('setnx') - ->once() - ->with('lock:foo', m::type('string')) - ->andReturn(1); - - $lock = new RedisLock($redis, 'lock:foo', 0); - - $this->assertTrue($lock->acquire()); - } - - public function testAcquireWithoutExpirationReturnsFalseWhenLockExists(): void - { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('setnx') - ->once() - ->with('lock:foo', m::type('string')) - ->andReturn(0); - - $lock = new RedisLock($redis, 'lock:foo', 0); - - $this->assertFalse($lock->acquire()); - } - - public function testReleaseUsesLuaScriptToAtomicallyCheckOwnership(): void - { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('pack') - ->once() - ->with(['owner123']) - ->andReturn(['packed-owner123']); - $connection->shouldReceive('eval') - ->once() - ->with(m::type('string'), 1, 'lock:foo', 'packed-owner123') - ->andReturn(1); - - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection)); - - $lock = new RedisLock($redis, 'lock:foo', 60, 'owner123'); - - $this->assertTrue($lock->release()); - } - - public function testReleaseReturnsFalseWhenNotOwner(): void - { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('pack') - ->once() - ->with(['owner123']) - ->andReturn(['packed-owner123']); - $connection->shouldReceive('eval') - ->once() - ->with(m::type('string'), 1, 'lock:foo', 'packed-owner123') - ->andReturn(0); - - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection)); - - $lock = new RedisLock($redis, 'lock:foo', 60, 'owner123'); - - $this->assertFalse($lock->release()); - } - - public function testForceReleaseDeletesKeyRegardlessOfOwnership(): void - { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('del') - ->once() - ->with('lock:foo'); - - $lock = new RedisLock($redis, 'lock:foo', 60); - - $lock->forceRelease(); - } - - public function testOwnerReturnsTheOwnerIdentifier(): void - { - $redis = m::mock(RedisProxy::class); - - $lock = new RedisLock($redis, 'lock:foo', 60, 'my-owner-id'); - - $this->assertSame('my-owner-id', $lock->owner()); - } - - public function testOwnerIsAutoGeneratedWhenNotProvided(): void - { - $redis = m::mock(RedisProxy::class); - - $lock = new RedisLock($redis, 'lock:foo', 60); - - $this->assertNotEmpty($lock->owner()); - $this->assertIsString($lock->owner()); - } - - public function testGetCallsAcquireAndExecutesCallbackOnSuccess(): void - { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('pack') - ->once() - ->andReturn(['packed-owner']); - $connection->shouldReceive('eval') - ->once() - ->andReturn(1); - - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('set') - ->once() - ->with('lock:foo', m::type('string'), 'EX', 60, 'NX') - ->andReturn(true); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection)); - - $lock = new RedisLock($redis, 'lock:foo', 60); - - $result = $lock->get(fn () => 'callback-result'); - - $this->assertSame('callback-result', $result); - } - - public function testGetReturnsFalseWhenLockNotAcquired(): void - { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('set') - ->once() - ->with('lock:foo', m::type('string'), 'EX', 60, 'NX') - ->andReturn(false); - - $lock = new RedisLock($redis, 'lock:foo', 60); - - $result = $lock->get(fn () => 'callback-result'); - - $this->assertFalse($result); - } - - public function testGetReleasesLockAfterCallbackEvenOnException(): void - { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('pack') - ->once() - ->andReturn(['packed-owner']); - $connection->shouldReceive('eval') - ->once() - ->andReturn(1); - - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('set') - ->once() - ->andReturn(true); - $redis->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection)); - - $lock = new RedisLock($redis, 'lock:foo', 60); - - $this->expectException(RuntimeException::class); - - $lock->get(function () { - throw new RuntimeException('test exception'); - }); - } - - public function testGetConnectionNameReturnsConnectionName(): void - { - $redis = m::mock(RedisProxy::class); - $redis->shouldReceive('getName')->once()->andReturn('default'); - - $lock = new RedisLock($redis, 'lock:foo', 60); - - $this->assertSame('default', $lock->getConnectionName()); - } -} diff --git a/tests/Cache/RegisterSwooleMaintenanceTimersTest.php b/tests/Cache/RegisterSwooleMaintenanceTimersTest.php index 1f9768a7b5..9d4895a44d 100644 --- a/tests/Cache/RegisterSwooleMaintenanceTimersTest.php +++ b/tests/Cache/RegisterSwooleMaintenanceTimersTest.php @@ -7,13 +7,16 @@ use Hypervel\Cache\Listeners\RegisterSwooleMaintenanceTimers; use Hypervel\Cache\SwooleStore; use Hypervel\Config\Repository; +use Hypervel\Contracts\Cache\Factory as CacheFactory; +use Hypervel\Contracts\Cache\Repository as CacheRepository; use Hypervel\Contracts\Container\Container; use Hypervel\Coordinator\Constants; use Hypervel\Coordinator\Timer; use Hypervel\Core\Events\AfterWorkerStart; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Server as SwooleServer; @@ -21,6 +24,8 @@ class RegisterSwooleMaintenanceTimersTest extends TestCase { + use VerifiesDoubles; + public function testRegistersEvictionAndIntervalRefreshTimersForEachSwooleStoreOnWorkerZero(): void { $config = $this->config([ @@ -50,23 +55,25 @@ public function testRegistersEvictionAndIntervalRefreshTimersForEachSwooleStoreO public function testDoesNotRegisterTimersOnOtherWorkers(): void { - $container = m::mock(Container::class); + $container = Double::for(Container::class, override: true); $timer = new FakeCoordinatorTimer; - (new RegisterSwooleMaintenanceTimers($container, $timer, $this->config([]))) + (new RegisterSwooleMaintenanceTimers($container->instance(), $timer, $this->config([]))) ->handle($this->workerEvent(workerId: 1)); + $container->unused(); $this->assertSame([], $timer->ticks); } public function testDoesNotRegisterTimersOnTaskWorkers(): void { - $container = m::mock(Container::class); + $container = Double::for(Container::class, override: true); $timer = new FakeCoordinatorTimer; - (new RegisterSwooleMaintenanceTimers($container, $timer, $this->config([]))) + (new RegisterSwooleMaintenanceTimers($container->instance(), $timer, $this->config([]))) ->handle($this->workerEvent(workerId: 0, taskworker: true)); + $container->unused(); $this->assertSame([], $timer->ticks); } @@ -80,22 +87,22 @@ public function testTimerCallbacksCallTheConfiguredStore(): void ], ]); - $store = m::mock(SwooleStore::class); - $store->shouldReceive('evictRecords')->once(); - $store->shouldReceive('refreshIntervalCaches')->once(); + $store = Double::for(SwooleStore::class); + $store->expects('evictRecords'); + $store->expects('refreshIntervalCaches'); - $repository = m::mock(); - $repository->shouldReceive('getStore')->once()->andReturn($store); + $repository = Double::for(CacheRepository::class); + $repository->expects('getStore')->returns($store); - $cache = m::mock(); - $cache->shouldReceive('store')->once()->with('fast')->andReturn($repository); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('fast')->returns($repository); - $container = m::mock(Container::class); - $container->shouldReceive('make')->once()->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true); + $container->expects('make')->with('cache')->returns($cache); $timer = new FakeCoordinatorTimer; - (new RegisterSwooleMaintenanceTimers($container, $timer, $config)) + (new RegisterSwooleMaintenanceTimers($container->instance(), $timer, $config)) ->handle($this->workerEvent(workerId: 0)); $timer->ticks[0]['callback'](); @@ -116,21 +123,21 @@ public function testResolvesEveryStoreBeforeRegisteringTimers(): void 'interval_refresh_interval' => 1000, ], ]); - $firstRepository = m::mock(); - $firstRepository->shouldReceive('getStore')->once()->andReturn(m::mock(SwooleStore::class)); + $firstRepository = Double::for(CacheRepository::class); + $firstRepository->expects('getStore')->returns(Double::for(SwooleStore::class)); $failure = new RuntimeException('Store resolution failed.'); - $cache = m::mock(); - $cache->shouldReceive('store')->once()->with('first')->andReturn($firstRepository); - $cache->shouldReceive('store')->once()->with('second')->andThrow($failure); + $cache = Double::for(CacheFactory::class); + $cache->expects('store')->with('first')->returns($firstRepository); + $cache->expects('store')->with('second')->throws($failure); - $container = m::mock(Container::class); - $container->shouldReceive('make')->twice()->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true); + $container->expects('make')->times(2)->with('cache')->returns($cache); $timer = new FakeCoordinatorTimer; try { - (new RegisterSwooleMaintenanceTimers($container, $timer, $config)) + (new RegisterSwooleMaintenanceTimers($container->instance(), $timer, $config)) ->handle($this->workerEvent(workerId: 0)); $this->fail('Expected store resolution to fail.'); @@ -240,11 +247,11 @@ public function testRejectsInvalidIntervalsBeforeTimerRegistration( ...$intervalConfig, ], ]); - $container = m::mock(Container::class); + $container = Double::for(Container::class, override: true); $timer = new FakeCoordinatorTimer; try { - (new RegisterSwooleMaintenanceTimers($container, $timer, $config)) + (new RegisterSwooleMaintenanceTimers($container->instance(), $timer, $config)) ->handle($this->workerEvent(workerId: 0)); $this->fail('Expected invalid timer configuration to fail.'); @@ -255,6 +262,7 @@ public function testRejectsInvalidIntervalsBeforeTimerRegistration( ); } + $container->unused(); $this->assertSame([], $timer->ticks); } @@ -311,11 +319,11 @@ public function testRejectsAnInvalidLaterStoreBeforeRegisteringEarlierTimers(): 'interval_refresh_interval' => 0, ], ]); - $container = m::mock(Container::class); + $container = Double::for(Container::class, override: true); $timer = new FakeCoordinatorTimer; try { - (new RegisterSwooleMaintenanceTimers($container, $timer, $config)) + (new RegisterSwooleMaintenanceTimers($container->instance(), $timer, $config)) ->handle($this->workerEvent(workerId: 0)); $this->fail('Expected invalid timer configuration to fail.'); @@ -326,6 +334,7 @@ public function testRejectsAnInvalidLaterStoreBeforeRegisteringEarlierTimers(): ); } + $container->unused(); $this->assertSame([], $timer->ticks); } @@ -346,23 +355,23 @@ private function config(array $stores): Repository */ private function containerWithSwooleStores(string ...$names): Container { - $cache = m::mock(); + $cache = Double::for(CacheFactory::class); foreach ($names as $name) { - $repository = m::mock(); - $repository->shouldReceive('getStore')->once()->andReturn(m::mock(SwooleStore::class)); - $cache->shouldReceive('store')->once()->with($name)->andReturn($repository); + $repository = Double::for(CacheRepository::class); + $repository->expects('getStore')->returns(Double::for(SwooleStore::class)); + $cache->expects('store')->with($name)->returns($repository); } - $container = m::mock(Container::class); - $container->shouldReceive('make')->times(count($names))->with('cache')->andReturn($cache); + $container = Double::for(Container::class, override: true); + $container->expects('make')->times(count($names))->with('cache')->returns($cache); - return $container; + return $container->instance(); } private function workerEvent(int $workerId, bool $taskworker = false): AfterWorkerStart { - $server = m::mock(SwooleServer::class); + $server = Double::for(SwooleServer::class); $server->taskworker = $taskworker; return new AfterWorkerStart($server, $workerId); diff --git a/tests/ConnectionPool/ConnectionPoolTest.php b/tests/ConnectionPool/ConnectionPoolTest.php index 338df33379..69342cef4b 100644 --- a/tests/ConnectionPool/ConnectionPoolTest.php +++ b/tests/ConnectionPool/ConnectionPoolTest.php @@ -22,7 +22,9 @@ use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; @@ -34,6 +36,8 @@ class ConnectionPoolTest extends TestCase { + use VerifiesDoubles; + public function testUnknownPoolOptionsAreRejected(): void { $this->expectException(InvalidArgumentException::class); @@ -210,10 +214,9 @@ public function testWarmPoolDoesNotScheduleMaintenanceUntilStarted(): void public function testCloseContinuesAfterMonitorCleanupFails(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error') - ->once() - ->with(m::on(static fn (string $message): bool => str_contains($message, 'monitor cleanup failed'))); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error') + ->with(Argument::satisfies(static fn (string $message): bool => str_contains($message, 'monitor cleanup failed'))); $container = $this->createContainer(); $container->instance(StdoutLoggerInterface::class, $logger); $pool = new CallbackPool($container, 'test'); @@ -221,9 +224,9 @@ public function testCloseContinuesAfterMonitorCleanupFails(): void $pool->replaceChannel($channel); $connection = $pool->borrow(); $pool->release($connection); - $timer = m::mock(Timer::class); - $timer->expects('tick')->with(1.0, m::type('callable'))->andReturn(1); - $timer->expects('clear')->with(1)->andThrow(new RuntimeException('monitor cleanup failed')); + $timer = Double::for(Timer::class); + $timer->expects('tick')->with(1.0, Argument::type('callable'))->returns(1); + $timer->expects('clear')->with(1)->throws(new RuntimeException('monitor cleanup failed')); $monitor = new IdleConnectionMonitor($pool, 1.0, $timer); $monitor->start(); (new ReflectionProperty(ConnectionPool::class, 'idleMonitor'))->setValue($pool, $monitor); @@ -684,10 +687,9 @@ static function () use (&$connections): Connection { public function testThrowingIdleCheckIsReportedDestroyedAndFreesCapacity(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error') - ->once() - ->with(m::on(static fn (string $message): bool => str_contains($message, 'check failed'))); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error') + ->with(Argument::satisfies(static fn (string $message): bool => str_contains($message, 'check failed'))); $container = $this->createContainer(); $container->instance(StdoutLoggerInterface::class, $logger); @@ -740,12 +742,12 @@ public function testCanceledIdleCheckDisposesOnceAndPreservesCancellation(?strin default => null, }; $container = $this->createContainer(); - $logger = m::mock(StdoutLoggerInterface::class); + $logger = Double::for(StdoutLoggerInterface::class); if ($cleanupFailure === 'failed') { - $logger->shouldReceive('error')->once()->with((string) $secondary); + $logger->expects('error')->with((string) $secondary); } else { - $logger->shouldNotReceive('error'); + $logger->expects('error')->never(); } $container->instance(StdoutLoggerInterface::class, $logger); @@ -821,15 +823,14 @@ public function testHealthyIdleConnectionIsDisposedWhenPoolClosesDuringCheck(): public function testUsageTrackerFailureIsReportedWithoutLosingBorrow(): void { - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error') - ->once() - ->with(m::on(static fn (string $message): bool => str_contains($message, 'recording failed'))); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error') + ->with(Argument::satisfies(static fn (string $message): bool => str_contains($message, 'recording failed'))); $container = $this->createContainer(); $container->instance(StdoutLoggerInterface::class, $logger); $pool = new CallbackPool($container, 'test'); - $tracker = m::mock(UsageTracker::class); - $tracker->shouldReceive('recordBorrow')->once()->andThrow(new RuntimeException('recording failed')); + $tracker = Double::for(UsageTracker::class); + $tracker->expects('recordBorrow')->throws(new RuntimeException('recording failed')); $pool->useUsageTracker($tracker); $connection = $pool->borrow(); @@ -888,9 +889,9 @@ public function shouldTrimExcessIdle(): bool public function testUsageTrackerFactoryRunsOnceAfterSubclassConstruction(): void { - $tracker = m::mock(UsageTracker::class); - $tracker->expects('recordBorrow')->twice(); - $tracker->expects('shouldTrimExcessIdle')->twice()->andReturnFalse(); + $tracker = Double::for(UsageTracker::class); + $tracker->expects('recordBorrow')->times(2); + $tracker->expects('shouldTrimExcessIdle')->times(2)->returns(false); $pool = new UsageTrackerPool($this->createContainer(), static fn () => $tracker); $this->assertSame(0, $pool->factoryCalls); @@ -1013,9 +1014,9 @@ public function trimExcessIdle(): void $this->close(); } }; - $tracker = m::mock(UsageTracker::class); + $tracker = Double::for(UsageTracker::class); $tracker->expects('recordBorrow'); - $tracker->expects('shouldTrimExcessIdle')->andReturnTrue(); + $tracker->expects('shouldTrimExcessIdle')->returns(true); $pool->useUsageTracker($tracker); $pool->start(); diff --git a/tests/ConnectionPool/ConnectionTest.php b/tests/ConnectionPool/ConnectionTest.php index efb5f6a02c..a670d564de 100644 --- a/tests/ConnectionPool/ConnectionTest.php +++ b/tests/ConnectionPool/ConnectionTest.php @@ -17,7 +17,9 @@ use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Tests\ConnectionPool\Fixtures\ActiveConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -27,16 +29,18 @@ class ConnectionTest extends TestCase { + use VerifiesDoubles; + public function testGetConnectionReturnsTheActiveConnection(): void { - $container = m::mock(ContainerContract::class); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldNotReceive('warning'); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnTrue(); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->once()->andReturn($logger); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); - - $connection = new ActiveConnectionStub($container, m::mock(ConnectionPool::class)); + $container = Double::for(ContainerContract::class, override: true); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('warning')->never(); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(true); + $container->expects('make')->with(StdoutLoggerInterface::class)->returns($logger); + $container->allows('bound')->with('events')->returns(false); + + $connection = new ActiveConnectionStub($container->instance(), Double::for(ConnectionPool::class)); $this->assertSame($connection, $connection->getConnection()); } @@ -44,15 +48,15 @@ public function testGetConnectionReturnsTheActiveConnection(): void public function testGetConnectionDoesNotRetryFailure(string $exceptionClass): void { $failure = new $exceptionClass('acquisition failed'); - $container = m::mock(ContainerContract::class); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldNotReceive('warning'); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnTrue(); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->once()->andReturn($logger); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); + $container = Double::for(ContainerContract::class, override: true); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('warning')->never(); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(true); + $container->expects('make')->with(StdoutLoggerInterface::class)->returns($logger); + $container->allows('bound')->with('events')->returns(false); $connection = new ConnectionCallbackStub( - $container, - m::mock(ConnectionPool::class), + $container->instance(), + Double::for(ConnectionPool::class), static fn (): mixed => throw $failure, ); $caught = null; @@ -78,15 +82,15 @@ public static function acquisitionFailures(): array public function testGetConnectionDoesNotRetryCancellation(): void { $cancellation = new CanceledException('connection canceled'); - $container = m::mock(ContainerContract::class); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('warning')->never(); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnTrue(); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->once()->andReturn($logger); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); + $container = Double::for(ContainerContract::class, override: true); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('warning')->never(); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(true); + $container->expects('make')->with(StdoutLoggerInterface::class)->returns($logger); + $container->allows('bound')->with('events')->returns(false); $connection = new ConnectionCallbackStub( - $container, - m::mock(ConnectionPool::class), + $container->instance(), + Double::for(ConnectionPool::class), static fn (): mixed => throw $cancellation, ); @@ -103,18 +107,18 @@ public function testGetConnectionDoesNotRetryCancellation(): void public function testConnectionReleasingEvent(): void { $assert = 0; - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher = m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->once()->with(ConnectionReleasing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(ConnectionReleasing::class)->andReturnUsing(function (ConnectionReleasing $event) use (&$assert) { + $container = Double::for(ContainerContract::class, override: true); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)); + $dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(ConnectionReleasing::class))->resolves(function (ConnectionReleasing $event) use (&$assert) { $assert = $event->connection->getLastReleaseTime(); }); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('release')->withAnyArgs()->andReturnNull(); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->allows('release')->returns(null); + $pool->allows('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); $before = hrtime(true) / 1e9; $connection->release(); @@ -127,15 +131,15 @@ public function testConnectionReleasingEvent(): void public function testReleaseUsesTheCurrentEventDispatcher(): void { $container = new Container; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->allows('hasListeners')->with(ConnectionReleasing::class)->andReturnTrue(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->with(ConnectionReleasing::class)->returns(true); + $dispatcher->expects('dispatch')->never(); $container->instance('events', $dispatcher); - $pool = m::mock(ConnectionPool::class); - $pool->expects('getOptions')->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool = Double::for(ConnectionPool::class); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); $connection = new ActiveConnectionStub($container, $pool); - $pool->expects('release')->with($connection); + $pool->expects('release')->with(Argument::same($connection)); $fake = new EventFake($dispatcher, [ConnectionReleasing::class]); $container->instance('events', $fake); @@ -150,15 +154,15 @@ public function testReleaseListenerCancellationStillReturnsTheConnectionOnce(boo { $cancellation = new CanceledException('listener canceled'); $failure = $cleanupThrows ? new RuntimeException('Listener cleanup failed.', previous: $cancellation) : $cancellation; - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher = m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->once()->with(ConnectionReleasing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow($failure); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->shouldReceive('release')->once()->with($connection); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)); + $dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true); + $dispatcher->expects('dispatch')->throws($failure); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::same($connection)); try { $connection->release(); @@ -175,15 +179,15 @@ public function testReleaseListenerCancellationRemainsPrimaryOverCleanupCancella $cancellation = new CanceledException('listener canceled'); $failure = $cleanupThrows ? new RuntimeException('Listener cleanup failed.', previous: $cancellation) : $cancellation; $cleanupCancellation = new CanceledException('release canceled'); - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher = m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->once()->with(ConnectionReleasing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow($failure); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->shouldReceive('release')->once()->with($connection)->andThrow($cleanupCancellation); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)); + $dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true); + $dispatcher->expects('dispatch')->throws($failure); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::same($connection))->throws($cleanupCancellation); try { $connection->release(); @@ -196,18 +200,18 @@ public function testReleaseListenerCancellationRemainsPrimaryOverCleanupCancella public function testCancellationWhileLoggingAListenerFailureStillReturnsTheConnectionOnce(): void { $cancellation = new CanceledException('logging canceled'); - $container = m::mock(ContainerContract::class); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error')->once()->andThrow($cancellation); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnTrue(); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->once()->andReturn($logger); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher = m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->once()->with(ConnectionReleasing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow(new RuntimeException('listener failed')); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->shouldReceive('release')->once()->with($connection); + $container = Double::for(ContainerContract::class, override: true); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->throws($cancellation); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(true); + $container->expects('make')->with(StdoutLoggerInterface::class)->returns($logger); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)); + $dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true); + $dispatcher->expects('dispatch')->throws(new RuntimeException('listener failed')); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::same($connection)); try { $connection->release(); @@ -219,24 +223,21 @@ public function testCancellationWhileLoggingAListenerFailureStillReturnsTheConne public function testOrdinaryReleaseListenerFailureIsLoggedAndTheConnectionIsReturned(): void { - $container = m::mock(ContainerContract::class); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error') - ->once() - ->with(m::on(static fn (string $message): bool => str_contains($message, 'listener failed'))); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnTrue(); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->once()->andReturn($logger); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher = m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->once()->with(ConnectionReleasing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow(new RuntimeException('listener failed')); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->shouldReceive('release')->once()->with($connection); + $container = Double::for(ContainerContract::class, override: true); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error') + ->with(Argument::satisfies(static fn (string $message): bool => str_contains($message, 'listener failed'))); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(true); + $container->expects('make')->with(StdoutLoggerInterface::class)->returns($logger); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)); + $dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true); + $dispatcher->expects('dispatch')->throws(new RuntimeException('listener failed')); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::same($connection)); $connection->release(); - - $this->addToAssertionCount(1); } #[DataProvider('cleanupFailures')] @@ -244,18 +245,18 @@ public function testLoggerFailureStillReleasesTheConnectionAndPreservesFailurePr { $loggingFailure = new RuntimeException('logger failed'); $cleanupFailure = $cleanupExceptionClass === null ? null : new $cleanupExceptionClass('cleanup failed'); - $container = m::mock(ContainerContract::class); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error')->once()->andThrow($loggingFailure); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnTrue(); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->once()->andReturn($logger); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher = m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->once()->with(ConnectionReleasing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow(new RuntimeException('listener failed')); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->shouldReceive('release')->once()->with($connection)->andReturnUsing(static function () use ($cleanupFailure): void { + $container = Double::for(ContainerContract::class, override: true); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->throws($loggingFailure); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(true); + $container->expects('make')->with(StdoutLoggerInterface::class)->returns($logger); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)); + $dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true); + $dispatcher->expects('dispatch')->throws(new RuntimeException('listener failed')); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::same($connection))->resolves(static function () use ($cleanupFailure): void { if ($cleanupFailure !== null) { throw $cleanupFailure; } @@ -284,18 +285,18 @@ public static function cleanupFailures(): array public function testReleaseCancellationSurvivesCleanupAndReportingFailures(string $reportingExceptionClass): void { $cancellation = new CanceledException('listener canceled'); - $container = m::mock(ContainerContract::class); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('error')->once()->andThrow(new $reportingExceptionClass('secondary reporting failed')); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnTrue(); - $container->shouldReceive('make')->with(StdoutLoggerInterface::class)->once()->andReturn($logger); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher = m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->once()->with(ConnectionReleasing::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow($cancellation); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->shouldReceive('release')->once()->with($connection)->andThrow(new RuntimeException('cleanup failed')); + $container = Double::for(ContainerContract::class, override: true); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->throws(new $reportingExceptionClass('secondary reporting failed')); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(true); + $container->expects('make')->with(StdoutLoggerInterface::class)->returns($logger); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)); + $dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true); + $dispatcher->expects('dispatch')->throws($cancellation); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::same($connection))->throws(new RuntimeException('cleanup failed')); $caught = null; try { @@ -317,60 +318,54 @@ public static function secondaryReportingFailures(): array public function testConfiguredReleaseEventIsNotDispatchedWithoutListeners(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); - $container->shouldReceive('bound')->with('events')->andReturnTrue(); - $container->shouldReceive('make')->with('events')->andReturn($dispatcher = m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->once()->with(ConnectionReleasing::class)->andReturnFalse(); - $dispatcher->shouldReceive('dispatch')->never(); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); - $pool->shouldReceive('release')->once()->with($connection); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->allows('bound')->with('events')->returns(true); + $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)); + $dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(false); + $dispatcher->expects('dispatch')->never(); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]])); + $pool->expects('release')->with(Argument::same($connection)); $connection->release(); - - $this->addToAssertionCount(1); } public function testDontHaveEvents(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); - $container->shouldNotReceive('bound')->with('events'); - $container->shouldNotReceive('make')->with('events'); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->expects('bound')->never()->with('events'); + $container->expects('make')->never()->with('events'); - $connection = new ActiveConnectionStub($container, $pool = m::mock(ConnectionPool::class)); - $pool->shouldReceive('release')->withAnyArgs()->andReturnNull(); - $pool->shouldReceive('getOptions')->andReturn(PoolOptions::fromArray([])); + $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)); + $pool->allows('release')->returns(null); + $pool->allows('getOptions')->returns(PoolOptions::fromArray([])); $connection->release(); - - $this->assertTrue(true); } public function testDiscardDelegatesToOwningPool(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); - $pool = m::mock(ConnectionPool::class); - $connection = new ActiveConnectionStub($container, $pool); - $pool->shouldReceive('discard')->once()->with($connection); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->allows('bound')->with('events')->returns(false); + $pool = Double::for(ConnectionPool::class); + $connection = new ActiveConnectionStub($container->instance(), $pool); + $pool->expects('discard')->with(Argument::same($connection)); $connection->discard(); - - $this->addToAssertionCount(1); } public function testCheckDoesNotResetActivityTimestamp(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('release')->once(); - $pool->shouldReceive('getOptions')->twice()->andReturn(PoolOptions::fromArray(['max_idle_time' => 60.0])); - $connection = new ActiveConnectionStub($container, $pool); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->allows('bound')->with('events')->returns(false); + $pool = Double::for(ConnectionPool::class); + $pool->expects('release'); + $pool->expects('getOptions')->times(2)->returns(PoolOptions::fromArray(['max_idle_time' => 60.0])); + $connection = new ActiveConnectionStub($container->instance(), $pool); $connection->release(); $lastUseTime = $connection->getLastUseTime(); @@ -381,12 +376,12 @@ public function testCheckDoesNotResetActivityTimestamp(): void public function testNullIdleTimeoutKeepsAnUnusedConnectionValid(): void { - $container = m::mock(ContainerContract::class); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); - $container->shouldReceive('bound')->with('events')->andReturnFalse(); - $pool = m::mock(ConnectionPool::class); - $pool->shouldReceive('getOptions')->once()->andReturn(PoolOptions::fromArray(['max_idle_time' => null])); - $connection = new ActiveConnectionStub($container, $pool); + $container = Double::for(ContainerContract::class, override: true); + $container->expects('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->allows('bound')->with('events')->returns(false); + $pool = Double::for(ConnectionPool::class); + $pool->expects('getOptions')->returns(PoolOptions::fromArray(['max_idle_time' => null])); + $connection = new ActiveConnectionStub($container->instance(), $pool); $this->assertTrue($connection->check()); $this->assertSame(0.0, $connection->getLastUseTime()); diff --git a/tests/ConnectionPool/Fixtures/FooPool.php b/tests/ConnectionPool/Fixtures/FooPool.php index 8146224579..465f914617 100644 --- a/tests/ConnectionPool/Fixtures/FooPool.php +++ b/tests/ConnectionPool/Fixtures/FooPool.php @@ -6,12 +6,12 @@ use Hypervel\ConnectionPool\ConnectionPool; use Hypervel\Contracts\ConnectionPool\Connection; -use Mockery as m; +use JMac\Testing\Double; class FooPool extends ConnectionPool { protected function createConnection(): Connection { - return m::mock(Connection::class); + return Double::for(Connection::class); } } diff --git a/tests/ConnectionPool/IdleConnectionMonitorTest.php b/tests/ConnectionPool/IdleConnectionMonitorTest.php index 91e553466f..69dced08de 100644 --- a/tests/ConnectionPool/IdleConnectionMonitorTest.php +++ b/tests/ConnectionPool/IdleConnectionMonitorTest.php @@ -14,17 +14,21 @@ use Hypervel\Tests\ConnectionPool\Fixtures\FooPool; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; class IdleConnectionMonitorTest extends TestCase { + use VerifiesDoubles; + public function testMonitorChecksIdleConnectionsAtItsInterval(): void { - $pool = m::mock(ConnectionPool::class); - $pool->allows('isClosed')->andReturnFalse(); - $pool->shouldReceive('checkIdleConnection')->atLeast()->once(); + $pool = Double::for(ConnectionPool::class); + $pool->allows('isClosed')->returns(false); + $pool->expects('checkIdleConnection')->times(minimum: 1); $timerCount = Timer::stats()['num']; $monitor = new IdleConnectionMonitor($pool, 0.001); @@ -42,10 +46,10 @@ public function testMonitorChecksIdleConnectionsAtItsInterval(): void public function testStartAndStopAreIdempotentAndPermitRestart(): void { - $pool = m::mock(ConnectionPool::class); - $pool->allows('isClosed')->andReturnFalse(); - $timer = m::mock(Timer::class); - $timer->expects('tick')->with(5.0, m::type('callable'))->twice()->andReturn(1, 2); + $pool = Double::for(ConnectionPool::class); + $pool->allows('isClosed')->returns(false); + $timer = Double::for(Timer::class); + $timer->expects('tick')->with(5.0, Argument::type('callable'))->times(2)->returns(1, 2); $timer->expects('clear')->with(1); $timer->expects('clear')->with(2); $monitor = new IdleConnectionMonitor($pool, 5.0, $timer); @@ -60,18 +64,18 @@ public function testStartAndStopAreIdempotentAndPermitRestart(): void public function testClosedPoolCannotStartAMonitor(): void { - $pool = m::mock(ConnectionPool::class); - $pool->allows('isClosed')->andReturnTrue(); - $timer = m::mock(Timer::class); - $timer->shouldNotReceive('tick'); + $pool = Double::for(ConnectionPool::class); + $pool->allows('isClosed')->returns(true); + $timer = Double::for(Timer::class); + $timer->expects('tick')->never(); (new IdleConnectionMonitor($pool, 1.0, $timer))->start(); } public function testSynchronousStartupReentryDoesNotCreateAnotherTimer(): void { - $pool = m::mock(ConnectionPool::class); - $pool->allows('isClosed')->andReturnFalse(); + $pool = Double::for(ConnectionPool::class); + $pool->allows('isClosed')->returns(false); $monitor = new IdleConnectionMonitor($pool, 60.0); $timerCount = Timer::stats()['num']; $startupCalls = 0; @@ -113,12 +117,20 @@ public function testCloseDuringStartupClearsTheUnpublishedTimer(): void public function testStartupFailureAllowsTheNextStart(): void { - $pool = m::mock(ConnectionPool::class); - $pool->allows('isClosed')->andReturnFalse(); + $pool = Double::for(ConnectionPool::class); + $pool->allows('isClosed')->returns(false); $failure = new RuntimeException('timer creation failed'); - $timer = m::mock(Timer::class); - $timer->expects('tick')->with(1.0, m::type('callable'))->ordered()->andThrow($failure); - $timer->expects('tick')->with(1.0, m::type('callable'))->ordered()->andReturn(1); + $timer = Double::for(Timer::class); + $attempts = 0; + $timer->expects('tick')->with(1.0, Argument::type('callable'))->times(2)->resolves( + static function () use (&$attempts, $failure): int { + if (++$attempts === 1) { + throw $failure; + } + + return 1; + }, + ); $timer->expects('clear')->with(1); $monitor = new IdleConnectionMonitor($pool, 1.0, $timer); $caught = null; @@ -136,9 +148,9 @@ public function testStartupFailureAllowsTheNextStart(): void public function testWorkerExitStopsWithoutCheckingIdleConnections(): void { - $pool = m::mock(ConnectionPool::class); - $pool->allows('isClosed')->andReturnFalse(); - $pool->shouldNotReceive('checkIdleConnection'); + $pool = Double::for(ConnectionPool::class); + $pool->allows('isClosed')->returns(false); + $pool->expects('checkIdleConnection')->never(); $monitor = new IdleConnectionMonitor($pool, 60.0); $timerCount = Timer::stats()['num']; @@ -154,8 +166,8 @@ public function testWorkerExitStopsWithoutCheckingIdleConnections(): void public function testEachMonitorOwnsItsTimer(): void { - $pool = m::mock(ConnectionPool::class); - $pool->allows('isClosed')->andReturnFalse(); + $pool = Double::for(ConnectionPool::class); + $pool->allows('isClosed')->returns(false); $first = new IdleConnectionMonitor($pool, 60.0); $second = new IdleConnectionMonitor($pool, 60.0); $timerCount = Timer::stats()['num']; @@ -180,15 +192,24 @@ public function testEachTickChecksOneIdleConnectionInFifoOrder(): void $pool = new FooPool(new Container, 'test', ['min_retained_connections' => 2]); $first = $pool->borrow(); $second = $pool->borrow(); - $first->expects('check')->once()->globally()->ordered()->andReturnTrue(); - $second->expects('check')->once()->globally()->ordered()->andReturnFalse(); + $checked = []; + $first->expects('check')->resolves(static function () use (&$checked): bool { + $checked[] = 'first'; + + return true; + }); + $second->expects('check')->resolves(static function () use (&$checked): bool { + $checked[] = 'second'; + + return false; + }); $first->expects('close'); $second->expects('close'); $pool->release($first); $pool->release($second); $callback = null; - $timer = m::mock(Timer::class); - $timer->expects('tick')->with(1.0, m::type('callable'))->andReturnUsing( + $timer = Double::for(Timer::class); + $timer->expects('tick')->with(1.0, Argument::type('callable'))->resolves( static function (float $interval, callable $check) use (&$callback): int { $callback = $check; @@ -204,6 +225,7 @@ static function (float $interval, callable $check) use (&$callback): int { $this->assertSame(2, $pool->getIdleCount()); $callback(false); + $this->assertSame(['first', 'second'], $checked); $this->assertSame(1, $pool->getManagedCount()); $this->assertSame(1, $pool->getIdleCount()); } finally { @@ -217,7 +239,7 @@ public function testInvalidIntervalsAreRejected(float $interval): void { $this->expectException(InvalidArgumentException::class); - new IdleConnectionMonitor(m::mock(ConnectionPool::class), $interval); + new IdleConnectionMonitor(Double::for(ConnectionPool::class), $interval); } public static function invalidIntervals(): array diff --git a/tests/ConnectionPool/KeepaliveConnectionTest.php b/tests/ConnectionPool/KeepaliveConnectionTest.php index 9225cc27bb..e1787cdc82 100644 --- a/tests/ConnectionPool/KeepaliveConnectionTest.php +++ b/tests/ConnectionPool/KeepaliveConnectionTest.php @@ -21,7 +21,9 @@ use Hypervel\Tests\ConnectionPool\Fixtures\HeartbeatPoolStub; use Hypervel\Tests\ConnectionPool\Fixtures\KeepaliveConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use RuntimeException; @@ -31,6 +33,8 @@ class KeepaliveConnectionTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { CoroutineContext::set('test.pool.heartbeat_connection', []); @@ -61,13 +65,13 @@ public function testConnectionConstruct(): void public function testConnectionAcceptsPoolContract(): void { - $pool = m::mock(ConnectionPool::class); + $pool = Double::for(ConnectionPool::class); $connection = new KeepaliveConnectionStub( - m::mock(ContainerContract::class), + new Container, $pool, ); - $pool->shouldReceive('release')->once()->with($connection); + $pool->expects('release')->with(Argument::same($connection)); $connection->release(); } @@ -220,7 +224,6 @@ public function testHeartbeatFailureFallsBackToThePhpErrorLogWithoutALogger(): v try { $container = $this->getContainer(['heartbeat_interval' => 0.001]); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->once()->andReturnFalse(); $pool = $container->make(HeartbeatPoolStub::class); /** @var KeepaliveConnectionStub $connection */ $connection = $pool->borrow(); @@ -398,15 +401,15 @@ public function testSupersededHolderCannotRequeueOrRefreshTheReplacement(): void public function testConcurrentReconnectKeepsOneSocketAndOneTimer(?Throwable $closeFailure): void { $container = new Container; - $logger = m::mock(StdoutLoggerInterface::class); + $logger = Double::for(StdoutLoggerInterface::class); $container->instance(StdoutLoggerInterface::class, $logger); if ($closeFailure !== null && ! $closeFailure instanceof CanceledException) { - $logger->shouldReceive('error')->once()->with(m::on( + $logger->expects('error')->with(Argument::satisfies( static fn (string $message): bool => str_contains($message, $closeFailure->getMessage()), )); } else { - $logger->shouldNotReceive('error'); + $logger->expects('error')->never(); } $pool = new HeartbeatPoolStub($container, 'test', ['heartbeat_interval' => 3600.0]); @@ -762,22 +765,22 @@ public function testReconnectPublishesIfAnEarlierWinnerHasAlreadyClosed(): void public function testHeartbeatCancellationRemainsPrimaryWhenProtocolCloseFails(): void { $container = new Container; - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldNotReceive('error'); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('error')->never(); $container->instance(StdoutLoggerInterface::class, $logger); $pool = new HeartbeatPoolStub($container, 'test', ['heartbeat_interval' => 3600.0]); $connection = $pool->borrow(); $connection->setActiveConnection(new stdClass); $callback = null; - $timer = m::mock(Timer::class); - $timer->shouldReceive('tick')->once()->andReturnUsing( + $timer = Double::for(Timer::class); + $timer->expects('tick')->resolves( function (float $interval, callable $heartbeat) use (&$callback): int { $callback = $heartbeat; return 1; }, ); - $timer->shouldReceive('clear')->once()->with(1); + $timer->expects('clear')->with(1); $connection->timer = $timer; $cancellation = new CanceledException('heartbeat canceled'); $connection->heartbeatFailure = $cancellation; @@ -805,13 +808,13 @@ function (float $interval, callable $heartbeat) use (&$callback): int { public function testLateHeartbeatFailureDoesNotCloseTheReplacement(Throwable $failure): void { $container = new Container; - $logger = m::mock(StdoutLoggerInterface::class); + $logger = Double::for(StdoutLoggerInterface::class); $container->instance(StdoutLoggerInterface::class, $logger); if ($failure instanceof CanceledException) { - $logger->shouldNotReceive('error'); + $logger->expects('error')->never(); } else { - $logger->shouldReceive('error')->once()->with(m::on( + $logger->expects('error')->with(Argument::satisfies( static fn (string $message): bool => str_contains($message, $failure->getMessage()), )); } @@ -824,15 +827,15 @@ public function testLateHeartbeatFailureDoesNotCloseTheReplacement(Throwable $fa $connection->createCallback = static fn () => new stdClass; $callbacks = []; $cleared = []; - $timer = m::mock(Timer::class); - $timer->shouldReceive('tick')->twice()->andReturnUsing( + $timer = Double::for(Timer::class); + $timer->expects('tick')->times(2)->resolves( function (float $interval, callable $heartbeat) use (&$callbacks): int { $callbacks[] = $heartbeat; return count($callbacks); }, ); - $timer->shouldReceive('clear')->andReturnUsing(function (int $id) use (&$cleared): void { + $timer->allows('clear')->resolves(function (int $id) use (&$cleared): void { $cleared[] = $id; }); $connection->timer = $timer; @@ -887,12 +890,9 @@ public static function heartbeatFailures(): array protected function getContainer(array $poolConfig = []): ContainerContract { - $container = m::mock(Container::class); + $container = new Container; Container::setInstance($container); - - $container->shouldReceive('make')->with(HeartbeatPoolStub::class)->andReturnUsing(function () use ($container, $poolConfig) { - return new HeartbeatPoolStub($container, 'test', $poolConfig); - }); + $container->bind(HeartbeatPoolStub::class, fn () => new HeartbeatPoolStub($container, 'test', $poolConfig)); return $container; } diff --git a/tests/Console/Concerns/InteractsWithIOTest.php b/tests/Console/Concerns/InteractsWithIOTest.php index 4640ed6ad1..d03fbb981e 100755 --- a/tests/Console/Concerns/InteractsWithIOTest.php +++ b/tests/Console/Concerns/InteractsWithIOTest.php @@ -9,7 +9,9 @@ use Hypervel\Console\Concerns\InteractsWithIO; use Hypervel\Console\OutputStyle; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\ArgvInput; @@ -18,6 +20,8 @@ class InteractsWithIOTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('iterableDataProvider')] public function testWithProgressBarIterable(array $iterable): void { @@ -70,7 +74,7 @@ public function testWithProgressBarSupportsGeneratorsWithoutPrecounting(): void { $command = new CommandInteractsWithIO; $bufferedOutput = new BufferedOutput; - $output = m::mock(OutputStyle::class, [new ArgvInput, $bufferedOutput])->makePartial(); + $output = Double::for(new OutputStyle(new ArgvInput, $bufferedOutput))->passthru(); $command->setOutput($output); $generator = (function () { @@ -78,10 +82,9 @@ public function testWithProgressBarSupportsGeneratorsWithoutPrecounting(): void yield 'second' => 'b'; })(); - $output->shouldReceive('createProgressBar') - ->once() + $output->expects('createProgressBar') ->with(0) - ->andReturnUsing(fn (int $steps): ProgressBar => new ProgressBar($bufferedOutput, $steps)); + ->resolves(fn (int $steps): ProgressBar => new ProgressBar($bufferedOutput, $steps)); $values = []; $result = $command->withProgressBar($generator, function (string $value, ProgressBar $bar, string $key) use (&$values): void { @@ -96,7 +99,7 @@ public function testWithProgressBarSupportsGeneratorsWithoutPrecounting(): void public function testAskWithCompletionAcceptsGeneratorValues(): void { $command = new CommandInteractsWithIO; - $output = m::mock(OutputStyle::class); + $output = Double::for(OutputStyle::class); $command->setOutput($output); $choices = (function () { @@ -104,14 +107,13 @@ public function testAskWithCompletionAcceptsGeneratorValues(): void yield 'bravo'; })(); - $output->shouldReceive('askQuestion') - ->once() - ->with(m::on(function (Question $question): bool { + $output->expects('askQuestion') + ->with(Argument::satisfies(function (Question $question): bool { $this->assertSame(['alpha', 'bravo'], $question->getAutocompleterValues()); return true; })) - ->andReturn('bravo'); + ->returns('bravo'); $this->assertSame('bravo', $command->anticipate('Choose', $choices)); } diff --git a/tests/Console/ConfiguresPromptsTest.php b/tests/Console/ConfiguresPromptsTest.php index 864099af35..dbb919aaa4 100644 --- a/tests/Console/ConfiguresPromptsTest.php +++ b/tests/Console/ConfiguresPromptsTest.php @@ -16,7 +16,10 @@ use Hypervel\Prompts\TextPrompt; use Hypervel\Support\Facades\Artisan; use Hypervel\Testbench\TestCase; -use Mockery as m; +use Hypervel\Tests\Console\Fixtures\ComponentsFactory; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionMethod; @@ -40,6 +43,8 @@ class ConfiguresPromptsTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('selectDataProvider')] public function testSelectFallback(Closure $prompt, string $answer, string|int $expectedReturn): void { @@ -104,7 +109,7 @@ function ($components) { $components ->expects('ask') ->with('How many?', null) - ->andReturn('0'); + ->returns('0'); $components ->expects('error') ->with('Must be at least 1'); @@ -132,22 +137,22 @@ public static function fallbackTransformDataProvider(): array return [ 'text' => [ fn () => text('Test', transform: fn (string $value): string => $value . '!'), - fn ($components) => $components->expects('ask')->with('Test', null)->andReturn('value'), + fn ($components) => $components->expects('ask')->with('Test', null)->returns('value'), 'value!', ], 'textarea' => [ fn () => textarea('Test', transform: fn (string $value): string => $value . '!'), - fn ($components) => $components->expects('ask')->with('Test', null, multiline: true)->andReturn('value'), + fn ($components) => $components->expects('ask')->with('Test', null, true)->returns('value'), 'value!', ], 'number' => [ fn () => number('Test', transform: fn (int $value): int => $value + 1), - fn ($components) => $components->expects('ask')->with('Test', null)->andReturn('1'), + fn ($components) => $components->expects('ask')->with('Test', null)->returns('1'), 2, ], 'password' => [ fn () => password('Test', transform: fn (string $value): string => $value . '!'), - fn ($components) => $components->expects('secret')->with('Test')->andReturn('value'), + fn ($components) => $components->expects('secret')->with('Test')->returns('value'), 'value!', ], 'pause' => [ @@ -157,52 +162,52 @@ function (): bool { return $prompt->prompt(); }, - fn ($components) => $components->expects('ask')->with('Test')->andReturnNull(), + fn ($components) => $components->expects('ask')->with('Test')->returns(null), true, ], 'confirm' => [ fn () => confirm('Test', transform: fn (bool $value): bool => ! $value), - fn ($components) => $components->expects('confirm')->with('Test', true)->andReturnTrue(), + fn ($components) => $components->expects('confirm')->with('Test', true)->returns(true), false, ], 'select' => [ fn () => select('Test', ['a'], transform: fn (string $value): string => $value . '!'), - fn ($components) => $components->expects('choice')->with('Test', ['a'], null)->andReturn('a'), + fn ($components) => $components->expects('choice')->with('Test', ['a'], null)->returns('a'), 'a!', ], 'multiselect' => [ fn () => multiselect('Test', ['a'], transform: fn (array $values): array => [...$values, 'b']), - fn ($components) => $components->expects('choice')->with('Test', ['None', 'a'], 'None', null, true)->andReturn(['a']), + fn ($components) => $components->expects('choice')->with('Test', ['None', 'a'], 'None', null, true)->returns(['a']), ['a', 'b'], ], 'datatable' => [ fn () => datatable(['Name'], [['Taylor']], label: 'Test', transform: fn (int $value): string => "row-{$value}"), - fn ($components) => $components->expects('choice')->with('Test', [1 => '1: Name: Taylor'])->andReturn('1'), + fn ($components) => $components->expects('choice')->with('Test', [1 => '1: Name: Taylor'])->returns('1'), 'row-0', ], 'suggest' => [ fn () => suggest('Test', ['value'], transform: fn (string $value): string => $value . '!'), - fn ($components) => $components->expects('askWithCompletion')->with('Test', ['value'], null)->andReturn('value'), + fn ($components) => $components->expects('askWithCompletion')->with('Test', ['value'], null)->returns('value'), 'value!', ], 'autocomplete' => [ fn () => autocomplete('Test', ['value'], transform: fn (string $value): string => $value . '!'), - fn ($components) => $components->expects('askWithCompletion')->with('Test', ['value'], null)->andReturn('value'), + fn ($components) => $components->expects('askWithCompletion')->with('Test', ['value'], null)->returns('value'), 'value!', ], 'search' => [ fn () => search('Test', fn (): array => ['a'], transform: fn (string $value): string => $value . '!'), function ($components): void { - $components->expects('ask')->with('Test')->andReturn('query'); - $components->expects('choice')->with('Test', ['a'], null)->andReturn('a'); + $components->expects('ask')->with('Test')->returns('query'); + $components->expects('choice')->with('Test', ['a'], null)->returns('a'); }, 'a!', ], 'multisearch' => [ fn () => multisearch('Test', fn (): array => ['a'], transform: fn (array $values): array => [...$values, 'b']), function ($components): void { - $components->expects('ask')->with('Test')->andReturn('query'); - $components->expects('choice')->with('Test', ['None', 'a'], 'None', null, true)->andReturn(['a']); + $components->expects('ask')->with('Test')->returns('query'); + $components->expects('choice')->with('Test', ['None', 'a'], 'None', null, true)->returns(['a']); }, ['a', 'b'], ], @@ -222,22 +227,22 @@ public static function zeroDefaultDataProvider(): array return [ 'text' => [ fn () => text('Test', default: '0'), - fn ($components) => $components->expects('ask')->with('Test', '0')->andReturn('answer'), + fn ($components) => $components->expects('ask')->with('Test', '0')->returns('answer'), 'answer', ], 'textarea' => [ fn () => textarea('Test', default: '0'), - fn ($components) => $components->expects('ask')->with('Test', '0', multiline: true)->andReturn('answer'), + fn ($components) => $components->expects('ask')->with('Test', '0', true)->returns('answer'), 'answer', ], 'suggest' => [ fn () => suggest('Test', ['answer'], default: '0'), - fn ($components) => $components->expects('askWithCompletion')->with('Test', ['answer'], '0')->andReturn('answer'), + fn ($components) => $components->expects('askWithCompletion')->with('Test', ['answer'], '0')->returns('answer'), 'answer', ], 'autocomplete' => [ fn () => autocomplete('Test', ['answer'], default: '0'), - fn ($components) => $components->expects('askWithCompletion')->with('Test', ['answer'], '0')->andReturn('answer'), + fn ($components) => $components->expects('askWithCompletion')->with('Test', ['answer'], '0')->returns('answer'), 'answer', ], ]; @@ -274,7 +279,7 @@ protected function validatePrompt(mixed $value, mixed $rules): ?string $this->runCommand( $command, - fn ($components) => $components->expects('ask')->with('Test', null)->andReturn('value'), + fn ($components) => $components->expects('ask')->with('Test', null)->returns('value'), ); $this->assertSame('value!', $command->answer); @@ -305,7 +310,7 @@ protected function validatePrompt(mixed $value, mixed $rules): ?string $status = $this->runCommand( $command, function ($components): void { - $components->expects('ask')->with('Test', null)->andReturn('0'); + $components->expects('ask')->with('Test', null)->returns('0'); $components->expects('error')->with('Must be at least 1'); }, runningUnitTests: true, @@ -345,7 +350,7 @@ public function testFallbackRejectsInvalidValidatorResults(mixed $result): void $this->runPrompt( fn () => text('Test', validate: fn (): mixed => $result), - fn ($components) => $components->expects('ask')->with('Test', null)->andReturn('value'), + fn ($components) => $components->expects('ask')->with('Test', null)->returns('value'), ); } @@ -428,7 +433,7 @@ public function testAutoCompleteFallbackWithArrayOptions(): void fn ($components) => $components ->expects('askWithCompletion') ->with('Color?', ['Red', 'Blue'], 'Red') - ->andReturn('Blue') + ->returns('Blue') ); $this->assertSame('Blue', $answer); @@ -445,13 +450,13 @@ public function testAutoCompleteFallbackNormalizesClosureCollectionOptions(): vo ])), fn ($components) => $components ->expects('askWithCompletion') - ->with('File?', m::on(function ($completion) { + ->with('File?', Argument::satisfies(function ($completion) { $this->assertIsCallable($completion); $this->assertSame(['app/Models/User.php', 'app/Http/Kernel.php'], $completion('app')); return true; }), null) - ->andReturn('app/Models/User.php') + ->returns('app/Models/User.php') ); $this->assertSame('app/Models/User.php', $answer); @@ -468,13 +473,13 @@ public function testSuggestFallbackNormalizesClosureCollectionOptions(): void ])), fn ($components) => $components ->expects('askWithCompletion') - ->with('Name?', m::on(function ($completion) { + ->with('Name?', Argument::satisfies(function ($completion) { $this->assertIsCallable($completion); $this->assertSame(['T Taylor', 'T Jess'], $completion('T')); return true; }), null) - ->andReturn('T Taylor') + ->returns('T Taylor') ); $this->assertSame('T Taylor', $answer); @@ -490,7 +495,7 @@ public function testDataTableFallbackReturnsOriginalKeys(Closure $prompt, array fn ($components) => $components ->expects('choice') ->with('Pick', $expectedChoices) - ->andReturn($return) + ->returns($return) ); $this->assertSame($expectedReturn, $answer); @@ -671,18 +676,18 @@ public function handle(): void */ protected function runCommand(Command $command, Closure $expectations, bool $runningUnitTests = false): int { - $application = m::mock(Application::class); - $command->setHypervel($application); + $application = Double::for(Application::class, override: true); + $command->setHypervel($application->instance()); $input = new ArrayInput([]); $output = new NullOutput; $outputStyle = new OutputStyle($input, $output); - $application->expects('make')->withArgs(fn (string $abstract): bool => $abstract === OutputStyle::class)->andReturn($outputStyle); - $factory = m::mock(Factory::class); - $application->expects('make')->withArgs(fn (string $abstract): bool => $abstract === Factory::class)->andReturn($factory); - $application->shouldReceive('bound')->andReturn(false); - $application->shouldReceive('runningUnitTests')->andReturn($runningUnitTests); - $application->expects('call')->with([$command, 'handle'])->andReturnUsing(fn (callable $callback): mixed => call_user_func($callback)); + $application->expects('make')->with(OutputStyle::class, Argument::remaining())->returns($outputStyle); + $factory = Double::for(ComponentsFactory::class); + $application->expects('make')->with(Factory::class, Argument::remaining())->returns($factory); + $application->allows('bound')->returns(false); + $application->allows('runningUnitTests')->returns($runningUnitTests); + $application->expects('call')->with(Argument::same([$command, 'handle']))->resolves(fn (callable $callback): mixed => call_user_func($callback)); $expectations($factory); diff --git a/tests/Console/ConsoleApplicationDeferredCallbacksTest.php b/tests/Console/ConsoleApplicationDeferredCallbacksTest.php index 673be77d63..bfc04c68c0 100644 --- a/tests/Console/ConsoleApplicationDeferredCallbacksTest.php +++ b/tests/Console/ConsoleApplicationDeferredCallbacksTest.php @@ -15,7 +15,8 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Support\Defer\DeferredCallbackCollection; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -28,6 +29,8 @@ class ConsoleApplicationDeferredCallbacksTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testPassiveObserverDoesNotCauseArtisanStartingEventToDispatch(): void @@ -50,13 +53,13 @@ public function testCoroutineCommandDrainsAfterObserversAndMutexCleanup(): void { $application = $this->createConsoleApplication(); $calls = []; - $mutex = m::mock(CommandMutex::class); - $mutex->shouldReceive('create')->once()->andReturnUsing(function () use (&$calls): bool { + $mutex = Double::for(CommandMutex::class); + $mutex->expects('create')->resolves(function () use (&$calls): bool { $calls[] = 'mutex-created'; return true; }); - $mutex->shouldReceive('forget')->once()->andReturnUsing(function () use (&$calls): bool { + $mutex->expects('forget')->resolves(function () use (&$calls): bool { $calls[] = 'mutex-released'; return true; diff --git a/tests/Console/Events/EventsTest.php b/tests/Console/Events/EventsTest.php index 82525b02d7..ddf25896e5 100644 --- a/tests/Console/Events/EventsTest.php +++ b/tests/Console/Events/EventsTest.php @@ -20,16 +20,19 @@ use Hypervel\Console\Scheduling\Event; use Hypervel\Console\Scheduling\EventMutex; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class EventsTest extends TestCase { + use VerifiesDoubles; + public function testArtisanStartingCarriesApplication(): void { - $app = m::mock(Application::class); + $app = Double::for(Application::class); $event = new ArtisanStarting($app); @@ -70,7 +73,7 @@ public function testCommandFinishedCarriesNonZeroExitCode(): void public function testBeforeHandleCarriesCommandAndInput(): void { - $command = m::mock(Command::class); + $command = Double::for(Command::class); $input = new ArrayInput([]); $event = new BeforeHandle($command, $input); @@ -81,7 +84,7 @@ public function testBeforeHandleCarriesCommandAndInput(): void public function testAfterHandleCarriesCommand(): void { - $command = m::mock(Command::class); + $command = Double::for(Command::class); $event = new AfterHandle($command); @@ -90,7 +93,7 @@ public function testAfterHandleCarriesCommand(): void public function testAfterExecuteCarriesExecutionData(): void { - $command = m::mock(Command::class); + $command = Double::for(Command::class); $throwable = new RuntimeException('Execute failed'); $input = new ArrayInput([]); $event = new AfterExecute($command, $throwable, $input, 1); @@ -103,7 +106,7 @@ public function testAfterExecuteCarriesExecutionData(): void public function testScheduledTaskStartingCarriesTask(): void { - $task = new Event(m::mock(EventMutex::class), 'php foo'); + $task = new Event(Double::for(EventMutex::class), 'php foo'); $event = new ScheduledTaskStarting($task); @@ -112,7 +115,7 @@ public function testScheduledTaskStartingCarriesTask(): void public function testScheduledTaskFinishedCarriesTaskAndRuntime(): void { - $task = new Event(m::mock(EventMutex::class), 'php foo'); + $task = new Event(Double::for(EventMutex::class), 'php foo'); $event = new ScheduledTaskFinished($task, 1.23); @@ -122,7 +125,7 @@ public function testScheduledTaskFinishedCarriesTaskAndRuntime(): void public function testScheduledTaskSkippedCarriesTask(): void { - $task = new Event(m::mock(EventMutex::class), 'php foo'); + $task = new Event(Double::for(EventMutex::class), 'php foo'); $event = new ScheduledTaskSkipped($task); @@ -131,7 +134,7 @@ public function testScheduledTaskSkippedCarriesTask(): void public function testScheduledTaskFailedCarriesTaskAndException(): void { - $task = new Event(m::mock(EventMutex::class), 'php foo'); + $task = new Event(Double::for(EventMutex::class), 'php foo'); $exception = new RuntimeException('Task failed'); $event = new ScheduledTaskFailed($task, $exception); @@ -142,7 +145,7 @@ public function testScheduledTaskFailedCarriesTaskAndException(): void public function testScheduledBackgroundTaskFinishedCarriesTask(): void { - $task = new Event(m::mock(EventMutex::class), 'php foo'); + $task = new Event(Double::for(EventMutex::class), 'php foo'); $event = new ScheduledBackgroundTaskFinished($task); diff --git a/tests/Console/Fixtures/Commands/FooExceptionCommand.php b/tests/Console/Fixtures/Commands/FooExceptionCommand.php index 630b6d7425..2be12bc948 100644 --- a/tests/Console/Fixtures/Commands/FooExceptionCommand.php +++ b/tests/Console/Fixtures/Commands/FooExceptionCommand.php @@ -6,7 +6,7 @@ use Hypervel\Console\Command; use Hypervel\Contracts\Events\Dispatcher; -use Mockery as m; +use JMac\Testing\Double; use RuntimeException; class FooExceptionCommand extends Command @@ -18,9 +18,9 @@ public function __construct(?string $name = null) { parent::__construct($name); - $this->eventDispatcher = m::mock(Dispatcher::class); - $this->eventDispatcher->shouldReceive('hasListeners')->andReturnTrue(); - $this->eventDispatcher->shouldReceive('dispatch')->andReturnNull(); + $this->eventDispatcher = Double::for(Dispatcher::class); + $this->eventDispatcher->allows('hasListeners')->returns(true); + $this->eventDispatcher->allows('dispatch')->returns(null); } /** diff --git a/tests/Console/Fixtures/Commands/FooExitCommand.php b/tests/Console/Fixtures/Commands/FooExitCommand.php index ea06b4fbd7..dd9216f2d3 100644 --- a/tests/Console/Fixtures/Commands/FooExitCommand.php +++ b/tests/Console/Fixtures/Commands/FooExitCommand.php @@ -6,7 +6,7 @@ use Hypervel\Console\Command; use Hypervel\Contracts\Events\Dispatcher; -use Mockery as m; +use JMac\Testing\Double; class FooExitCommand extends Command { @@ -17,9 +17,9 @@ public function __construct(?string $name = null) { parent::__construct($name); - $this->eventDispatcher = m::mock(Dispatcher::class); - $this->eventDispatcher->shouldReceive('hasListeners')->andReturnTrue(); - $this->eventDispatcher->shouldReceive('dispatch')->andReturnNull(); + $this->eventDispatcher = Double::for(Dispatcher::class); + $this->eventDispatcher->allows('hasListeners')->returns(true); + $this->eventDispatcher->allows('dispatch')->returns(null); } /** diff --git a/tests/Console/Fixtures/ComponentsFactory.php b/tests/Console/Fixtures/ComponentsFactory.php new file mode 100644 index 0000000000..437e7defca --- /dev/null +++ b/tests/Console/Fixtures/ComponentsFactory.php @@ -0,0 +1,42 @@ + []]); @@ -38,10 +41,10 @@ public function testGetPathWithRelativePath(): void $command = new GeneratorCommandStub; $command->setHypervel($this->app); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-path') - ->andReturn('packages/my-package/src'); + ->returns('packages/my-package/src'); $command->setTestInput($input); $path = $command->exposedGetPath('MyNamespace\MyClass'); @@ -54,10 +57,10 @@ public function testGetPathWithRelativePathWithTrailingSlash(): void $command = new GeneratorCommandStub; $command->setHypervel($this->app); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-path') - ->andReturn('packages/my-package/src/'); + ->returns('packages/my-package/src/'); $command->setTestInput($input); $path = $command->exposedGetPath('MyNamespace\MyClass'); @@ -69,10 +72,10 @@ public function testGetPathWithAbsolutePath(): void { $command = new GeneratorCommandStub; - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-path') - ->andReturn('/tmp/custom-path'); + ->returns('/tmp/custom-path'); $command->setTestInput($input); $path = $command->exposedGetPath('MyNamespace\MyClass'); @@ -84,10 +87,10 @@ public function testGetPathWithAbsolutePathWithTrailingSlash(): void { $command = new GeneratorCommandStub; - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-path') - ->andReturn('/tmp/custom-path/'); + ->returns('/tmp/custom-path/'); $command->setTestInput($input); $path = $command->exposedGetPath('MyNamespace\MyClass'); @@ -100,10 +103,10 @@ public function testGetPathExtractsClassNameFromDeeplyNestedNamespace(): void $command = new GeneratorCommandStub; $command->setHypervel($this->app); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-path') - ->andReturn('src/Controllers'); + ->returns('src/Controllers'); $command->setTestInput($input); $path = $command->exposedGetPath('App\Http\Controllers\Api\V1\UserController'); @@ -120,10 +123,10 @@ public function testGetPathDefaultUsesAppPath(): void $command = new GeneratorCommandStub; $command->setHypervel($this->app); - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-path') - ->andReturn(null); + ->returns(null); $command->setTestInput($input); $path = $command->exposedGetPath('App\Http\Controllers\UserController'); @@ -237,10 +240,10 @@ public function testQualifyClassPrependsDefaultNamespace(): void { $command = new GeneratorCommandStub; - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-namespace') - ->andReturn(null); + ->returns(null); $command->setTestInput($input); $this->assertSame('App\UserController', $command->exposedQualifyClass('UserController')); @@ -250,10 +253,10 @@ public function testQualifyClassReplacesForwardSlashesWithBackslashes(): void { $command = new GeneratorCommandStub; - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-namespace') - ->andReturn(null); + ->returns(null); $command->setTestInput($input); $this->assertSame('App\Http\Controllers\UserController', $command->exposedQualifyClass('Http/Controllers/UserController')); @@ -263,10 +266,10 @@ public function testQualifyClassUsesCustomTargetNamespaceOption(): void { $command = new GeneratorCommandStub; - $input = m::mock(InputInterface::class); - $input->shouldReceive('getOption') + $input = Double::for(InputInterface::class); + $input->expects('getOption')->times(minimum: 1) ->with('target-namespace') - ->andReturn('Custom\Namespace'); + ->returns('Custom\Namespace'); $command->setTestInput($input); $this->assertSame('Custom\Namespace\UserController', $command->exposedQualifyClass('UserController')); @@ -274,11 +277,11 @@ public function testQualifyClassUsesCustomTargetNamespaceOption(): void public function testWriteFailureDoesNotCreateMatchingTestOrReportSuccess(): void { - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->andReturnFalse(); - $files->shouldReceive('ensureDirectoryExists')->once(); - $files->shouldReceive('get')->once()->andReturn('shouldReceive('replace')->once()->andThrow(new RuntimeException('Unable to replace generated file.')); + $files = Double::for(Filesystem::class); + $files->allows('exists')->returns(false); + $files->expects('ensureDirectoryExists'); + $files->expects('get')->returns('expects('replace')->throws(new RuntimeException('Unable to replace generated file.')); $command = new GeneratorCommandStub($files); $command->setHypervel($this->app); diff --git a/tests/Console/InteractsWithSignalsTest.php b/tests/Console/InteractsWithSignalsTest.php index f0508bfc9b..0bc2329994 100644 --- a/tests/Console/InteractsWithSignalsTest.php +++ b/tests/Console/InteractsWithSignalsTest.php @@ -10,11 +10,15 @@ use Hypervel\Coroutine\SignalRegistry; use Hypervel\Support\ClassInvoker; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionProperty; class InteractsWithSignalsTest extends TestCase { + use VerifiesDoubles; + public function testTrapCreatesRegistry(): void { $command = new InteractsWithSignalsTestStub; @@ -22,8 +26,8 @@ public function testTrapCreatesRegistry(): void $invoker = new ClassInvoker($command); $this->assertNull($invoker->signalRegistry); - $signalRegistry = m::mock(SignalRegistry::class)->shouldIgnoreMissing(); - $signalRegistry->shouldReceive('register')->once(); + $signalRegistry = Double::for(SignalRegistry::class); + $signalRegistry->expects('register'); Container::getInstance()->instance(SignalRegistry::class, $signalRegistry); $command->callTrap(SIGTERM, fn (int $signo) => null); @@ -33,8 +37,8 @@ public function testTrapCreatesRegistry(): void public function testTrapReusesExistingRegistry(): void { - $signalRegistry = m::mock(SignalRegistry::class)->shouldIgnoreMissing(); - $signalRegistry->shouldReceive('register')->twice(); + $signalRegistry = Double::for(SignalRegistry::class); + $signalRegistry->expects('register')->times(2); $command = new InteractsWithSignalsTestStub; $this->setSignalRegistry($command, $signalRegistry); @@ -46,9 +50,9 @@ public function testTrapReusesExistingRegistry(): void public function testUntrapDelegatesToRegistry(): void { $command = new InteractsWithSignalsTestStub; - $signalRegistry = m::mock(SignalRegistry::class)->shouldIgnoreMissing(); - $signalRegistry->shouldReceive('register')->once(); - $signalRegistry->shouldReceive('unregister')->with($command, SIGTERM)->once(); + $signalRegistry = Double::for(SignalRegistry::class); + $signalRegistry->expects('register'); + $signalRegistry->expects('unregister')->with(Argument::same($command), SIGTERM); $this->setSignalRegistry($command, $signalRegistry); @@ -68,9 +72,9 @@ public function testUntrapWithNoRegistryIsNoop(): void public function testUntrapAllSignals(): void { $command = new InteractsWithSignalsTestStub; - $signalRegistry = m::mock(SignalRegistry::class)->shouldIgnoreMissing(); - $signalRegistry->shouldReceive('register')->once(); - $signalRegistry->shouldReceive('unregister')->with($command, null)->once(); + $signalRegistry = Double::for(SignalRegistry::class); + $signalRegistry->expects('register'); + $signalRegistry->expects('unregister')->with(Argument::same($command), null); $this->setSignalRegistry($command, $signalRegistry); @@ -87,8 +91,8 @@ public function testTrapResolvesLazyIterableSignals(): void yield SIGINT; })(); $callback = static fn (int $signal): null => null; - $registry = m::mock(SignalRegistry::class)->shouldIgnoreMissing(); - $registry->expects('register')->with($command, $signals, $callback); + $registry = Double::for(SignalRegistry::class); + $registry->expects('register')->with(Argument::same($command), Argument::same($signals), Argument::same($callback)); Container::getInstance()->instance(SignalRegistry::class, $registry); $calls = 0; diff --git a/tests/Console/MigrationGeneratorCommandTest.php b/tests/Console/MigrationGeneratorCommandTest.php index 4dab439b95..ec8846dba1 100644 --- a/tests/Console/MigrationGeneratorCommandTest.php +++ b/tests/Console/MigrationGeneratorCommandTest.php @@ -7,15 +7,18 @@ use Hypervel\Console\MigrationGeneratorCommand; use Hypervel\Filesystem\Filesystem; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class MigrationGeneratorCommandTest extends TestCase { + use VerifiesDoubles; + public function testGlobFailureIsReported(): void { - $files = m::mock(Filesystem::class); - $files->shouldReceive('glob')->once()->with('/app/database/migrations/*.php')->andReturnFalse(); + $files = Double::for(Filesystem::class); + $files->expects('glob')->with('/app/database/migrations/*.php')->returns(false); $command = new TestMigrationGeneratorCommand($files); diff --git a/tests/Console/View/ComponentsTest.php b/tests/Console/View/ComponentsTest.php index 1e97e45cee..05523a762a 100644 --- a/tests/Console/View/ComponentsTest.php +++ b/tests/Console/View/ComponentsTest.php @@ -22,7 +22,9 @@ use Hypervel\Foundation\Application; use Hypervel\Tests\Console\Concerns\CreatesAnsweredOutputStyles; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Console\Question\Question; @@ -30,6 +32,7 @@ class ComponentsTest extends TestCase { use CreatesAnsweredOutputStyles; + use VerifiesDoubles; public function testAlert(): void { @@ -129,16 +132,15 @@ public function testChoice(): void public function testAskWithCompletionAcceptsGeneratorValues(): void { - $output = m::mock(OutputStyle::class); + $output = Double::for(OutputStyle::class); - $output->shouldReceive('askQuestion') - ->with(m::on(function (Question $question): bool { + $output->expects('askQuestion') + ->with(Argument::satisfies(function (Question $question): bool { $this->assertSame(['a', 'b'], $question->getAutocompleterValues()); return true; })) - ->once() - ->andReturn('b'); + ->returns('b'); $choices = (function (): Generator { yield 'a'; diff --git a/tests/Integration/Cache/Redis/RedisStoreTest.php b/tests/Integration/Cache/Redis/RedisStoreTest.php index 0eb6f4f32d..29ca355aec 100644 --- a/tests/Integration/Cache/Redis/RedisStoreTest.php +++ b/tests/Integration/Cache/Redis/RedisStoreTest.php @@ -410,7 +410,7 @@ public function testFlushStaleTagsRemovesExpiredEntriesAndStopsScanning(): void $this->assertSame(2, $store->connection()->zcard($tagSet)); - // The scan has to recognise it is back at its starting cursor, or this never returns... + // The scan has to recognize it is back at its starting cursor, or this never returns... $store->flushStaleTags(); $this->assertSame(1, $store->connection()->zcard($tagSet)); diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 7499e0cd15..aed463ac8d 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -1095,7 +1095,7 @@ public function testTouchingParent(): void CarbonImmutable::setTestNow('2017-10-10 10:10:10'); $tag->update(['name' => $tag->name]); - $this->assertNotSame('2017-10-10 10:10:10', $post->fresh()->updated_at->toDateTimeString()); + $this->assertSame('2017-10-10 09:10:10', $post->fresh()->updated_at->toDateTimeString()); $tag->update(['name' => Str::random()]); $this->assertSame('2017-10-10 10:10:10', $post->fresh()->updated_at->toDateTimeString()); From 4d5bed5bb320da50da7d7776cab32ea0d8181105 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:43:11 +0000 Subject: [PATCH 2/4] Convert Redis, lifecycle, Data and database test doubles Replace direct Mockery doubles in the Redis cache suite, remaining scheduler cases, Context, Cookie, Coordinator, Core, Coroutine, Data and the first Database test group. Preserve explicit call counts, forbidden calls, argument checks, cancellation ownership and cross-call ordering. Exercise Redis operations through initialized connections and strict native client doubles. Reuse concrete scan fixtures where cursor arguments must be updated by reference, retaining pagination and concurrent membership-repair coverage. Record scan inputs and metadata operations for existing assertions; remove one duplicate page test and an unreachable native null-scan case. Use real request, DTO and dispatcher objects where mocking adds no value. Keep scheduler default stubs from absorbing forbidden or excess calls. Resolve the database CLI Process through the existing container with explicit parameters, retaining fresh process ownership, launch options and streamed output while removing constructor interception and isolated test processes. Validation: every changed test file passed independently. The affected Redis cache group passed 491 tests with 2803 assertions. Source, type-fixture and skeleton static analysis passed, as did root/skeleton formatting and the final changed-file formatting and whitespace checks. --- src/database/src/Console/DbCommand.php | 10 +- tests/Auth/EnsureEmailIsVerifiedTest.php | 42 +- tests/Auth/RequirePasswordMiddlewareTest.php | 44 +- tests/Cache/Redis/AllTagSetTest.php | 70 +- tests/Cache/Redis/AllTaggedCacheTest.php | 648 +++++++++--------- tests/Cache/Redis/AnyTagSetTest.php | 122 ++-- tests/Cache/Redis/AnyTaggedCacheTest.php | 520 +++++++------- .../Redis/Console/BenchmarkCommandTest.php | 78 ++- .../Checks/CleanupVerificationCheckTest.php | 13 +- .../Cache/Redis/Console/DoctorCommandTest.php | 388 +++++------ .../Cache/Redis/ExceptionPropagationTest.php | 57 +- tests/Cache/Redis/Operations/AddTest.php | 27 +- .../Redis/Operations/AllTag/AddEntryTest.php | 167 ++--- .../Cache/Redis/Operations/AllTag/AddTest.php | 63 +- .../Redis/Operations/AllTag/DecrementTest.php | 98 ++- .../Operations/AllTag/FlushStaleTest.php | 111 ++- .../Redis/Operations/AllTag/FlushTest.php | 249 +++---- .../Redis/Operations/AllTag/ForeverTest.php | 138 ++-- .../Operations/AllTag/GetEntriesTest.php | 267 +++----- .../Redis/Operations/AllTag/IncrementTest.php | 98 ++- .../Redis/Operations/AllTag/PruneTest.php | 217 +++--- .../Redis/Operations/AllTag/PutManyTest.php | 284 ++++---- .../Cache/Redis/Operations/AllTag/PutTest.php | 169 ++--- .../Redis/Operations/AllTag/TouchTest.php | 29 +- .../Cache/Redis/Operations/AnyTag/AddTest.php | 80 +-- .../Redis/Operations/AnyTag/DecrementTest.php | 74 +- .../Redis/Operations/AnyTag/FlushTest.php | 222 +++--- .../Redis/Operations/AnyTag/ForeverTest.php | 10 +- .../Operations/AnyTag/GetTagItemsTest.php | 60 +- .../Operations/AnyTag/GetTaggedKeysTest.php | 58 +- .../Redis/Operations/AnyTag/IncrementTest.php | 74 +- .../Redis/Operations/AnyTag/PruneTest.php | 382 ++++++----- .../Redis/Operations/AnyTag/PutManyTest.php | 83 ++- .../Cache/Redis/Operations/AnyTag/PutTest.php | 78 +-- .../Cache/Redis/Operations/DecrementTest.php | 6 +- tests/Cache/Redis/Operations/FlushTest.php | 16 +- tests/Cache/Redis/Operations/ForeverTest.php | 10 +- tests/Cache/Redis/Operations/ForgetTest.php | 4 +- tests/Cache/Redis/Operations/GetTest.php | 16 +- .../Cache/Redis/Operations/IncrementTest.php | 8 +- tests/Cache/Redis/Operations/ManyTest.php | 10 +- tests/Cache/Redis/Operations/PutManyTest.php | 36 +- tests/Cache/Redis/Operations/PutTest.php | 20 +- tests/Cache/Redis/RedisCacheTestCase.php | 243 ++----- tests/Cache/Redis/RedisStoreTest.php | 102 ++- .../Cache/Redis/Support/SerializationTest.php | 57 +- .../Cache/Redis/Support/StoreContextTest.php | 67 +- .../Console/Scheduling/CallbackEventTest.php | 17 +- .../Scheduling/ScheduleRunCommandTest.php | 407 ++++++----- .../ScheduleRunContextPropagationTest.php | 40 +- tests/Context/ContextCoroutineTest.php | 3 +- tests/Context/ContextTest.php | 5 +- tests/Cookie/CookieJarTest.php | 35 +- .../AddQueuedCookiesToResponseTest.php | 9 +- tests/Coordinator/TimerTest.php | 20 +- .../Core/Bootstrap/LifecycleCallbackTest.php | 22 +- .../TaskCallbackNonCoroutineTest.php | 48 +- tests/Core/Bootstrap/TaskCallbackTest.php | 287 ++++---- .../Core/Bootstrap/WorkerExitCallbackTest.php | 44 +- .../Bootstrap/WorkerStartCallbackTest.php | 101 ++- tests/Core/StdoutLoggerTest.php | 49 +- tests/Coroutine/ConcurrentTest.php | 12 +- tests/Coroutine/CoroutineTest.php | 60 +- tests/Coroutine/ParallelTest.php | 12 +- .../Coroutine/SignalRegistryRollbackTest.php | 15 +- tests/Coroutine/SignalRegistryTest.php | 41 +- tests/Coroutine/WaitConcurrentTest.php | 12 +- tests/Coroutine/WaiterTest.php | 12 +- tests/Data/DataServiceProviderTest.php | 9 +- .../Data/Support/Creation/DataCollectTest.php | 9 +- tests/Data/Support/DataTypeFactoryTest.php | 8 +- .../Transformers/ArrayableTransformerTest.php | 7 +- .../DateTimeInterfaceTransformerTest.php | 7 +- .../Data/Transformers/EnumTransformerTest.php | 7 +- .../Transformers/SerializeTransformerTest.php | 7 +- tests/Database/ConnectionResolverTest.php | 411 ++++++----- tests/Database/ConnectionTest.php | 21 +- .../DatabaseAbstractSchemaGrammarTest.php | 7 +- .../DatabaseApplicableTransactionTest.php | 13 +- .../Database/DatabaseConnectionLeaseTest.php | 19 +- ...atabaseConnectionLifecycleListenerTest.php | 137 ++-- .../Database/DatabaseDbCommandLaunchTest.php | 40 +- tests/Database/DatabaseDbCommandTest.php | 21 +- .../DatabaseDriverConnectionLeaseTest.php | 9 +- ...aseEloquentCreateOrFirstValidationTest.php | 21 +- .../Database/DatabaseEloquentJsonCastTest.php | 7 +- .../DatabaseEloquentRouteBindingTest.php | 51 +- tests/Database/DatabaseIntegrationTest.php | 23 +- ...atabaseManagerSetDefaultConnectionTest.php | 9 +- .../DatabaseMariaDbConnectionTest.php | 11 +- tests/Redis/Fixtures/FakeRedisClient.php | 77 ++- 91 files changed, 3744 insertions(+), 4063 deletions(-) diff --git a/src/database/src/Console/DbCommand.php b/src/database/src/Console/DbCommand.php index fbdf06779e..a4a82031fe 100644 --- a/src/database/src/Console/DbCommand.php +++ b/src/database/src/Console/DbCommand.php @@ -58,11 +58,11 @@ public function handle(): int } try { - (new Process( - array_merge([$configuration->command], $configuration->arguments), - null, - $configuration->environment - ))->setTimeout(null)->setTty(true)->mustRun(function ($type, $buffer) { + // Container resolution lets tests replace the process without class overloading. + $this->hypervel->make(Process::class, [ + 'command' => array_merge([$configuration->command], $configuration->arguments), + 'env' => $configuration->environment, + ])->setTimeout(null)->setTty(true)->mustRun(function ($type, $buffer) { $this->output->write($buffer); }); } catch (ProcessFailedException $e) { diff --git a/tests/Auth/EnsureEmailIsVerifiedTest.php b/tests/Auth/EnsureEmailIsVerifiedTest.php index a298e86202..d3b2488c63 100644 --- a/tests/Auth/EnsureEmailIsVerifiedTest.php +++ b/tests/Auth/EnsureEmailIsVerifiedTest.php @@ -29,12 +29,12 @@ public function testVerifiedUserPassesThrough(): void $user = Double::for(Authenticatable::class, MustVerifyEmail::class); $user->allows('hasVerifiedEmail')->returns(true); - $request = Double::for(Request::class, override: true); - $request->allows('user')->returns($user); + $request = Request::create('/'); + $request->setUserResolver(fn () => $user); $expectedResponse = new Response('ok'); $middleware = new EnsureEmailIsVerified; - $result = $middleware->handle($request->instance(), fn () => $expectedResponse); + $result = $middleware->handle($request, fn () => $expectedResponse); $this->assertSame($expectedResponse, $result); } @@ -44,26 +44,26 @@ public function testUserThatDoesNotImplementMustVerifyEmailPassesThrough(): void // User implements Authenticatable but does not implement MustVerifyEmail. $user = Double::for(Authenticatable::class); - $request = Double::for(Request::class, override: true); - $request->allows('user')->returns($user); + $request = Request::create('/'); + $request->setUserResolver(fn () => $user); $expectedResponse = new Response('ok'); $middleware = new EnsureEmailIsVerified; - $result = $middleware->handle($request->instance(), fn () => $expectedResponse); + $result = $middleware->handle($request, fn () => $expectedResponse); $this->assertSame($expectedResponse, $result); } public function testGuestRequestReturnsJsonWhenExpectsJson(): void { - $request = Double::for(Request::class, override: true); - $request->allows('user')->returns(null); - $request->allows('expectsJson')->returns(true); + $request = Request::create('/'); + $request->setUserResolver(fn () => null); + $request->headers->set('Accept', 'application/json'); $this->expectException(HttpException::class); $middleware = new EnsureEmailIsVerified; - $middleware->handle($request->instance(), fn () => new Response('should not reach')); + $middleware->handle($request, fn () => new Response('should not reach')); } public function testUnverifiedUserReturnsJsonWhenExpectsJson(): void @@ -71,14 +71,14 @@ public function testUnverifiedUserReturnsJsonWhenExpectsJson(): void $user = Double::for(Authenticatable::class, MustVerifyEmail::class); $user->allows('hasVerifiedEmail')->returns(false); - $request = Double::for(Request::class, override: true); - $request->allows('user')->returns($user); - $request->allows('expectsJson')->returns(true); + $request = Request::create('/'); + $request->setUserResolver(fn () => $user); + $request->headers->set('Accept', 'application/json'); $this->expectException(HttpException::class); $middleware = new EnsureEmailIsVerified; - $middleware->handle($request->instance(), fn () => new Response('should not reach')); + $middleware->handle($request, fn () => new Response('should not reach')); } public function testUnverifiedUserRedirectsWhenNotJson(): void @@ -89,12 +89,11 @@ public function testUnverifiedUserRedirectsWhenNotJson(): void $user = Double::for(Authenticatable::class, MustVerifyEmail::class); $user->allows('hasVerifiedEmail')->returns(false); - $request = Double::for(Request::class, override: true); - $request->allows('user')->returns($user); - $request->allows('expectsJson')->returns(false); + $request = Request::create('/'); + $request->setUserResolver(fn () => $user); $middleware = new EnsureEmailIsVerified; - $result = $middleware->handle($request->instance(), fn () => new Response('should not reach'), 'verify.email'); + $result = $middleware->handle($request, fn () => new Response('should not reach'), 'verify.email'); $this->assertSame(302, $result->getStatusCode()); } @@ -103,12 +102,11 @@ public function testGuestRequestRedirectsWhenNotJson(): void { $this->app->make('router')->get('/email/verify', fn () => 'verify')->name('verify.email'); - $request = Double::for(Request::class, override: true); - $request->allows('user')->returns(null); - $request->allows('expectsJson')->returns(false); + $request = Request::create('/'); + $request->setUserResolver(fn () => null); $middleware = new EnsureEmailIsVerified; - $result = $middleware->handle($request->instance(), fn () => new Response('should not reach'), 'verify.email'); + $result = $middleware->handle($request, fn () => new Response('should not reach'), 'verify.email'); $this->assertSame(302, $result->getStatusCode()); } diff --git a/tests/Auth/RequirePasswordMiddlewareTest.php b/tests/Auth/RequirePasswordMiddlewareTest.php index 5c74cbe1b9..cdb3458b0e 100644 --- a/tests/Auth/RequirePasswordMiddlewareTest.php +++ b/tests/Auth/RequirePasswordMiddlewareTest.php @@ -31,9 +31,9 @@ public function testReturnsJson423WhenStaleAndRequestExpectsJson(): void ->with('auth.password_confirmed_at_web', 0) ->returns(0); // Never confirmed - $request = Double::for(Request::class, override: true); - $request->allows('session')->returns($session); - $request->allows('expectsJson')->returns(true); + $request = Request::create('/'); + $request->setHypervelSession($session); + $request->headers->set('Accept', 'application/json'); $jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423); $responseFactory = Double::for(ResponseFactory::class); @@ -44,7 +44,7 @@ public function testReturnsJson423WhenStaleAndRequestExpectsJson(): void $urlGenerator = Double::for(UrlGenerator::class); $middleware = $this->middleware(responseFactory: $responseFactory, urlGenerator: $urlGenerator); - $result = $middleware->handle($request->instance(), fn () => new Response('should not reach')); + $result = $middleware->handle($request, fn () => new Response('should not reach')); $this->assertSame($jsonResponse, $result); @@ -60,8 +60,8 @@ public function testCustomTimeoutIsHonored(): void ->with('auth.password_confirmed_at_web', 0) ->returns(990); // Confirmed 10 seconds ago - $request = Double::for(Request::class, override: true); - $request->allows('session')->returns($session); + $request = Request::create('/'); + $request->setHypervelSession($session); $responseFactory = Double::for(ResponseFactory::class); $urlGenerator = Double::for(UrlGenerator::class); @@ -70,18 +70,18 @@ public function testCustomTimeoutIsHonored(): void // With default timeout (10800), 10 seconds would pass through $expectedResponse = new Response('ok'); - $result = $middleware->handle($request->instance(), fn () => $expectedResponse); + $result = $middleware->handle($request, fn () => $expectedResponse); $this->assertSame($expectedResponse, $result); // With custom timeout of 5 seconds, 10 seconds ago is stale - $request->allows('expectsJson')->returns(true); + $request->headers->set('Accept', 'application/json'); $jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423); $responseFactory->expects('json') ->with(['message' => 'Password confirmation required.'], 423) ->returns($jsonResponse); $result = $middleware->handle( - $request->instance(), + $request, fn () => new Response('should not reach'), null, 5, @@ -100,9 +100,9 @@ public function testConfirmationIsScopedToCurrentGuard(): void ->with('auth.password_confirmed_at_admin', 0) ->returns(0); - $request = Double::for(Request::class, override: true); - $request->allows('session')->returns($session); - $request->allows('expectsJson')->returns(true); + $request = Request::create('/'); + $request->setHypervelSession($session); + $request->headers->set('Accept', 'application/json'); $responseFactory = Double::for(ResponseFactory::class); $responseFactory->expects('json') @@ -110,7 +110,7 @@ public function testConfirmationIsScopedToCurrentGuard(): void ->returns($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423)); $result = $this->middleware(responseFactory: $responseFactory, guard: 'admin') - ->handle($request->instance(), fn () => new Response('should not reach')); + ->handle($request, fn () => new Response('should not reach')); $this->assertSame($jsonResponse, $result); @@ -127,8 +127,8 @@ public function testPerGuardTimeoutIsHonored(): void ->times(2) ->returns(989, 991); - $request = Double::for(Request::class, override: true); - $request->allows('session')->returns($session); + $request = Request::create('/'); + $request->setHypervelSession($session); $responseFactory = Double::for(ResponseFactory::class); $responseFactory->expects('json') @@ -147,12 +147,12 @@ public function testPerGuardTimeoutIsHonored(): void $middleware = $this->middleware(responseFactory: $responseFactory, config: $config, guard: 'admin'); - $request->allows('expectsJson')->returns(true); - $result = $middleware->handle($request->instance(), fn () => new Response('should not reach')); + $request->headers->set('Accept', 'application/json'); + $result = $middleware->handle($request, fn () => new Response('should not reach')); $this->assertSame($jsonResponse, $result); $expectedResponse = new Response('ok'); - $result = $middleware->handle($request->instance(), fn () => $expectedResponse); + $result = $middleware->handle($request, fn () => $expectedResponse); $this->assertSame($expectedResponse, $result); CarbonImmutable::setTestNow(); @@ -167,9 +167,9 @@ public function testRouteParameterOverridesPerGuardTimeout(): void ->with('auth.password_confirmed_at_admin', 0) ->returns(994); - $request = Double::for(Request::class, override: true); - $request->allows('session')->returns($session); - $request->allows('expectsJson')->returns(true); + $request = Request::create('/'); + $request->setHypervelSession($session); + $request->headers->set('Accept', 'application/json'); $responseFactory = Double::for(ResponseFactory::class); $responseFactory->expects('json') @@ -187,7 +187,7 @@ public function testRouteParameterOverridesPerGuardTimeout(): void ]); $result = $this->middleware(responseFactory: $responseFactory, config: $config, guard: 'admin') - ->handle($request->instance(), fn () => new Response('should not reach'), null, 5); + ->handle($request, fn () => new Response('should not reach'), null, 5); $this->assertSame($jsonResponse, $result); diff --git a/tests/Cache/Redis/AllTagSetTest.php b/tests/Cache/Redis/AllTagSetTest.php index ad2e31ef45..b7baa15d08 100644 --- a/tests/Cache/Redis/AllTagSetTest.php +++ b/tests/Cache/Redis/AllTagSetTest.php @@ -24,14 +24,12 @@ public function testResetAttemptsEveryTag(): void $store = $this->createStore($connection); $tagSet = new AllTagSet($store, ['users', 'posts']); - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with('prefix:_all:tag:users:entries') - ->andReturn(1); - $connection->shouldReceive('del') - ->once() + ->returns(1); + $connection->client()->expects('del') ->with('prefix:_all:tag:posts:entries') - ->andReturn(1); + ->returns(1); $this->assertTrue($tagSet->reset()); } @@ -42,14 +40,12 @@ public function testFlushAttemptsEveryTag(): void $store = $this->createStore($connection); $tagSet = new AllTagSet($store, ['users', 'posts']); - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with('prefix:_all:tag:users:entries') - ->andReturn(1); - $connection->shouldReceive('del') - ->once() + ->returns(1); + $connection->client()->expects('del') ->with('prefix:_all:tag:posts:entries') - ->andReturn(1); + ->returns(1); $this->assertTrue($tagSet->flush()); } @@ -60,14 +56,14 @@ public function testResetAndFlushAttemptEveryTagAndTreatMissingTagsAsSuccess(): $store = $this->createStore($connection); $tagSet = new AllTagSet($store, ['users', 'posts']); - $connection->shouldReceive('del') - ->twice() + $connection->client()->expects('del') + ->times(2) ->with('prefix:_all:tag:users:entries') - ->andReturn(0); - $connection->shouldReceive('del') - ->twice() + ->returns(0); + $connection->client()->expects('del') + ->times(2) ->with('prefix:_all:tag:posts:entries') - ->andReturn(1); + ->returns(1); $this->assertTrue($tagSet->reset()); $this->assertTrue($tagSet->flush()); @@ -107,18 +103,15 @@ public function testResetAttemptsLaterTagsAndRethrowsTheFirstException(): void $connection = $this->mockConnection(); $tagSet = new AllTagSet($this->createStore($connection), ['users', 'posts', 'comments']); - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with('prefix:_all:tag:users:entries') - ->andThrow($firstException); - $connection->shouldReceive('del') - ->once() + ->throws($firstException); + $connection->client()->expects('del') ->with('prefix:_all:tag:posts:entries') - ->andThrow(new RuntimeException('posts failed')); - $connection->shouldReceive('del') - ->once() + ->throws(new RuntimeException('posts failed')); + $connection->client()->expects('del') ->with('prefix:_all:tag:comments:entries') - ->andReturn(1); + ->returns(1); try { $tagSet->reset(); @@ -134,11 +127,10 @@ public function testResetStopsImmediatelyOnCancellation(): void $connection = $this->mockConnection(); $tagSet = new AllTagSet($this->createStore($connection), ['users', 'posts']); - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with('prefix:_all:tag:users:entries') - ->andThrow($cancellation); - $connection->shouldNotReceive('del')->with('prefix:_all:tag:posts:entries'); + ->throws($cancellation); + $connection->client()->expects('del')->never()->with('prefix:_all:tag:posts:entries'); try { $tagSet->reset(); @@ -155,10 +147,9 @@ public function testFlushTagCallsResetTag(): void $tagSet = new AllTagSet($store, ['users']); // resetTag calls store->forget which uses del - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with('prefix:_all:tag:users:entries') - ->andReturn(1); + ->returns(1); $result = $tagSet->flushTag('users'); @@ -171,10 +162,10 @@ public function testPerTagOperationsReturnTheIdentifierWhenTheTagDoesNotExist(): $connection = $this->mockConnection(); $tagSet = new AllTagSet($this->createStore($connection), ['users']); - $connection->shouldReceive('del') - ->twice() + $connection->client()->expects('del') + ->times(2) ->with('prefix:_all:tag:users:entries') - ->andReturn(0); + ->returns(0); $this->assertSame('_all:tag:users:entries', $tagSet->resetTag('users')); $this->assertSame('_all:tag:users:entries', $tagSet->flushTag('users')); @@ -186,10 +177,9 @@ public function testResetTagDeletesTagAndReturnsId(): void $store = $this->createStore($connection); $tagSet = new AllTagSet($store, ['users']); - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with('prefix:_all:tag:users:entries') - ->andReturn(1); + ->returns(1); $result = $tagSet->resetTag('users'); diff --git a/tests/Cache/Redis/AllTaggedCacheTest.php b/tests/Cache/Redis/AllTaggedCacheTest.php index b473319fc2..00ab99e286 100644 --- a/tests/Cache/Redis/AllTaggedCacheTest.php +++ b/tests/Cache/Redis/AllTaggedCacheTest.php @@ -27,7 +27,9 @@ use Hypervel\Cache\Repository; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Support\CarbonImmutable; -use Mockery as m; +use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -45,15 +47,15 @@ public function testTagEntriesCanBeStoredForever(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:people:entries|_all:tag:author:entries') . ':name'; // Combined operation: SET + ZADD for both tags (forever uses score -1) - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:people:entries', -1, $key)->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:author:entries', -1, $key)->andReturn($connection); - $connection->shouldReceive('set')->once()->with("prefix:{$key}", serialize('Sally'))->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1, 1]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:people:entries', -1.0, $key)->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:author:entries', -1.0, $key)->returns($connection->client()); + $connection->client()->expects('set')->with("prefix:{$key}", serialize('Sally'))->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1, 1]); $store = $this->createStore($connection); $result = $store->tags(['people', 'author'])->forever('name', 'Sally'); @@ -65,15 +67,15 @@ public function testTagEntriesCanBeStoredForeverWithNumericValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:people:entries|_all:tag:author:entries') . ':age'; // Numeric values are NOT serialized (optimization) - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:people:entries', -1, $key)->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:author:entries', -1, $key)->andReturn($connection); - $connection->shouldReceive('set')->once()->with("prefix:{$key}", 30)->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1, 1]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:people:entries', -1.0, $key)->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:author:entries', -1.0, $key)->returns($connection->client()); + $connection->client()->expects('set')->with("prefix:{$key}", 30)->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1, 1]); $store = $this->createStore($connection); $result = $store->tags(['people', 'author'])->forever('age', 30); @@ -85,14 +87,14 @@ public function testTagEntriesCanBeIncremented(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:votes:entries') . ':person-1'; // Combined operation: INCRBY + ZADD NX in single pipeline - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:votes:entries', ['NX'], -1, $key)->andReturn($connection); - $connection->shouldReceive('incrby')->once()->with("prefix:{$key}", 1)->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([1, 1]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:votes:entries', ['NX'], -1, $key)->returns($connection->client()); + $connection->client()->expects('incrby')->with("prefix:{$key}", 1)->returns($connection->client()); + $connection->client()->expects('exec')->returns([1, 1]); $store = $this->createStore($connection); $result = $store->tags(['votes'])->increment('person-1'); @@ -104,14 +106,14 @@ public function testTagEntriesCanBeDecremented(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:votes:entries') . ':person-1'; // Combined operation: DECRBY + ZADD NX in single pipeline - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:votes:entries', ['NX'], -1, $key)->andReturn($connection); - $connection->shouldReceive('decrby')->once()->with("prefix:{$key}", 1)->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([9, 1]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:votes:entries', ['NX'], -1, $key)->returns($connection->client()); + $connection->client()->expects('decrby')->with("prefix:{$key}", 1)->returns($connection->client()); + $connection->client()->expects('exec')->returns([9, 1]); $store = $this->createStore($connection); $result = $store->tags(['votes'])->decrement('person-1'); @@ -123,14 +125,13 @@ public function testStaleEntriesCanBeFlushed(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // FlushStaleEntries uses pipeline for zRemRangeByScore - $connection->shouldReceive('zRemRangeByScore') - ->once() + $connection->client()->expects('zRemRangeByScore') ->with('prefix:_all:tag:people:entries', '0', (string) now()->timestamp) - ->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([0]); + ->returns($connection->client()); + $connection->client()->expects('exec')->returns([0]); $store = $this->createStore($connection); $store->tags(['people'])->flushStale(); @@ -140,16 +141,16 @@ public function testPut(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:people:entries|_all:tag:author:entries') . ':name'; $expectedScore = now()->timestamp + 5; // Combined operation: SETEX + ZADD for both tags in single pipeline - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:people:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:author:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('setex')->once()->with("prefix:{$key}", 5, serialize('Sally'))->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1, 1]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:people:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:author:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('setex')->with("prefix:{$key}", 5, serialize('Sally'))->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1, 1]); $store = $this->createStore($connection); $result = $store->tags(['people', 'author'])->put('name', 'Sally', 5); @@ -161,16 +162,16 @@ public function testPutWithNumericValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:people:entries|_all:tag:author:entries') . ':age'; $expectedScore = now()->timestamp + 5; // Numeric values are NOT serialized - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:people:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:author:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('setex')->once()->with("prefix:{$key}", 5, 30)->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1, 1]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:people:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:author:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('setex')->with("prefix:{$key}", 5, 30)->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1, 1]); $store = $this->createStore($connection); $result = $store->tags(['people', 'author'])->put('age', 30, 5); @@ -182,30 +183,28 @@ public function testPutWithArray(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $namespace = hash('xxh128', '_all:tag:people:entries|_all:tag:author:entries') . ':'; $expectedScore = now()->timestamp + 5; // PutMany uses variadic ZADD: one command per tag with all keys as members // First tag (people) gets both keys in one ZADD - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:people:entries', $expectedScore, $namespace . 'name', $expectedScore, $namespace . 'age') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:people:entries', (float) $expectedScore, $namespace . 'name', $expectedScore, $namespace . 'age') + ->returns($connection->client()); // Second tag (author) gets both keys in one ZADD - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:author:entries', $expectedScore, $namespace . 'name', $expectedScore, $namespace . 'age') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:author:entries', (float) $expectedScore, $namespace . 'name', $expectedScore, $namespace . 'age') + ->returns($connection->client()); // SETEX for each key - $connection->shouldReceive('setex')->once()->with("prefix:{$namespace}name", 5, serialize('Sally'))->andReturn($connection); - $connection->shouldReceive('setex')->once()->with("prefix:{$namespace}age", 5, 30)->andReturn($connection); + $connection->client()->expects('setex')->with("prefix:{$namespace}name", 5, serialize('Sally'))->returns($connection->client()); + $connection->client()->expects('setex')->with("prefix:{$namespace}age", 5, 30)->returns($connection->client()); // Results: 2 SETEXs + 2 ZADDs - $connection->shouldReceive('exec')->once()->andReturn([true, true, 2, 2]); + $connection->client()->expects('exec')->returns([true, true, 2, 2]); $store = $this->createStore($connection); $result = $store->tags(['people', 'author'])->put([ @@ -224,21 +223,20 @@ public function testManyUsesSingleMgetWithCachedTagPrefix(): void $namespace = '_all:tag:people:entries|_all:tag:author:entries'; $prefix = hash('xxh128', $namespace) . ':'; - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with([ "prefix:{$prefix}name", "prefix:{$prefix}age", "prefix:{$prefix}missing", ]) - ->andReturn([ + ->returns([ serialize('Sally'), '30', null, ]); - $tags = m::mock(AllTagSet::class, [$store, ['people', 'author']])->makePartial(); - $tags->shouldReceive('getNamespace')->once()->andReturn($namespace); + $tags = Double::for(new AllTagSet($store, ['people', 'author']))->passthru(); + $tags->expects('getNamespace')->returns($namespace); $result = (new AllTaggedCache($store, $tags))->many([ 'name' => 'unused', @@ -259,14 +257,13 @@ public function testManyFiresTaggedManyEvents(): void $key = hash('xxh128', '_all:tag:users:entries') . ':'; $events = []; - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with(["prefix:{$key}profile", "prefix:{$key}missing"]) - ->andReturn([serialize('cached'), null]); + ->returns([serialize('cached'), null]); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->andReturnUsing(function (object $event) use (&$events): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(true); + $dispatcher->allows('dispatch')->resolves(function (object $event) use (&$events): void { $events[] = $event; }); @@ -295,61 +292,60 @@ public function testManyFiresTaggedManyEvents(): void public function testFlush(): void { - $connection = $this->mockConnection(); - - // Flush operation scans tag sets and deletes entries - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:people:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['key1' => 0, 'key2' => 0]; - }); - $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:people:entries', 'prefix:key1', 'prefix:key2'], ['key1', 'key2']) - ->andReturn(1); - - $store = $this->createStore($connection); - $result = $store->tags(['people'])->flush(); + $client = new FakeRedisClient( + zScanResults: [ + 'prefix:_all:tag:people:entries' => [ + ['members' => ['key1' => 0, 'key2' => 0], 'iterator' => 0], + ], + ], + evalShaResults: [1], + ); + $store = $this->createStoreWithFakeClient($client); - $this->assertTrue($result); + $this->assertTrue($store->tags(['people'])->flush()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:people:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); + $calls = $client->getEvalShaCalls(); + $this->assertCount(1, $calls); + $this->assertSame(['prefix:_all:tag:people:entries', 'prefix:key1', 'prefix:key2', 'key1', 'key2'], $calls[0]['args']); + $this->assertSame(3, $calls[0]['num_keys']); } public function testClearFlushesTaggedItems(): void { - $connection = $this->mockConnection(); - - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:people:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['key1' => 0, 'key2' => 0]; - }); - $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:people:entries', 'prefix:key1', 'prefix:key2'], ['key1', 'key2']) - ->andReturn(1); - - $store = $this->createStore($connection); - $result = $store->tags(['people'])->clear(); + $client = new FakeRedisClient( + zScanResults: [ + 'prefix:_all:tag:people:entries' => [ + ['members' => ['key1' => 0, 'key2' => 0], 'iterator' => 0], + ], + ], + evalShaResults: [1], + ); + $store = $this->createStoreWithFakeClient($client); - $this->assertTrue($result); + $this->assertTrue($store->tags(['people'])->clear()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:people:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); + $calls = $client->getEvalShaCalls(); + $this->assertCount(1, $calls); + $this->assertSame(['prefix:_all:tag:people:entries', 'prefix:key1', 'prefix:key2', 'key1', 'key2'], $calls[0]['args']); + $this->assertSame(3, $calls[0]['num_keys']); } public function testPutNullTtlCallsForever(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:users:entries') . ':name'; // Null TTL should call forever (SET + ZADD with -1) - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:users:entries', -1, $key)->andReturn($connection); - $connection->shouldReceive('set')->once()->with("prefix:{$key}", serialize('John'))->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:users:entries', -1.0, $key)->returns($connection->client()); + $connection->client()->expects('set')->with("prefix:{$key}", serialize('John'))->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $store = $this->createStore($connection); $result = $store->tags(['users'])->put('name', 'John', null); @@ -364,10 +360,9 @@ public function testPutZeroTtlDeletesKey(): void $key = hash('xxh128', '_all:tag:users:entries') . ':name'; // Zero TTL should delete the key (Forget operation uses connection) - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with("prefix:{$key}") - ->andReturn(1); + ->returns(1); $store = $this->createStore($connection); $result = $store->tags(['users'])->put('name', 'John', 0); @@ -381,14 +376,12 @@ public function testPutManyZeroTtlDeletesNamespacedKeys(): void $namespace = hash('xxh128', '_all:tag:users:entries') . ':'; - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with("prefix:{$namespace}name") - ->andReturn(1); - $connection->shouldReceive('del') - ->once() + ->returns(1); + $connection->client()->expects('del') ->with("prefix:{$namespace}age") - ->andReturn(1); + ->returns(1); $store = $this->createStore($connection); $result = $store->tags(['users'])->putMany([ @@ -407,16 +400,15 @@ public function testTouchUpdatesKeyAndTagScores(bool $succeeded): void $key = hash('xxh128', '_all:tag:users:entries') . ':name'; - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function (string $script, array $keys, array $args) use ($key): bool { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function (string $script, array $keys, array $args) use ($key): bool { $this->assertSame(["prefix:{$key}", 'prefix:_all:tag:users:entries'], $keys); $this->assertSame(60, $args[0]); $this->assertSame($key, $args[2]); return true; - }) - ->andReturn($succeeded); + })) + ->returns($succeeded); $store = $this->createStore($connection); $result = $store->tags(['users'])->touch('name', 60); @@ -430,8 +422,8 @@ public function testTouchWithDatetimeInPastOrZeroSecondsRemovesOldItem(): void $key = hash('xxh128', '_all:tag:users:entries') . ':name'; - $connection->shouldNotReceive('evalWithShaCache'); - $connection->expects('del')->twice()->with("prefix:{$key}")->andReturn(1); + $connection->expects('evalWithShaCache')->never(); + $connection->client()->expects('del')->times(2)->with("prefix:{$key}")->returns(1); $store = $this->createStore($connection); $tagged = $store->tags(['users']); @@ -444,13 +436,13 @@ public function testIncrementWithCustomValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:counters:entries') . ':hits'; - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:counters:entries', ['NX'], -1, $key)->andReturn($connection); - $connection->shouldReceive('incrby')->once()->with("prefix:{$key}", 5)->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([15, 1]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:counters:entries', ['NX'], -1, $key)->returns($connection->client()); + $connection->client()->expects('incrby')->with("prefix:{$key}", 5)->returns($connection->client()); + $connection->client()->expects('exec')->returns([15, 1]); $store = $this->createStore($connection); $result = $store->tags(['counters'])->increment('hits', 5); @@ -462,13 +454,13 @@ public function testDecrementWithCustomValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $key = hash('xxh128', '_all:tag:counters:entries') . ':stock'; - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:counters:entries', ['NX'], -1, $key)->andReturn($connection); - $connection->shouldReceive('decrby')->once()->with("prefix:{$key}", 3)->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([7, 0]); + $connection->client()->expects('zadd')->with('prefix:_all:tag:counters:entries', ['NX'], -1, $key)->returns($connection->client()); + $connection->client()->expects('decrby')->with("prefix:{$key}", 3)->returns($connection->client()); + $connection->client()->expects('exec')->returns([7, 0]); $store = $this->createStore($connection); $result = $store->tags(['counters'])->decrement('stock', 3); @@ -482,10 +474,9 @@ public function testRememberReturnsExistingValueOnCacheHit(): void $key = hash('xxh128', '_all:tag:users:entries') . ':profile'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturn(serialize('cached_value')); + ->returns(serialize('cached_value')); $store = $this->createStore($connection); $result = $store->tags(['users'])->remember('profile', 60, fn () => 'new_value'); @@ -501,16 +492,15 @@ public function testRememberCallsCallbackAndStoresValueOnMiss(): void $expectedScore = now()->timestamp + 60; // Cache miss - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturnNull(); + ->returns(null); // Pipeline for SETEX + ZADD on miss - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:users:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('setex')->once()->with("prefix:{$key}", 60, serialize('computed_value'))->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:users:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('setex')->with("prefix:{$key}", 60, serialize('computed_value'))->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $callCount = 0; $store = $this->createStore($connection); @@ -531,17 +521,17 @@ public function testRememberNormalizesEnumKeyForRedisAndEvents(): void $key = hash('xxh128', '_all:tag:users:entries') . ':0'; $expectedScore = now()->timestamp + 60; - $connection->shouldReceive('get')->once()->with("prefix:{$key}")->andReturnNull(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:users:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('setex')->once()->with("prefix:{$key}", 60, serialize('computed_value'))->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + $connection->client()->expects('get')->with("prefix:{$key}")->returns(null); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:users:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('setex')->with("prefix:{$key}", 60, serialize('computed_value'))->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); @@ -567,10 +557,9 @@ public function testRememberDoesNotCallCallbackOnCacheHit(): void $key = hash('xxh128', '_all:tag:users:entries') . ':data'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturn(serialize('existing_value')); + ->returns(serialize('existing_value')); $callCount = 0; $store = $this->createStore($connection); @@ -590,11 +579,11 @@ public function testRememberNullableStoresAndReturnsNonNullValue(): void $key = hash('xxh128', '_all:tag:users:entries') . ':profile'; $expectedScore = now()->timestamp + 60; - $connection->shouldReceive('get')->once()->with("prefix:{$key}")->andReturnNull(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:users:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('setex')->once()->with("prefix:{$key}", 60, serialize('computed'))->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + $connection->client()->expects('get')->with("prefix:{$key}")->returns(null); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:users:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('setex')->with("prefix:{$key}", 60, serialize('computed'))->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $store = $this->createStore($connection); $result = $store->tags(['users'])->rememberNullable('profile', 60, fn () => 'computed'); @@ -608,18 +597,17 @@ public function testRememberNullableStoresSentinelWhenCallbackReturnsNull(): voi $key = hash('xxh128', '_all:tag:users:entries') . ':profile'; $expectedScore = now()->timestamp + 60; - $connection->shouldReceive('get')->once()->with("prefix:{$key}")->andReturnNull(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:users:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('get')->with("prefix:{$key}")->returns(null); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:users:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('setex') ->with( "prefix:{$key}", 60, - m::on(fn (string $serialized): bool => unserialize($serialized) === NullSentinel::VALUE) + Argument::satisfies(fn (string $serialized): bool => unserialize($serialized) === NullSentinel::VALUE) ) - ->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + ->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $store = $this->createStore($connection); $result = $store->tags(['users'])->rememberNullable('profile', 60, fn () => null); @@ -632,10 +620,9 @@ public function testRememberNullableReturnsNullOnSentinelHitWithoutInvokingCallb $connection = $this->mockConnection(); $key = hash('xxh128', '_all:tag:users:entries') . ':profile'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $invoked = false; $store = $this->createStore($connection); @@ -653,16 +640,15 @@ public function testRememberNullableFiresCacheHitWithNullPayloadOnSentinelHit(): $connection = $this->mockConnection(); $key = hash('xxh128', '_all:tag:users:entries') . ':profile'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); @@ -684,17 +670,17 @@ public function testRememberNullableFiresKeyWrittenWithNullPayloadOnCacheMiss(): $key = hash('xxh128', '_all:tag:users:entries') . ':profile'; $expectedScore = now()->timestamp + 60; - $connection->shouldReceive('get')->once()->with("prefix:{$key}")->andReturnNull(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:users:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('setex')->once()->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + $connection->client()->expects('get')->with("prefix:{$key}")->returns(null); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:users:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('setex')->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); @@ -719,10 +705,9 @@ public function testPlainRememberUnwrapsSentinelOnCachedNullHit(): void $connection = $this->mockConnection(); $key = hash('xxh128', '_all:tag:users:entries') . ':profile'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $invoked = false; $store = $this->createStore($connection); @@ -741,10 +726,9 @@ public function testRememberForeverReturnsExistingValueOnCacheHit(): void $key = hash('xxh128', '_all:tag:config:entries') . ':settings'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturn(serialize('cached_settings')); + ->returns(serialize('cached_settings')); $store = $this->createStore($connection); $result = $store->tags(['config'])->rememberForever('settings', fn () => 'new_settings'); @@ -758,16 +742,15 @@ public function testRememberForeverNormalizesEnumKeyForRedisAndEvents(): void $key = hash('xxh128', '_all:tag:config:entries') . ':1'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturn(serialize('cached_settings')); + ->returns(serialize('cached_settings')); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); @@ -791,16 +774,15 @@ public function testRememberForeverCallsCallbackAndStoresValueOnMiss(): void $key = hash('xxh128', '_all:tag:config:entries') . ':settings'; // Cache miss - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturnNull(); + ->returns(null); // Pipeline for SET + ZADD (score -1) on miss - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:config:entries', -1, $key)->andReturn($connection); - $connection->shouldReceive('set')->once()->with("prefix:{$key}", serialize('computed_settings'))->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:config:entries', -1.0, $key)->returns($connection->client()); + $connection->client()->expects('set')->with("prefix:{$key}", serialize('computed_settings'))->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $store = $this->createStore($connection); $result = $store->tags(['config'])->rememberForever('settings', fn () => 'computed_settings'); @@ -813,17 +795,16 @@ public function testRememberForeverNullableStoresSentinelWhenCallbackReturnsNull $connection = $this->mockConnection(); $key = hash('xxh128', '_all:tag:config:entries') . ':settings'; - $connection->shouldReceive('get')->once()->with("prefix:{$key}")->andReturnNull(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:config:entries', -1, $key)->andReturn($connection); - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('get')->with("prefix:{$key}")->returns(null); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:config:entries', -1.0, $key)->returns($connection->client()); + $connection->client()->expects('set') ->with( "prefix:{$key}", - m::on(fn (string $serialized): bool => unserialize($serialized) === NullSentinel::VALUE) + Argument::satisfies(fn (string $serialized): bool => unserialize($serialized) === NullSentinel::VALUE) ) - ->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + ->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $store = $this->createStore($connection); $result = $store->tags(['config'])->rememberForeverNullable('settings', fn () => null); @@ -836,17 +817,16 @@ public function testSearNullableDelegatesToRememberForeverNullable(): void $connection = $this->mockConnection(); $key = hash('xxh128', '_all:tag:config:entries') . ':settings'; - $connection->shouldReceive('get')->once()->with("prefix:{$key}")->andReturnNull(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:config:entries', -1, $key)->andReturn($connection); - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('get')->with("prefix:{$key}")->returns(null); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:config:entries', -1.0, $key)->returns($connection->client()); + $connection->client()->expects('set') ->with( "prefix:{$key}", - m::on(fn (string $serialized): bool => unserialize($serialized) === NullSentinel::VALUE) + Argument::satisfies(fn (string $serialized): bool => unserialize($serialized) === NullSentinel::VALUE) ) - ->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + ->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $store = $this->createStore($connection); $result = $store->tags(['config'])->searNullable('settings', fn () => null); @@ -862,10 +842,9 @@ public function testPlainRememberForeverUnwrapsSentinelOnCachedNullHit(): void $connection = $this->mockConnection(); $key = hash('xxh128', '_all:tag:config:entries') . ':settings'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $invoked = false; $store = $this->createStore($connection); @@ -884,10 +863,9 @@ public function testRememberPropagatesExceptionFromCallback(): void $key = hash('xxh128', '_all:tag:users:entries') . ':data'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturnNull(); + ->returns(null); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Callback failed'); @@ -904,10 +882,9 @@ public function testRememberForeverPropagatesExceptionFromCallback(): void $key = hash('xxh128', '_all:tag:config:entries') . ':data'; - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturnNull(); + ->returns(null); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Forever callback failed'); @@ -926,17 +903,16 @@ public function testRememberWithMultipleTags(): void $expectedScore = now()->timestamp + 120; // Cache miss - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with("prefix:{$key}") - ->andReturnNull(); + ->returns(null); // Pipeline for SETEX + ZADDs on miss - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:users:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('zadd')->once()->with('prefix:_all:tag:posts:entries', $expectedScore, $key)->andReturn($connection); - $connection->shouldReceive('setex')->once()->with("prefix:{$key}", 120, serialize('activity_data'))->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1, 1]); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:users:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('zadd')->with('prefix:_all:tag:posts:entries', (float) $expectedScore, $key)->returns($connection->client()); + $connection->client()->expects('setex')->with("prefix:{$key}", 120, serialize('activity_data'))->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1, 1]); $store = $this->createStore($connection); $result = $store->tags(['users', 'posts'])->remember('activity', 120, fn () => 'activity_data'); @@ -953,10 +929,9 @@ public function testFlexibleNullableReturnsNullOnFreshSentinelHit(): void // flexible() reads both keys via a single manyRaw() → store->many() → MGET. // phpredis's mget() returns a numeric array in input order. - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with(["prefix:{$valueKey}", "prefix:{$markerKey}"]) - ->andReturn([serialize(NullSentinel::VALUE), serialize($now)]); + ->returns([serialize(NullSentinel::VALUE), serialize($now)]); $invoked = false; $store = $this->createStore($connection); @@ -971,16 +946,16 @@ public function testFlexibleNullableReturnsNullOnFreshSentinelHit(): void public function testAllTaggedCacheSkipsEventDispatchSeamWithoutListenersAndEntersItWithListeners(): void { - $put = m::mock(Put::class); - $put->shouldReceive('execute')->twice()->andReturnTrue(); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('put')->twice()->andReturn($put); - $store = m::mock(RedisStore::class); - $store->shouldReceive('allTagOps')->twice()->andReturn($operations); - $tags = m::mock(AllTagSet::class); - $tags->shouldReceive('getNamespace')->andReturn('namespace'); - $tags->shouldReceive('tagIds')->andReturn([]); - $tags->shouldReceive('getNames')->andReturn(['users']); + $put = Double::for(Put::class); + $put->expects('execute')->times(2)->returns(true); + $operations = Double::for(AllTagOperations::class); + $operations->expects('put')->times(2)->returns($put); + $store = Double::for(RedisStore::class); + $store->expects('allTagOps')->times(2)->returns($operations); + $tags = Double::for(AllTagSet::class); + $tags->allows('getNamespace')->returns('namespace'); + $tags->allows('tagIds')->returns([]); + $tags->allows('getNames')->returns(['users']); $cache = new class($store, $tags) extends AllTaggedCache { public int $eventCalls = 0; @@ -992,9 +967,9 @@ protected function event(object $event): void parent::event($event); } }; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(false); + $events->expects('dispatch')->never(); $cache->setEventDispatcher($events); $this->assertTrue($cache->put('first', 'value', 60)); @@ -1018,16 +993,14 @@ public function testPutDispatchesTheRepositoryWriteEventsWithStoreNameAndTags(): $key = hash('xxh128', '_all:tag:users:entries') . ':name'; $score = now()->timestamp + 60; - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', $score, $key) - ->andReturn($connection); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', (float) $score, $key) + ->returns($connection->client()); + $connection->client()->expects('setex') ->with("prefix:{$key}", 60, serialize('John')) - ->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + ->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $captured = []; $tagged = (new Repository($this->createStore($connection), ['store' => 'redis']))->tags(['users']); @@ -1050,17 +1023,15 @@ public function testAddWithoutTtlDispatchesRepositoryReadAndWriteEvents(): void $connection = $this->mockConnection(); $key = hash('xxh128', '_all:tag:users:entries') . ':name'; - $connection->shouldReceive('get')->once()->with("prefix:{$key}")->andReturnNull(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', -1, $key) - ->andReturn($connection); - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('get')->with("prefix:{$key}")->returns(null); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', -1.0, $key) + ->returns($connection->client()); + $connection->client()->expects('set') ->with("prefix:{$key}", serialize('John')) - ->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 1]); + ->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 1]); $captured = []; $tagged = (new Repository($this->createStore($connection), ['store' => 'redis']))->tags(['users']); @@ -1085,16 +1056,14 @@ public function testPutDispatchesTheRepositoryFailureEventWithStoreNameAndTags() $key = hash('xxh128', '_all:tag:users:entries') . ':name'; $score = now()->timestamp + 60; - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', $score, $key) - ->andReturn($connection); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', (float) $score, $key) + ->returns($connection->client()); + $connection->client()->expects('setex') ->with("prefix:{$key}", 60, serialize('John')) - ->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([false, 1]); + ->returns($connection->client()); + $connection->client()->expects('exec')->returns([false, 1]); $captured = []; $tagged = (new Repository($this->createStore($connection), ['store' => 'redis']))->tags(['users']); @@ -1109,11 +1078,11 @@ public function testPutDispatchesTheRepositoryFailureEventWithStoreNameAndTags() public function testPutDispatchesTheRepositoryFailureEventWhenTheOperationThrows(): void { $exception = new RuntimeException('write failed'); - $put = m::mock(Put::class); - $put->shouldReceive('execute')->once()->andThrow($exception); + $put = Double::for(Put::class); + $put->expects('execute')->throws($exception); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('put')->once()->andReturn($put); + $operations = Double::for(AllTagOperations::class); + $operations->expects('put')->returns($put); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -1137,11 +1106,11 @@ public function testPutDoesNotDispatchFailureEventWhenTheOperationIsCanceled(boo if ($cleanupThrows) { $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } - $put = m::mock(Put::class); - $put->shouldReceive('execute')->once()->andThrow($cancellation); + $put = Double::for(Put::class); + $put->expects('execute')->throws($cancellation); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('put')->once()->andReturn($put); + $operations = Double::for(AllTagOperations::class); + $operations->expects('put')->returns($put); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -1159,11 +1128,11 @@ public function testPutManyDispatchesRepositoryFailureEventsWhenTheOperationThro { $exception = new RuntimeException('batch write failed'); $values = ['name' => 'John', 'age' => 30]; - $putMany = m::mock(PutMany::class); - $putMany->shouldReceive('execute')->once()->andThrow($exception); + $putMany = Double::for(PutMany::class); + $putMany->expects('execute')->throws($exception); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('putMany')->once()->andReturn($putMany); + $operations = Double::for(AllTagOperations::class); + $operations->expects('putMany')->returns($putMany); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -1192,11 +1161,11 @@ public function testPutManyDoesNotDispatchFailureEventsWhenTheOperationIsCancele $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } $values = ['name' => 'John', 'age' => 30]; - $putMany = m::mock(PutMany::class); - $putMany->shouldReceive('execute')->once()->andThrow($cancellation); + $putMany = Double::for(PutMany::class); + $putMany->expects('execute')->throws($cancellation); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('putMany')->once()->andReturn($putMany); + $operations = Double::for(AllTagOperations::class); + $operations->expects('putMany')->returns($putMany); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -1212,12 +1181,12 @@ public function testPutManyDoesNotDispatchFailureEventsWhenTheOperationIsCancele public function testEmptyPutManyReturnsTrueWithoutOperationOrEvents(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('allTagOps'); - $tags = m::mock(AllTagSet::class); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners'); - $events->shouldNotReceive('dispatch'); + $store = Double::for(RedisStore::class); + $store->expects('allTagOps')->never(); + $tags = Double::for(AllTagSet::class); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $tagged = new AllTaggedCache($store, $tags); $tagged->setEventDispatcher($events); @@ -1227,11 +1196,11 @@ public function testEmptyPutManyReturnsTrueWithoutOperationOrEvents(): void public function testForeverDispatchesTheRepositoryFailureEventWhenTheOperationThrows(): void { $exception = new RuntimeException('forever write failed'); - $forever = m::mock(Forever::class); - $forever->shouldReceive('execute')->once()->andThrow($exception); + $forever = Double::for(Forever::class); + $forever->expects('execute')->throws($exception); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('forever')->once()->andReturn($forever); + $operations = Double::for(AllTagOperations::class); + $operations->expects('forever')->returns($forever); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -1255,11 +1224,11 @@ public function testForeverDoesNotDispatchFailureEventWhenTheOperationIsCanceled if ($cleanupThrows) { $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } - $forever = m::mock(Forever::class); - $forever->shouldReceive('execute')->once()->andThrow($cancellation); + $forever = Double::for(Forever::class); + $forever->expects('execute')->throws($cancellation); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('forever')->once()->andReturn($forever); + $operations = Double::for(AllTagOperations::class); + $operations->expects('forever')->returns($forever); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -1279,26 +1248,23 @@ public function testPutManyDispatchesTheRepositoryWriteEventsWithStoreNameAndTag $namespace = hash('xxh128', '_all:tag:users:entries') . ':'; $score = now()->timestamp + 60; - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zadd') ->with( 'prefix:_all:tag:users:entries', - $score, + (float) $score, $namespace . 'name', $score, $namespace . 'age' ) - ->andReturn($connection); - $connection->shouldReceive('setex') - ->once() + ->returns($connection->client()); + $connection->client()->expects('setex') ->with("prefix:{$namespace}name", 60, serialize('John')) - ->andReturn($connection); - $connection->shouldReceive('setex') - ->once() + ->returns($connection->client()); + $connection->client()->expects('setex') ->with("prefix:{$namespace}age", 60, 30) - ->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, true, 2]); + ->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, true, 2]); $captured = []; $tagged = (new Repository($this->createStore($connection), ['store' => 'redis']))->tags(['users']); @@ -1320,20 +1286,18 @@ public function testPutManyDispatchesTheRepositoryWriteEventsWithStoreNameAndTag public function testFlushDispatchesTheRepositoryEventsWithStoreNameAndTags(): void { - $connection = $this->mockConnection(); - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return []; - }); + $client = new FakeRedisClient(zScanResults: [ + 'prefix:_all:tag:users:entries' => [['members' => [], 'iterator' => 0]], + ]); $captured = []; - $tagged = (new Repository($this->createStore($connection), ['store' => 'redis']))->tags(['users']); + $tagged = (new Repository($this->createStoreWithFakeClient($client), ['store' => 'redis']))->tags(['users']); $tagged->setEventDispatcher($this->capturingDispatcher($captured)); $this->assertTrue($tagged->flush()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); + $this->assertSame([], $client->getEvalShaCalls()); $this->assertSame([CacheFlushing::class, CacheFlushed::class], array_map(get_class(...), $captured)); foreach ($captured as $event) { @@ -1345,11 +1309,11 @@ public function testFlushDispatchesTheRepositoryEventsWithStoreNameAndTags(): vo public function testFlushDispatchesFailureEventWithExactOperationException(): void { $exception = new RuntimeException('flush failed'); - $flush = m::mock(Flush::class); - $flush->shouldReceive('execute')->once()->andThrow($exception); + $flush = Double::for(Flush::class); + $flush->expects('execute')->throws($exception); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('flush')->once()->andReturn($flush); + $operations = Double::for(AllTagOperations::class); + $operations->expects('flush')->returns($flush); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -1372,11 +1336,11 @@ public function testFlushDoesNotDispatchFailureEventWhenTheOperationIsCanceled(b if ($cleanupThrows) { $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } - $flush = m::mock(Flush::class); - $flush->shouldReceive('execute')->once()->andThrow($cancellation); + $flush = Double::for(Flush::class); + $flush->expects('execute')->throws($cancellation); - $operations = m::mock(AllTagOperations::class); - $operations->shouldReceive('flush')->once()->andReturn($flush); + $operations = Double::for(AllTagOperations::class); + $operations->expects('flush')->returns($flush); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -1397,10 +1361,10 @@ public function testFlushDoesNotDispatchFailureEventWhenTheOperationIsCanceled(b */ private function capturingDispatcher(array &$captured): Dispatcher { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$captured): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(true); + $dispatcher->allows('dispatch') + ->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); @@ -1409,16 +1373,16 @@ private function capturingDispatcher(array &$captured): Dispatcher private function taggedCacheWithOperations(AllTagOperations $operations, array &$captured): AllTaggedCache { - $store = m::mock(RedisStore::class); - $store->shouldReceive('allTagOps')->once()->andReturn($operations); + $store = Double::for(RedisStore::class); + $store->expects('allTagOps')->returns($operations); - $tags = m::mock(AllTagSet::class); - $tags->shouldReceive('getNames')->andReturn(['users']); - $tags->shouldReceive('getNamespace')->andReturn('users'); - $tags->shouldReceive('tagIds')->andReturn(['users-id']); + $tags = Double::for(AllTagSet::class); + $tags->allows('getNames')->returns(['users']); + $tags->allows('getNamespace')->returns('users'); + $tags->allows('tagIds')->returns(['users-id']); $cache = new AllTaggedCache($store, $tags); - $store->shouldReceive('tags')->once()->with(['users'])->andReturn($cache); + $store->expects('tags')->with(['users'])->returns($cache); $tagged = (new Repository($store, ['store' => 'redis']))->tags(['users']); $tagged->setEventDispatcher($this->capturingDispatcher($captured)); diff --git a/tests/Cache/Redis/AnyTagSetTest.php b/tests/Cache/Redis/AnyTagSetTest.php index 9898f4b451..b92a15f8f6 100644 --- a/tests/Cache/Redis/AnyTagSetTest.php +++ b/tests/Cache/Redis/AnyTagSetTest.php @@ -7,19 +7,15 @@ use Generator; use Hypervel\Cache\Redis\AnyTagSet; use Hypervel\Cache\RedisStore; -use Mockery as m; - -/** - * Tests for AnyTagSet class. - * - * Uses MocksRedisConnections to mock at the Redis client level, - * allowing the full operation chain to execute. - */ +use Hypervel\Redis\PhpRedisConnection; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Matching\Argument; + class AnyTagSetTest extends RedisCacheTestCase { private RedisStore $store; - private m\MockInterface $connection; + private PhpRedisConnection&DoubleInterface $connection; /** * Set up test fixtures. @@ -59,15 +55,13 @@ public function testEntriesReturnsGeneratorOfKeys(): void $tagSet = new AnyTagSet($this->store, ['users']); // GetTaggedKeys checks HLEN then uses HKEYS for small hashes - $this->connection->shouldReceive('hlen') - ->once() + $this->connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(3); + ->returns(3); - $this->connection->shouldReceive('hkeys') - ->once() + $this->connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['key1', 'key2', 'key3']); + ->returns(['key1', 'key2', 'key3']); $entries = $tagSet->entries(); @@ -80,24 +74,20 @@ public function testEntriesDeduplicatesAcrossTags(): void $tagSet = new AnyTagSet($this->store, ['users', 'posts']); // First tag 'users' has keys key1, key2 - $this->connection->shouldReceive('hlen') - ->once() + $this->connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(2); - $this->connection->shouldReceive('hkeys') - ->once() + ->returns(2); + $this->connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['key1', 'key2']); + ->returns(['key1', 'key2']); // Second tag 'posts' has keys key2, key3 (key2 is duplicate) - $this->connection->shouldReceive('hlen') - ->once() + $this->connection->client()->expects('hlen') ->with('prefix:_any:tag:posts:entries') - ->andReturn(2); - $this->connection->shouldReceive('hkeys') - ->once() + ->returns(2); + $this->connection->client()->expects('hkeys') ->with('prefix:_any:tag:posts:entries') - ->andReturn(['key2', 'key3']); + ->returns(['key2', 'key3']); $entries = $tagSet->entries(); @@ -111,14 +101,12 @@ public function testEntriesWithEmptyTagReturnsEmpty(): void { $tagSet = new AnyTagSet($this->store, ['users']); - $this->connection->shouldReceive('hlen') - ->once() + $this->connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(0); - $this->connection->shouldReceive('hkeys') - ->once() + ->returns(0); + $this->connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn([]); + ->returns([]); $entries = $tagSet->entries(); @@ -139,21 +127,19 @@ public function testFlushDeletesKeysAndScannedMemberships(): void $tagSet = new AnyTagSet($this->store, ['users']); // GetTaggedKeys for the flush operation - $this->connection->shouldReceive('hlen') - ->once() + $this->connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(2); - $this->connection->shouldReceive('hkeys') - ->once() + ->returns(2); + $this->connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['key1', 'key2']); + ->returns(['key1', 'key2']); $this->connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key2:_any:tags', 'prefix:key1', 'prefix:key2'], [2, 'key1', 'key2']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key2:_any:tags', 'prefix:key1', 'prefix:key2'], [2, 'key1', 'key2']) + ->returns(1); $this->connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) - ->andReturn([1, 1]); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) + ->returns([1, 1]); $this->assertTrue($tagSet->flush()); } @@ -163,21 +149,19 @@ public function testFlushTagDeletesSingleTag(): void $tagSet = new AnyTagSet($this->store, ['users', 'posts']); // GetTaggedKeys for the flush operation (only 'users' tag) - $this->connection->shouldReceive('hlen') - ->once() + $this->connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(1); - $this->connection->shouldReceive('hkeys') - ->once() + ->returns(1); + $this->connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['key1']); + ->returns(['key1']); $this->connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key1'], [1, 'key1']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key1'], [1, 'key1']) + ->returns(1); $this->connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) - ->andReturn([1, 1]); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) + ->returns([1, 1]); $result = $tagSet->flushTag('users'); @@ -189,33 +173,29 @@ public function testResetCallsFlush(): void $tagSet = new AnyTagSet($this->store, ['users', 'posts']); // GetTaggedKeys for both tags - $this->connection->shouldReceive('hlen') - ->once() + $this->connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(1); - $this->connection->shouldReceive('hkeys') - ->once() + ->returns(1); + $this->connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['key1']); + ->returns(['key1']); - $this->connection->shouldReceive('hlen') - ->once() + $this->connection->client()->expects('hlen') ->with('prefix:_any:tag:posts:entries') - ->andReturn(1); - $this->connection->shouldReceive('hkeys') - ->once() + ->returns(1); + $this->connection->client()->expects('hkeys') ->with('prefix:_any:tag:posts:entries') - ->andReturn(['key2']); + ->returns(['key2']); $this->connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key1'], [1, 'key1']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key1'], [1, 'key1']) + ->returns(1); $this->connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:posts:entries', 'prefix:key2:_any:tags', 'prefix:key2'], [1, 'key2']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_any:tag:posts:entries', 'prefix:key2:_any:tags', 'prefix:key2'], [1, 'key2']) + ->returns(1); $this->connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries', 'prefix:_any:tag:posts:entries'], ['users', 'posts']) - ->andReturn([2, 2]); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries', 'prefix:_any:tag:posts:entries'], ['users', 'posts']) + ->returns([2, 2]); $this->assertTrue($tagSet->reset()); } diff --git a/tests/Cache/Redis/AnyTaggedCacheTest.php b/tests/Cache/Redis/AnyTaggedCacheTest.php index 4325be7e62..66da2b81a6 100644 --- a/tests/Cache/Redis/AnyTaggedCacheTest.php +++ b/tests/Cache/Redis/AnyTaggedCacheTest.php @@ -28,7 +28,8 @@ use Hypervel\Cache\TaggedCache; use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Redis\Exceptions\LuaScriptException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use stdClass; @@ -211,9 +212,8 @@ public function testPutStoresValueWithTags(): void $connection = $this->mockConnection(); // Union mode uses Lua script via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users', 'posts'])->put('mykey', 'myvalue', 60); @@ -226,9 +226,8 @@ public function testPutWithNullTtlCallsForever(): void $connection = $this->mockConnection(); // Forever operation uses Lua script via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users', 'posts'])->put('mykey', 'myvalue', null); @@ -239,15 +238,14 @@ public function testPutWithNullTtlCallsForever(): void public function testPutWithZeroTtlDeletesPlainKey(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(1); + $connection->expects('evalWithShaCache') + ->returns(1); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $events->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); @@ -270,15 +268,15 @@ public function testPutWithArrayCallsPutMany(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->andReturn($connection); - $connection->shouldReceive('smembers')->andReturn($connection); - $connection->shouldReceive('exec')->andReturn([[], []]); - $connection->shouldReceive('setex')->andReturn($connection); - $connection->shouldReceive('del')->andReturn($connection); - $connection->shouldReceive('sadd')->andReturn($connection); - $connection->shouldReceive('expire')->andReturn($connection); - $connection->shouldReceive('hsetex')->andReturn($connection); - $connection->shouldReceive('zadd')->andReturn($connection); + $connection->client()->allows('pipeline')->returns($connection->client()); + $connection->client()->allows('smembers')->returns($connection->client()); + $connection->client()->allows('exec')->returns([[], []]); + $connection->client()->allows('setex')->returns($connection->client()); + $connection->client()->allows('del')->returns($connection->client()); + $connection->client()->allows('sadd')->returns($connection->client()); + $connection->client()->allows('expire')->returns($connection->client()); + $connection->client()->allows('hsetex')->returns($connection->client()); + $connection->client()->allows('zadd')->returns($connection->client()); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->put(['key1' => 'value1', 'key2' => 'value2'], 60); @@ -290,15 +288,15 @@ public function testPutManyStoresMultipleValues(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->andReturn($connection); - $connection->shouldReceive('smembers')->andReturn($connection); - $connection->shouldReceive('exec')->andReturn([[], []]); - $connection->shouldReceive('setex')->andReturn($connection); - $connection->shouldReceive('del')->andReturn($connection); - $connection->shouldReceive('sadd')->andReturn($connection); - $connection->shouldReceive('expire')->andReturn($connection); - $connection->shouldReceive('hsetex')->andReturn($connection); - $connection->shouldReceive('zadd')->andReturn($connection); + $connection->client()->allows('pipeline')->returns($connection->client()); + $connection->client()->allows('smembers')->returns($connection->client()); + $connection->client()->allows('exec')->returns([[], []]); + $connection->client()->allows('setex')->returns($connection->client()); + $connection->client()->allows('del')->returns($connection->client()); + $connection->client()->allows('sadd')->returns($connection->client()); + $connection->client()->allows('expire')->returns($connection->client()); + $connection->client()->allows('hsetex')->returns($connection->client()); + $connection->client()->allows('zadd')->returns($connection->client()); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->putMany(['key1' => 'value1', 'key2' => 'value2'], 120); @@ -311,9 +309,9 @@ public function testPutManyWithNullTtlCallsForeverForEach(): void $connection = $this->mockConnection(); // Forever for each key - called twice for 2 keys - $connection->shouldReceive('evalWithShaCache') - ->twice() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->times(2) + ->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->putMany(['key1' => 'value1', 'key2' => 'value2'], null); @@ -324,9 +322,8 @@ public function testPutManyWithNullTtlCallsForeverForEach(): void public function testPutManyWithZeroTtlDeletesPlainKeys(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(1); + $connection->expects('evalWithShaCache') + ->returns(1); $store = $this->createStore($connection); $cache = $store->setTagMode('any')->tags(['users']); @@ -340,15 +337,15 @@ public function testSetMultipleWritesThroughTaggedPath(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->andReturn($connection); - $connection->shouldReceive('smembers')->andReturn($connection); - $connection->shouldReceive('exec')->andReturn([[], []]); - $connection->shouldReceive('setex')->andReturn($connection); - $connection->shouldReceive('del')->andReturn($connection); - $connection->shouldReceive('sadd')->andReturn($connection); - $connection->shouldReceive('expire')->andReturn($connection); - $connection->shouldReceive('hsetex')->andReturn($connection); - $connection->shouldReceive('zadd')->andReturn($connection); + $connection->client()->allows('pipeline')->returns($connection->client()); + $connection->client()->allows('smembers')->returns($connection->client()); + $connection->client()->allows('exec')->returns([[], []]); + $connection->client()->allows('setex')->returns($connection->client()); + $connection->client()->allows('del')->returns($connection->client()); + $connection->client()->allows('sadd')->returns($connection->client()); + $connection->client()->allows('expire')->returns($connection->client()); + $connection->client()->allows('hsetex')->returns($connection->client()); + $connection->client()->allows('zadd')->returns($connection->client()); $store = $this->createStore($connection); $cache = $store->setTagMode('any')->tags(['users']); @@ -359,16 +356,13 @@ public function testSetMultipleWritesThroughTaggedPath(): void public function testArrayAccessSetWritesThroughTaggedPath(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); $store = $this->createStore($connection); $cache = $store->setTagMode('any')->tags(['users']); $cache['mykey'] = 'myvalue'; - - $this->assertTrue(true); } public function testAddStoresValueIfNotExists(): void @@ -376,13 +370,12 @@ public function testAddStoresValueIfNotExists(): void $connection = $this->mockConnection(); // Add uses Lua script with SET NX via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners'); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $store = $this->createStore($connection); $store->setTagMode('any'); @@ -396,14 +389,13 @@ public function testAddWithNullTtlStoresPermanently(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args): bool { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args): bool { $this->assertSame(0, $args[1]); return true; - }) - ->andReturn(true); + })) + ->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->add('mykey', 'myvalue', null); @@ -427,9 +419,8 @@ public function testForeverStoresValueIndefinitely(): void $connection = $this->mockConnection(); // Forever uses Lua script without expiration via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->forever('mykey', 'myvalue'); @@ -442,9 +433,8 @@ public function testIncrementReturnsNewValue(): void $connection = $this->mockConnection(); // Increment uses Lua script with INCRBY via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(5); + $connection->expects('evalWithShaCache') + ->returns(5); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->increment('counter'); @@ -456,9 +446,8 @@ public function testIncrementWithCustomValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(15); + $connection->expects('evalWithShaCache') + ->returns(15); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->increment('counter', 10); @@ -471,9 +460,8 @@ public function testDecrementReturnsNewValue(): void $connection = $this->mockConnection(); // Decrement uses Lua script with DECRBY via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(3); + $connection->expects('evalWithShaCache') + ->returns(3); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->decrement('counter'); @@ -485,9 +473,8 @@ public function testDecrementWithCustomValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(0); + $connection->expects('evalWithShaCache') + ->returns(0); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->decrement('counter', 5); @@ -501,18 +488,17 @@ public function testFlushDeletesAllTaggedItems(): void // GetTaggedKeys uses hlen to check size // When small (< threshold), it uses hkeys directly instead of scan - $connection->shouldReceive('hlen') - ->andReturn(2); - $connection->shouldReceive('hkeys') - ->once() - ->andReturn(['key1', 'key2']); + $connection->client()->allows('hlen') + ->returns(2); + $connection->client()->expects('hkeys') + ->returns(['key1', 'key2']); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key2:_any:tags', 'prefix:key1', 'prefix:key2'], [2, 'key1', 'key2']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key2:_any:tags', 'prefix:key1', 'prefix:key2'], [2, 'key1', 'key2']) + ->returns(1); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) - ->andReturn([1, 1]); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) + ->returns([1, 1]); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->flush(); @@ -524,17 +510,16 @@ public function testClearFlushesTaggedItems(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('hlen') - ->andReturn(2); - $connection->shouldReceive('hkeys') - ->once() - ->andReturn(['key1', 'key2']); + $connection->client()->allows('hlen') + ->returns(2); + $connection->client()->expects('hkeys') + ->returns(['key1', 'key2']); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key2:_any:tags', 'prefix:key1', 'prefix:key2'], [2, 'key1', 'key2']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key2:_any:tags', 'prefix:key1', 'prefix:key2'], [2, 'key1', 'key2']) + ->returns(1); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) - ->andReturn([1, 1]); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) + ->returns([1, 1]); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->clear(); @@ -546,10 +531,9 @@ public function testRememberRetrievesExistingValueFromStore(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturn(serialize('cached_value')); + ->returns(serialize('cached_value')); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->remember('mykey', 60, fn () => 'new_value'); @@ -559,8 +543,8 @@ public function testRememberRetrievesExistingValueFromStore(): void public function testRememberHandlesIncompleteClassBeforeDispatchingHitEvent(): void { - $store = m::mock(RedisStore::class); - $store->shouldReceive('get')->once()->with('mykey')->andReturn( + $store = Double::for(RedisStore::class); + $store->expects('get')->with('mykey')->returns( unserialize(serialize(new stdClass), ['allowed_classes' => false]) ); @@ -570,10 +554,10 @@ public function testRememberHandlesIncompleteClassBeforeDispatchingHitEvent(): v $sequence[] = ['handler', $key, $class]; }); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $events->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$sequence): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function (object $event) use (&$sequence): void { $sequence[] = $event::class; }); @@ -596,15 +580,13 @@ public function testRememberCallsCallbackAndStoresValueWhenMiss(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturnNull(); + ->returns(null); // Should store the value with tags via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); $callCount = 0; $store = $this->createStore($connection); @@ -622,26 +604,24 @@ public function testRememberNormalizesEnumKeyForRedisAndEvents(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:0') - ->andReturnNull(); + ->returns(null); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function (string $script, array $keys, array $args): bool { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function (string $script, array $keys, array $args): bool { $this->assertSame('prefix:0', $keys[0]); $this->assertSame('0', $args[5]); return true; - }) - ->andReturn(true); + })) + ->returns(true); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); @@ -668,29 +648,28 @@ public function testRememberNormalizesEnumKeyForRedisAndEvents(): void public function testPutDispatchesTheRepositoryFailureEvent(): void { - $put = m::mock(Put::class); - $put->shouldReceive('execute') - ->once() + $put = Double::for(Put::class); + $put->expects('execute') ->with('mykey', 'myvalue', 60, ['users']) - ->andReturnFalse(); + ->returns(false); - $operations = m::mock(AnyTagOperations::class); - $operations->shouldReceive('put')->once()->andReturn($put); + $operations = Double::for(AnyTagOperations::class); + $operations->expects('put')->returns($put); - $store = m::mock(RedisStore::class); - $store->shouldReceive('anyTagOps')->once()->andReturn($operations); + $store = Double::for(RedisStore::class); + $store->expects('anyTagOps')->returns($operations); - $tags = m::mock(AnyTagSet::class); - $tags->shouldReceive('getNames')->andReturn(['users']); + $tags = Double::for(AnyTagSet::class); + $tags->allows('getNames')->returns(['users']); $cache = new AnyTaggedCache($store, $tags); - $store->shouldReceive('tags')->once()->with(['users'])->andReturn($cache); + $store->expects('tags')->with(['users'])->returns($cache); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $events->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); @@ -708,14 +687,14 @@ public function testPutDispatchesTheRepositoryFailureEvent(): void public function testAnyTaggedCacheSkipsEventDispatchSeamWithoutListenersAndEntersItWithListeners(): void { - $put = m::mock(Put::class); - $put->shouldReceive('execute')->twice()->andReturnTrue(); - $operations = m::mock(AnyTagOperations::class); - $operations->shouldReceive('put')->twice()->andReturn($put); - $store = m::mock(RedisStore::class); - $store->shouldReceive('anyTagOps')->twice()->andReturn($operations); - $tags = m::mock(AnyTagSet::class); - $tags->shouldReceive('getNames')->andReturn(['users']); + $put = Double::for(Put::class); + $put->expects('execute')->times(2)->returns(true); + $operations = Double::for(AnyTagOperations::class); + $operations->expects('put')->times(2)->returns($put); + $store = Double::for(RedisStore::class); + $store->expects('anyTagOps')->times(2)->returns($operations); + $tags = Double::for(AnyTagSet::class); + $tags->allows('getNames')->returns(['users']); $cache = new class($store, $tags) extends AnyTaggedCache { public int $eventCalls = 0; @@ -727,18 +706,18 @@ protected function event(object $event): void parent::event($event); } }; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(false); + $events->expects('dispatch')->never(); $cache->setEventDispatcher($events); $this->assertTrue($cache->put('first', 'value', 60)); $this->assertSame(0, $cache->eventCalls); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $events->shouldReceive('dispatch')->twice()->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->expects('dispatch')->times(2)->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); $cache->setEventDispatcher($events); @@ -755,14 +734,13 @@ protected function event(object $event): void public function testPutDispatchesTheRepositoryFailureEventWhenTheOperationThrows(): void { $exception = new RuntimeException('write failed'); - $put = m::mock(Put::class); - $put->shouldReceive('execute') - ->once() + $put = Double::for(Put::class); + $put->expects('execute') ->with('mykey', 'myvalue', 60, ['users']) - ->andThrow($exception); + ->throws($exception); - $operations = m::mock(AnyTagOperations::class); - $operations->shouldReceive('put')->once()->andReturn($put); + $operations = Double::for(AnyTagOperations::class); + $operations->expects('put')->returns($put); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -786,14 +764,13 @@ public function testPutDoesNotDispatchFailureEventWhenTheOperationIsCanceled(boo if ($cleanupThrows) { $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } - $put = m::mock(Put::class); - $put->shouldReceive('execute') - ->once() + $put = Double::for(Put::class); + $put->expects('execute') ->with('mykey', 'myvalue', 60, ['users']) - ->andThrow($cancellation); + ->throws($cancellation); - $operations = m::mock(AnyTagOperations::class); - $operations->shouldReceive('put')->once()->andReturn($put); + $operations = Double::for(AnyTagOperations::class); + $operations->expects('put')->returns($put); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -811,14 +788,13 @@ public function testPutManyDispatchesRepositoryFailureEventsWhenTheOperationThro { $exception = new RuntimeException('batch write failed'); $values = ['first' => 'one', 'second' => 'two']; - $putMany = m::mock(PutMany::class); - $putMany->shouldReceive('execute') - ->once() + $putMany = Double::for(PutMany::class); + $putMany->expects('execute') ->with($values, 60, ['users']) - ->andThrow($exception); + ->throws($exception); - $operations = m::mock(AnyTagOperations::class); - $operations->shouldReceive('putMany')->once()->andReturn($putMany); + $operations = Double::for(AnyTagOperations::class); + $operations->expects('putMany')->returns($putMany); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -846,14 +822,13 @@ public function testPutManyDoesNotDispatchFailureEventsWhenTheOperationIsCancele $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } $values = ['first' => 'one', 'second' => 'two']; - $putMany = m::mock(PutMany::class); - $putMany->shouldReceive('execute') - ->once() + $putMany = Double::for(PutMany::class); + $putMany->expects('execute') ->with($values, 60, ['users']) - ->andThrow($cancellation); + ->throws($cancellation); - $operations = m::mock(AnyTagOperations::class); - $operations->shouldReceive('putMany')->once()->andReturn($putMany); + $operations = Double::for(AnyTagOperations::class); + $operations->expects('putMany')->returns($putMany); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -869,12 +844,12 @@ public function testPutManyDoesNotDispatchFailureEventsWhenTheOperationIsCancele public function testEmptyPutManyReturnsTrueWithoutOperationOrEvents(): void { - $store = m::mock(RedisStore::class); - $store->shouldNotReceive('anyTagOps'); - $tags = m::mock(AnyTagSet::class); - $events = m::mock(Dispatcher::class); - $events->shouldNotReceive('hasListeners'); - $events->shouldNotReceive('dispatch'); + $store = Double::for(RedisStore::class); + $store->expects('anyTagOps')->never(); + $tags = Double::for(AnyTagSet::class); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->never(); + $events->expects('dispatch')->never(); $tagged = new AnyTaggedCache($store, $tags); $tagged->setEventDispatcher($events); @@ -884,14 +859,13 @@ public function testEmptyPutManyReturnsTrueWithoutOperationOrEvents(): void public function testForeverDispatchesTheRepositoryFailureEventWhenTheOperationThrows(): void { $exception = new RuntimeException('forever write failed'); - $forever = m::mock(Forever::class); - $forever->shouldReceive('execute') - ->once() + $forever = Double::for(Forever::class); + $forever->expects('execute') ->with('mykey', 'myvalue', ['users']) - ->andThrow($exception); + ->throws($exception); - $operations = m::mock(AnyTagOperations::class); - $operations->shouldReceive('forever')->once()->andReturn($forever); + $operations = Double::for(AnyTagOperations::class); + $operations->expects('forever')->returns($forever); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -915,14 +889,13 @@ public function testForeverDoesNotDispatchFailureEventWhenTheOperationIsCanceled if ($cleanupThrows) { $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } - $forever = m::mock(Forever::class); - $forever->shouldReceive('execute') - ->once() + $forever = Double::for(Forever::class); + $forever->expects('execute') ->with('mykey', 'myvalue', ['users']) - ->andThrow($cancellation); + ->throws($cancellation); - $operations = m::mock(AnyTagOperations::class); - $operations->shouldReceive('forever')->once()->andReturn($forever); + $operations = Double::for(AnyTagOperations::class); + $operations->expects('forever')->returns($forever); $captured = []; $tagged = $this->taggedCacheWithOperations($operations, $captured); @@ -940,8 +913,8 @@ public function testRememberNullableStoresAndReturnsNonNullValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:mykey')->andReturnNull(); - $connection->shouldReceive('evalWithShaCache')->once()->andReturn(true); + $connection->client()->expects('get')->with('prefix:mykey')->returns(null); + $connection->expects('evalWithShaCache')->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->rememberNullable('mykey', 60, fn () => 'computed'); @@ -953,19 +926,18 @@ public function testRememberNullableStoresSentinelWhenCallbackReturnsNull(): voi { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:mykey')->andReturnNull(); + $connection->client()->expects('get')->with('prefix:mykey')->returns(null); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args): bool { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args): bool { foreach (array_merge((array) $keys, (array) $args) as $arg) { if (is_string($arg) && @unserialize($arg) === NullSentinel::VALUE) { return true; } } return false; - }) - ->andReturn(true); + })) + ->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->rememberNullable('mykey', 60, fn () => null); @@ -977,10 +949,9 @@ public function testRememberNullableReturnsNullOnSentinelHitWithoutInvokingCallb { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $invoked = false; $store = $this->createStore($connection); @@ -997,16 +968,15 @@ public function testRememberNullableFiresCacheHitWithNullPayloadOnSentinelHit(): { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); @@ -1026,14 +996,14 @@ public function testRememberNullableFiresKeyWrittenWithNullPayloadOnCacheMiss(): { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:mykey')->andReturnNull(); - $connection->shouldReceive('evalWithShaCache')->once()->andReturn(true); + $connection->client()->expects('get')->with('prefix:mykey')->returns(null); + $connection->expects('evalWithShaCache')->returns(true); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function ($event) use (&$captured) { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function ($event) use (&$captured) { $captured[] = $event; }); @@ -1058,10 +1028,9 @@ public function testPlainRememberUnwrapsSentinelOnCachedNullHit(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $invoked = false; $store = $this->createStore($connection); @@ -1078,10 +1047,9 @@ public function testRememberForeverRetrievesExistingValueFromStore(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturn(serialize('cached_value')); + ->returns(serialize('cached_value')); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->rememberForever('mykey', fn () => 'new_value'); @@ -1093,16 +1061,15 @@ public function testRememberForeverNormalizesEnumKeyForRedisAndEvents(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:1') - ->andReturn(serialize('cached_settings')); + ->returns(serialize('cached_settings')); $captured = []; - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturn(true); - $events->shouldReceive('dispatch') - ->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch') + ->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); @@ -1123,15 +1090,13 @@ public function testRememberForeverCallsCallbackAndStoresValueWhenMiss(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturnNull(); + ->returns(null); // Should store the value forever with tags using evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->rememberForever('mykey', fn () => 'computed_value'); @@ -1143,18 +1108,17 @@ public function testRememberForeverNullableStoresSentinelWhenCallbackReturnsNull { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:mykey')->andReturnNull(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args): bool { + $connection->client()->expects('get')->with('prefix:mykey')->returns(null); + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args): bool { foreach (array_merge((array) $keys, (array) $args) as $arg) { if (is_string($arg) && @unserialize($arg) === NullSentinel::VALUE) { return true; } } return false; - }) - ->andReturn(true); + })) + ->returns(true); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->rememberForeverNullable('mykey', fn () => null); @@ -1166,10 +1130,9 @@ public function testSearNullableDelegatesToRememberForeverNullable(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->searNullable('mykey', fn () => 'should-not-run'); @@ -1181,10 +1144,9 @@ public function testPlainRememberForeverUnwrapsSentinelOnCachedNullHit(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturn(serialize(NullSentinel::VALUE)); + ->returns(serialize(NullSentinel::VALUE)); $invoked = false; $store = $this->createStore($connection); @@ -1211,10 +1173,9 @@ public function testItemKeyReturnsKeyUnchanged(): void $connection = $this->mockConnection(); // In any mode, keys are NOT namespaced by tags - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') // Should NOT have tag namespace prefix - ->andReturn(serialize('value')); + ->returns(serialize('value')); $store = $this->createStore($connection); $store->setTagMode('any')->tags(['users'])->remember('mykey', 60, fn () => 'fallback'); @@ -1224,9 +1185,8 @@ public function testIncrementThrowsOnLuaFailure(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andThrow(new LuaScriptException('Lua script execution failed')); + $connection->expects('evalWithShaCache') + ->throws(new LuaScriptException('Lua script execution failed')); $this->expectException(LuaScriptException::class); @@ -1238,9 +1198,8 @@ public function testDecrementThrowsOnLuaFailure(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andThrow(new LuaScriptException('Lua script execution failed')); + $connection->expects('evalWithShaCache') + ->throws(new LuaScriptException('Lua script execution failed')); $this->expectException(LuaScriptException::class); @@ -1253,10 +1212,9 @@ public function testRememberPropagatesExceptionFromCallback(): void $connection = $this->mockConnection(); // Client returns null (cache miss) - callback will be executed - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturnNull(); + ->returns(null); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Callback failed'); @@ -1272,10 +1230,9 @@ public function testRememberForeverPropagatesExceptionFromCallback(): void $connection = $this->mockConnection(); // Client returns null (cache miss) - callback will be executed - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturnNull(); + ->returns(null); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Forever callback failed'); @@ -1291,10 +1248,9 @@ public function testRememberDoesNotCallCallbackWhenValueExists(): void $connection = $this->mockConnection(); // Client returns existing value (cache hit) - $connection->shouldReceive('get') - ->once() + $connection->client()->expects('get') ->with('prefix:mykey') - ->andReturn(serialize('cached_value')); + ->returns(serialize('cached_value')); $callCount = 0; $store = $this->createStore($connection); @@ -1313,19 +1269,17 @@ public function testItemsReturnsGenerator(): void $connection = $this->mockConnection(); // GetTaggedKeys uses hlen to check size first - $connection->shouldReceive('hlen') - ->andReturn(2); + $connection->client()->allows('hlen') + ->returns(2); // When small (< threshold), it uses hkeys directly - $connection->shouldReceive('hkeys') - ->once() - ->andReturn(['key1', 'key2']); + $connection->client()->expects('hkeys') + ->returns(['key1', 'key2']); // Get values for found keys (mget receives array) - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with(['prefix:key1', 'prefix:key2']) - ->andReturn([serialize('value1'), serialize('value2')]); + ->returns([serialize('value1'), serialize('value2')]); $store = $this->createStore($connection); $result = $store->setTagMode('any')->tags(['users'])->items(); @@ -1351,18 +1305,18 @@ public function testFlexibleNullableThrowsBadMethodCallException(): void private function taggedCacheWithOperations(AnyTagOperations $operations, array &$captured): AnyTaggedCache { - $store = m::mock(RedisStore::class); - $store->shouldReceive('anyTagOps')->once()->andReturn($operations); + $store = Double::for(RedisStore::class); + $store->expects('anyTagOps')->returns($operations); - $tags = m::mock(AnyTagSet::class); - $tags->shouldReceive('getNames')->andReturn(['users']); + $tags = Double::for(AnyTagSet::class); + $tags->allows('getNames')->returns(['users']); $cache = new AnyTaggedCache($store, $tags); - $store->shouldReceive('tags')->once()->with(['users'])->andReturn($cache); + $store->expects('tags')->with(['users'])->returns($cache); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->withAnyArgs()->andReturnTrue(); - $events->shouldReceive('dispatch')->andReturnUsing(function (object $event) use (&$captured): void { + $events = Double::for(Dispatcher::class); + $events->allows('hasListeners')->returns(true); + $events->allows('dispatch')->resolves(function (object $event) use (&$captured): void { $captured[] = $event; }); diff --git a/tests/Cache/Redis/Console/BenchmarkCommandTest.php b/tests/Cache/Redis/Console/BenchmarkCommandTest.php index 04bdf007a7..970ebb6bc4 100644 --- a/tests/Cache/Redis/Console/BenchmarkCommandTest.php +++ b/tests/Cache/Redis/Console/BenchmarkCommandTest.php @@ -16,7 +16,8 @@ use Hypervel\Console\OutputStyle; use Hypervel\Contracts\Cache\Factory as CacheContract; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; @@ -25,6 +26,8 @@ class BenchmarkCommandTest extends TestCase { + use VerifiesDoubles; + public function testSetupPreservesZeroStoreOption(): void { $this->mockCacheStore('0'); @@ -76,8 +79,8 @@ public function testSetupFailsGracefullyWhenNoRedisStoreCanBeDetected(): void 'file' => ['driver' => 'file'], ]); - $cache = m::mock(CacheContract::class); - $cache->shouldNotReceive('store'); + $cache = Double::for(CacheContract::class); + $cache->expects('store')->never(); $this->app->instance(CacheContract::class, $cache); $command = $this->createCommand(); @@ -99,8 +102,8 @@ public function testMemoryRecoveryGuidanceIncludesEveryCleanupPattern(): void 'all-tag-pattern:*', ]; - $context = m::mock(BenchmarkContext::class); - $context->expects('getCleanupPatterns')->once()->andReturn($patterns); + $context = Double::for(BenchmarkContext::class); + $context->expects('getCleanupPatterns')->returns($patterns); $command = $this->createCommand(); $output = new BufferedOutput; @@ -168,7 +171,7 @@ public function testValidTagModeIsPassedThroughAsAnEnum(): void { $this->mockFullCacheStore('redis'); $context = $this->mockBenchmarkContext(); - $context->expects('getStoreInstance')->andReturn(m::mock(RedisStore::class)); + $context->expects('getStoreInstance')->returns(Double::for(RedisStore::class)); $command = $this->createFullCommand($context); $this->assertSame(Command::SUCCESS, $command->run(new ArrayInput([ @@ -279,16 +282,19 @@ public function testSystemInformationFailureIsReportedWithoutStoppingBenchmark() ); } + /** + * Configure a Redis cache store for command setup. + */ private function mockCacheStore(string $name): void { - $store = m::mock(RedisStore::class); + $store = Double::for(RedisStore::class); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore')->once()->andReturn($store); - $repository->shouldReceive('get')->once()->with('test')->andReturnNull(); + $repository = Double::for(Repository::class); + $repository->expects('getStore')->returns($store); + $repository->expects('get')->with('test')->returns(null); - $cache = m::mock(CacheContract::class); - $cache->shouldReceive('store')->twice()->with($name)->andReturn($repository); + $cache = Double::for(CacheContract::class); + $cache->expects('store')->times(2)->with($name)->returns($repository); $this->app->instance(CacheContract::class, $cache); } @@ -298,30 +304,29 @@ private function mockCacheStore(string $name): void */ private function mockFullCacheStore(string $name, ?Throwable $displayException = null): void { - $store = m::mock(RedisStore::class); + $store = Double::for(RedisStore::class); if ($displayException === null) { - $storeContext = m::mock(StoreContext::class); - $storeContext->shouldReceive('withConnection') - ->once() - ->andReturn(['redis_version' => '8.0.0']); + $storeContext = Double::for(StoreContext::class); + $storeContext->expects('withConnection') + ->returns(['redis_version' => '8.0.0']); - $store->shouldReceive('getContext')->once()->andReturn($storeContext); - $store->shouldReceive('getTagMode')->once()->andReturn(TagMode::Any); + $store->expects('getContext')->returns($storeContext); + $store->expects('getTagMode')->returns(TagMode::Any); } else { - $store->shouldNotReceive('getContext'); - $store->shouldNotReceive('getTagMode'); + $store->expects('getContext')->never(); + $store->expects('getTagMode')->never(); } - $repository = m::mock(Repository::class); + $repository = Double::for(Repository::class); if ($displayException === null) { - $repository->shouldReceive('getStore')->twice()->andReturn($store); + $repository->expects('getStore')->times(2)->returns($store); } else { $getStoreCalls = 0; - $repository->shouldReceive('getStore') - ->twice() - ->andReturnUsing(function () use (&$getStoreCalls, $displayException, $store): RedisStore { + $repository->expects('getStore') + ->times(2) + ->resolves(function () use (&$getStoreCalls, $displayException, $store): RedisStore { ++$getStoreCalls; if ($getStoreCalls === 2) { @@ -332,10 +337,10 @@ private function mockFullCacheStore(string $name, ?Throwable $displayException = }); } - $repository->shouldReceive('get')->once()->with('test')->andReturnNull(); + $repository->expects('get')->with('test')->returns(null); - $cacheManager = m::mock(CacheContract::class); - $cacheManager->shouldReceive('store')->times(3)->with($name)->andReturn($repository); + $cacheManager = Double::for(CacheContract::class); + $cacheManager->expects('store')->times(3)->with($name)->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); } @@ -345,14 +350,12 @@ private function mockFullCacheStore(string $name, ?Throwable $displayException = */ private function mockBenchmarkContext(?Throwable $cleanupException = null): BenchmarkContext { - $context = m::mock(BenchmarkContext::class); - $context->allows('getCleanupPatterns')->andReturn(['cache:_bench:*']); - $cleanup = $context->shouldReceive('cleanup')->once(); + $context = Double::for(BenchmarkContext::class); + $context->allows('getCleanupPatterns')->returns(['cache:_bench:*']); + $cleanup = $context->expects('cleanup'); - if ($cleanupException === null) { - $cleanup->andReturnNull(); - } else { - $cleanup->andThrow($cleanupException); + if ($cleanupException !== null) { + $cleanup->throws($cleanupException); } return $context; @@ -372,6 +375,9 @@ private function benchmarkInput(): ArrayInput ]); } + /** + * Create a command limited to setup. + */ private function createCommand(): TestableBenchmarkCommand { $command = new TestableBenchmarkCommand; diff --git a/tests/Cache/Redis/Console/Doctor/Checks/CleanupVerificationCheckTest.php b/tests/Cache/Redis/Console/Doctor/Checks/CleanupVerificationCheckTest.php index 06eacc9127..3658a2b0d6 100644 --- a/tests/Cache/Redis/Console/Doctor/Checks/CleanupVerificationCheckTest.php +++ b/tests/Cache/Redis/Console/Doctor/Checks/CleanupVerificationCheckTest.php @@ -12,15 +12,18 @@ use Hypervel\Cache\TagMode; use Hypervel\Redis\PhpRedisClusterConnection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CleanupVerificationCheckTest extends TestCase { + use VerifiesDoubles; + public function testVerificationScansLogicalPatternsThroughTheClusterAwareHelper(): void { - $connection = m::mock(PhpRedisClusterConnection::class); - $store = m::mock(RedisStore::class); - $store->allows('getTagMode')->andReturn(TagMode::All); + $connection = Double::for(PhpRedisClusterConnection::class); + $store = Double::for(RedisStore::class); + $store->allows('getTagMode')->returns(TagMode::All); $context = new DoctorContext( cache: new Repository($store), store: $store, @@ -36,7 +39,7 @@ public function testVerificationScansLogicalPatternsThroughTheClusterAwareHelper 'cache:_all:tag:_doctor:test:*', ] as $pattern) { $connection->expects('safeScan')->with($pattern, 100) - ->andReturnUsing(static function () use ($pattern): Generator { + ->resolves(static function () use ($pattern): Generator { if ($pattern === 'cache:_doctor:test:*') { yield 'cache:_doctor:test:leftover'; } diff --git a/tests/Cache/Redis/Console/DoctorCommandTest.php b/tests/Cache/Redis/Console/DoctorCommandTest.php index 580fe674ff..4189aaa509 100644 --- a/tests/Cache/Redis/Console/DoctorCommandTest.php +++ b/tests/Cache/Redis/Console/DoctorCommandTest.php @@ -22,10 +22,10 @@ use Hypervel\Console\OutputStyle; use Hypervel\Contracts\Cache\Factory as CacheContract; use Hypervel\Contracts\Cache\Store; -use Hypervel\Redis\PhpRedisConnection; use Hypervel\Redis\RedisConnection; -use Hypervel\Testbench\TestCase; -use Mockery as m; +use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; @@ -33,7 +33,7 @@ use Symfony\Component\Console\Output\NullOutput; use Throwable; -class DoctorCommandTest extends TestCase +class DoctorCommandTest extends RedisCacheTestCase { private const int CLEANUP_TEST_TAG_COUNT = 25; @@ -84,8 +84,8 @@ public static function phpRedisRequirements(): array #[DataProvider('serverRequirements')] public function testRedisVersionCheckUsesFeatureRequirement(string $taggingMode, array $info, bool $supported): void { - $connection = m::mock(RedisConnection::class); - $connection->allows('info')->with('server')->andReturn($info); + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->allows('info')->with('server')->returns($info); $check = new RedisVersionCheck($connection, $taggingMode); @@ -115,10 +115,10 @@ public static function serverRequirements(): array public function testHashFieldExpirationCheckSkipsAllMode(): void { - $connection = m::mock(RedisConnection::class); - $connection->shouldNotReceive('hsetex'); - $connection->shouldNotReceive('hexpire'); - $connection->shouldNotReceive('del'); + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->expects('hsetex')->never(); + $connection->client()->expects('hexpire')->never(); + $connection->client()->expects('del')->never(); $check = new HashFieldExpirationCheck($connection, 'all'); $result = $check->run(); @@ -135,19 +135,16 @@ public function testHashFieldExpirationCheckSkipsAllMode(): void public function testHashFieldExpirationCheckProbesHsetexAndHexpireInAnyMode(): void { - $connection = m::mock(RedisConnection::class); - $connection->shouldReceive('hsetex') - ->once() - ->with(m::pattern('/^erc:doctor:hash-field-expiration-test:/'), ['field' => '1'], ['EX' => 60]) - ->andReturn(true); - $connection->shouldReceive('hexpire') - ->once() - ->with(m::pattern('/^erc:doctor:hash-field-expiration-test:/'), 60, ['field']) - ->andReturn([1]); - $connection->shouldReceive('del') - ->once() - ->with(m::pattern('/^erc:doctor:hash-field-expiration-test:/')) - ->andReturn(1); + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->expects('hsetex') + ->with(Argument::matches('/^erc:doctor:hash-field-expiration-test:/'), ['field' => '1'], ['EX' => 60]) + ->returns(1); + $connection->client()->expects('hexpire') + ->with(Argument::matches('/^erc:doctor:hash-field-expiration-test:/'), 60, ['field']) + ->returns([1]); + $connection->client()->expects('del') + ->with(Argument::matches('/^erc:doctor:hash-field-expiration-test:/')) + ->returns(1); $check = new HashFieldExpirationCheck($connection, 'any'); $result = $check->run(); @@ -164,16 +161,14 @@ public function testHashFieldExpirationCheckProbesHsetexAndHexpireInAnyMode(): v public function testHashFieldExpirationCheckReportsFixInstructionsWhenProbeFails(): void { - $connection = m::mock(RedisConnection::class); - $connection->shouldReceive('hsetex') - ->once() - ->with(m::pattern('/^erc:doctor:hash-field-expiration-test:/'), ['field' => '1'], ['EX' => 60]) - ->andThrow(new RuntimeException('unsupported command')); - $connection->shouldReceive('hexpire')->never(); - $connection->shouldReceive('del') - ->once() - ->with(m::pattern('/^erc:doctor:hash-field-expiration-test:/')) - ->andReturn(0); + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->expects('hsetex') + ->with(Argument::matches('/^erc:doctor:hash-field-expiration-test:/'), ['field' => '1'], ['EX' => 60]) + ->throws(new RuntimeException('unsupported command')); + $connection->client()->expects('hexpire')->never(); + $connection->client()->expects('del') + ->with(Argument::matches('/^erc:doctor:hash-field-expiration-test:/')) + ->returns(0); $check = new HashFieldExpirationCheck($connection, 'any'); $result = $check->run(); @@ -193,19 +188,16 @@ public function testHashFieldExpirationCheckReportsFixInstructionsWhenProbeFails public function testHashFieldExpirationCheckReportsFailureWhenProbeReturnsFalse(): void { - $connection = m::mock(RedisConnection::class); - $connection->shouldReceive('hsetex') - ->once() - ->with(m::pattern('/^erc:doctor:hash-field-expiration-test:/'), ['field' => '1'], ['EX' => 60]) - ->andReturn(false); - $connection->shouldReceive('hexpire') - ->once() - ->with(m::pattern('/^erc:doctor:hash-field-expiration-test:/'), 60, ['field']) - ->andReturn(false); - $connection->shouldReceive('del') - ->once() - ->with(m::pattern('/^erc:doctor:hash-field-expiration-test:/')) - ->andReturn(0); + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->expects('hsetex') + ->with(Argument::matches('/^erc:doctor:hash-field-expiration-test:/'), ['field' => '1'], ['EX' => 60]) + ->returns(false); + $connection->client()->expects('hexpire') + ->with(Argument::matches('/^erc:doctor:hash-field-expiration-test:/'), 60, ['field']) + ->returns(false); + $connection->client()->expects('del') + ->with(Argument::matches('/^erc:doctor:hash-field-expiration-test:/')) + ->returns(0); $check = new HashFieldExpirationCheck($connection, 'any'); $result = $check->run(); @@ -336,26 +328,25 @@ public function testSystemInformationErrorIsVisibleAndDoesNotStopDiagnostics(): { config()->set('cache.default', 'redis'); $displayException = new Error('system information failed'); - $connection = m::mock(RedisConnection::class); - $storeContext = m::mock(StoreContext::class); - $storeContext->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); + $connection = $this->mockConnection()->shouldTransform(false); + $storeContext = Double::for(StoreContext::class); + $storeContext->expects('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); - $store = m::mock(RedisStore::class); - $store->shouldReceive('getContext')->once()->andReturn($storeContext); - $store->shouldReceive('getTagMode')->once()->andReturn(TagMode::Any); - $store->shouldReceive('getPrefix')->once()->andReturn('cache:'); + $store = Double::for(RedisStore::class); + $store->expects('getContext')->returns($storeContext); + $store->expects('getTagMode')->returns(TagMode::Any); + $store->expects('getPrefix')->returns('cache:'); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore')->once()->andReturn($store); + $repository = Double::for(Repository::class); + $repository->expects('getStore')->returns($store); $storeCalls = 0; - $cacheManager = m::mock(CacheContract::class); - $cacheManager->shouldReceive('store') - ->twice() + $cacheManager = Double::for(CacheContract::class); + $cacheManager->expects('store') + ->times(2) ->with('redis') - ->andReturnUsing(function () use (&$storeCalls, $displayException, $repository): Repository { + ->resolves(function () use (&$storeCalls, $displayException, $repository): Repository { ++$storeCalls; if ($storeCalls === 1) { @@ -382,16 +373,16 @@ public function testSystemInformationErrorIsVisibleAndDoesNotStopDiagnostics(): public function testDoctorFailsForNonRedisStore(): void { - $nonRedisStore = m::mock(Store::class); + $nonRedisStore = Double::for(Store::class); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore') - ->andReturn($nonRedisStore); + $repository = Double::for(Repository::class); + $repository->allows('getStore') + ->returns($nonRedisStore); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->allows('store') ->with('file') - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); @@ -405,43 +396,43 @@ public function testDoctorFailsForNonRedisStore(): void public function testDoctorDetectsRedisStoreFromConfig(): void { // Set up config with a redis store - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('array') + $config = Double::for(ConfigRepository::class); + $config->allows('array') ->with('cache.stores') - ->andReturn([ + ->returns([ 'file' => ['driver' => 'file'], 'redis' => ['driver' => 'redis', 'connection' => 'default'], ]); - $config->shouldReceive('string') + $config->allows('string') ->with('cache.default') - ->andReturn('file'); - $config->shouldReceive('get') + ->returns('file'); + $config->allows('get') ->with('cache.stores.redis.connection', 'default') - ->andReturn('default'); + ->returns('default'); $this->app->instance('config', $config); // Mock Redis store - $context = m::mock(StoreContext::class); - $context->shouldReceive('withConnection') - ->andReturnUsing(function (callable $callback): mixed { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('info')->with('server')->andReturn(['redis_version' => '7.0.0']); + $context = Double::for(StoreContext::class); + $context->allows('withConnection') + ->resolves(function (callable $callback): mixed { + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->allows('info')->with('server')->returns(['redis_version' => '7.0.0']); return $callback($connection); }); - $store = m::mock(RedisStore::class); - $store->shouldReceive('getTagMode')->andReturn(TagMode::Any); - $store->shouldReceive('getContext')->andReturn($context); - $store->shouldReceive('getPrefix')->andReturn('cache:'); + $store = Double::for(RedisStore::class); + $store->allows('getTagMode')->returns(TagMode::Any); + $store->allows('getContext')->returns($context); + $store->allows('getPrefix')->returns('cache:'); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore')->andReturn($store); + $repository = Double::for(Repository::class); + $repository->allows('getStore')->returns($store); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->allows('store') ->with('redis') - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); @@ -468,37 +459,37 @@ public function testDoctorUsesZeroNamedStore(): void return; } - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string') + $config = Double::for(ConfigRepository::class); + $config->allows('string') ->with('cache.default') - ->andReturn('file'); - $config->shouldReceive('get') + ->returns('file'); + $config->allows('get') ->with('cache.stores.0.connection', 'default') - ->andReturn('custom'); + ->returns('custom'); $this->app->instance('config', $config); // Mock Redis store - $context = m::mock(StoreContext::class); - $context->shouldReceive('withConnection') - ->andReturnUsing(function (callable $callback): mixed { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('info')->with('server')->andReturn(['redis_version' => '7.0.0']); + $context = Double::for(StoreContext::class); + $context->allows('withConnection') + ->resolves(function (callable $callback): mixed { + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->allows('info')->with('server')->returns(['redis_version' => '7.0.0']); return $callback($connection); }); - $store = m::mock(RedisStore::class); - $store->shouldReceive('getTagMode')->andReturn(TagMode::All); - $store->shouldReceive('getContext')->andReturn($context); - $store->shouldReceive('getPrefix')->andReturn('cache:'); + $store = Double::for(RedisStore::class); + $store->allows('getTagMode')->returns(TagMode::All); + $store->allows('getContext')->returns($context); + $store->allows('getPrefix')->returns('cache:'); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore')->andReturn($store); + $repository = Double::for(Repository::class); + $repository->allows('getStore')->returns($store); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->allows('store') ->with('0') - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); @@ -527,10 +518,10 @@ protected function runCleanupVerification(DoctorContext $context): void public function testDoctorRunsChecksWhileRedisConnectionIsBorrowed(): void { - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string') + $config = Double::for(ConfigRepository::class); + $config->allows('string') ->with('cache.default') - ->andReturn('redis'); + ->returns('redis'); $this->app->instance('config', $config); @@ -539,16 +530,15 @@ public function testDoctorRunsChecksWhileRedisConnectionIsBorrowed(): void $this->assertTrue($borrowedConnection); }; - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('info') - ->once() + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->expects('info') ->with('server') - ->andReturn(['redis_version' => '7.0.0']); + ->returns(['redis_version' => '7.0.0']); - $context = m::mock(StoreContext::class); - $context->shouldReceive('withConnection') - ->twice() - ->andReturnUsing(function (callable $callback) use (&$borrowedConnection, $connection): mixed { + $context = Double::for(StoreContext::class); + $context->expects('withConnection') + ->times(2) + ->resolves(function (callable $callback) use (&$borrowedConnection, $connection): mixed { $borrowedConnection = true; try { @@ -558,18 +548,18 @@ public function testDoctorRunsChecksWhileRedisConnectionIsBorrowed(): void } }); - $store = m::mock(RedisStore::class); - $store->shouldReceive('getTagMode')->andReturn(TagMode::Any); - $store->shouldReceive('getContext')->andReturn($context); - $store->shouldReceive('getPrefix')->andReturn('cache:'); + $store = Double::for(RedisStore::class); + $store->allows('getTagMode')->returns(TagMode::Any); + $store->allows('getContext')->returns($context); + $store->allows('getPrefix')->returns('cache:'); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore')->andReturn($store); + $repository = Double::for(Repository::class); + $repository->allows('getStore')->returns($store); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->allows('store') ->with('redis') - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); @@ -614,37 +604,37 @@ protected function cleanup(DoctorContext $context, bool $silent = false): void public function testDoctorDisplaysTagMode(): void { - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('string') + $config = Double::for(ConfigRepository::class); + $config->allows('string') ->with('cache.default') - ->andReturn('redis'); - $config->shouldReceive('get') + ->returns('redis'); + $config->allows('get') ->with('cache.stores.redis.connection', 'default') - ->andReturn('default'); + ->returns('default'); $this->app->instance('config', $config); // Mock Redis store with 'all' mode - $context = m::mock(StoreContext::class); - $context->shouldReceive('withConnection') - ->andReturnUsing(function (callable $callback): mixed { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('info')->with('server')->andReturn(['redis_version' => '7.0.0']); + $context = Double::for(StoreContext::class); + $context->allows('withConnection') + ->resolves(function (callable $callback): mixed { + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->allows('info')->with('server')->returns(['redis_version' => '7.0.0']); return $callback($connection); }); - $store = m::mock(RedisStore::class); - $store->shouldReceive('getTagMode')->andReturn(TagMode::All); - $store->shouldReceive('getContext')->andReturn($context); - $store->shouldReceive('getPrefix')->andReturn('cache:'); + $store = Double::for(RedisStore::class); + $store->allows('getTagMode')->returns(TagMode::All); + $store->allows('getContext')->returns($context); + $store->allows('getPrefix')->returns('cache:'); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore')->andReturn($store); + $repository = Double::for(Repository::class); + $repository->allows('getStore')->returns($store); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->allows('store') ->with('redis') - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); @@ -675,16 +665,16 @@ protected function runCleanupVerification(DoctorContext $context): void public function testDoctorFailsWhenNoRedisStoreDetected(): void { // Set up config with NO redis stores - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('array') + $config = Double::for(ConfigRepository::class); + $config->allows('array') ->with('cache.stores') - ->andReturn([ + ->returns([ 'file' => ['driver' => 'file'], 'array' => ['driver' => 'array'], ]); - $config->shouldReceive('string') + $config->allows('string') ->with('cache.default') - ->andReturn('file'); + ->returns('file'); $this->app->instance('config', $config); @@ -700,41 +690,41 @@ public function testDoctorFailsWhenNoRedisStoreDetected(): void public function testDoctorDisplaysSystemInformation(): void { - $config = m::mock(ConfigRepository::class); - $config->shouldReceive('array') + $config = Double::for(ConfigRepository::class); + $config->allows('array') ->with('cache.stores') - ->andReturn([ + ->returns([ 'redis' => ['driver' => 'redis', 'connection' => 'default'], ]); - $config->shouldReceive('string') + $config->allows('string') ->with('cache.default') - ->andReturn('redis'); - $config->shouldReceive('get') + ->returns('redis'); + $config->allows('get') ->with('cache.stores.redis.connection', 'default') - ->andReturn('default'); + ->returns('default'); $this->app->instance('config', $config); - $context = m::mock(StoreContext::class); - $context->shouldReceive('withConnection') - ->andReturnUsing(function (callable $callback): mixed { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('info')->with('server')->andReturn(['redis_version' => '7.2.4']); + $context = Double::for(StoreContext::class); + $context->allows('withConnection') + ->resolves(function (callable $callback): mixed { + $connection = $this->mockConnection()->shouldTransform(false); + $connection->client()->allows('info')->with('server')->returns(['redis_version' => '7.2.4']); return $callback($connection); }); - $store = m::mock(RedisStore::class); - $store->shouldReceive('getTagMode')->andReturn(TagMode::Any); - $store->shouldReceive('getContext')->andReturn($context); - $store->shouldReceive('getPrefix')->andReturn('cache:'); + $store = Double::for(RedisStore::class); + $store->allows('getTagMode')->returns(TagMode::Any); + $store->allows('getContext')->returns($context); + $store->allows('getPrefix')->returns('cache:'); - $repository = m::mock(Repository::class); - $repository->shouldReceive('getStore')->andReturn($store); + $repository = Double::for(Repository::class); + $repository->allows('getStore')->returns($store); - $cacheManager = m::mock(CacheManager::class); - $cacheManager->shouldReceive('store') + $cacheManager = Double::for(CacheManager::class); + $cacheManager->allows('store') ->with('redis') - ->andReturn($repository); + ->returns($repository); $this->app->instance(CacheContract::class, $cacheManager); @@ -763,11 +753,11 @@ private function createCleanupContext( ?Throwable $registryException = null, int $cleanupInvocations = 1, ): DoctorContext { - $taggedCache = m::mock(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class); $tagFlushCalls = 0; - $taggedCache->shouldReceive('flush') + $taggedCache->expects('flush') ->times(self::CLEANUP_TEST_TAG_COUNT * $cleanupInvocations) - ->andReturnUsing(function () use (&$tagFlushCalls, $failingTagFlush, $tagException): bool { + ->resolves(function () use (&$tagFlushCalls, $failingTagFlush, $tagException): bool { ++$tagFlushCalls; if ($tagException !== null && $tagFlushCalls === $failingTagFlush) { @@ -777,16 +767,16 @@ private function createCleanupContext( return true; }); - $repository = m::mock(Repository::class); - $repository->shouldReceive('tags') + $repository = Double::for(Repository::class); + $repository->expects('tags') ->times(self::CLEANUP_TEST_TAG_COUNT * $cleanupInvocations) - ->andReturn($taggedCache); + ->returns($taggedCache); - $connection = m::mock(RedisConnection::class); + $connection = $this->mockConnection()->shouldTransform(false); $patternCalls = 0; - $connection->shouldReceive('flushByPattern') + $connection->expects('flushByPattern') ->times(self::CLEANUP_PATTERN_COUNT * $cleanupInvocations) - ->andReturnUsing(function (string $pattern) use (&$patternCalls, $patternExceptions): int { + ->resolves(function (string $pattern) use (&$patternCalls, $patternExceptions): int { ++$patternCalls; if (isset($patternExceptions[$patternCalls])) { @@ -797,24 +787,24 @@ private function createCleanupContext( }); if ($registryException === null) { - $connection->shouldReceive('zRange')->times($cleanupInvocations)->andReturn([]); - $connection->shouldReceive('zCard')->times($cleanupInvocations)->andReturn(0); - $connection->shouldReceive('del')->times($cleanupInvocations)->andReturn(1); + $connection->client()->expects('zRange')->times($cleanupInvocations)->returns([]); + $connection->client()->expects('zCard')->times($cleanupInvocations)->returns(0); + $connection->client()->expects('del')->times($cleanupInvocations)->returns(1); } else { - $connection->shouldReceive('zRange')->once()->andThrow($registryException); - $connection->shouldNotReceive('zCard'); - $connection->shouldNotReceive('del'); + $connection->client()->expects('zRange')->throws($registryException); + $connection->client()->expects('zCard')->never(); + $connection->client()->expects('del')->never(); } - $storeContext = m::mock(StoreContext::class); - $storeContext->shouldReceive('registryKey')->andReturn('cache:_any:tag_registry'); - $storeContext->shouldReceive('withConnection') - ->andReturnUsing(fn (callable $callback): mixed => $callback($connection)); + $storeContext = Double::for(StoreContext::class); + $storeContext->allows('registryKey')->returns('cache:_any:tag_registry'); + $storeContext->allows('withConnection') + ->resolves(fn (callable $callback): mixed => $callback($connection)); - $store = m::mock(RedisStore::class); - $store->shouldReceive('getContext')->andReturn($storeContext); - $store->shouldReceive('getTagMode')->andReturn(TagMode::Any); - $store->shouldReceive('getPrefix')->andReturn('cache:'); + $store = Double::for(RedisStore::class); + $store->allows('getContext')->returns($storeContext); + $store->allows('getTagMode')->returns(TagMode::Any); + $store->allows('getPrefix')->returns('cache:'); return new DoctorContext( cache: $repository, @@ -830,10 +820,10 @@ private function createCleanupContext( */ private function bindDoctorContext(DoctorContext $context): void { - $context->cache->shouldReceive('getStore')->once()->andReturn($context->store); + $context->cache->expects('getStore')->returns($context->store); - $cacheManager = m::mock(CacheContract::class); - $cacheManager->shouldReceive('store')->once()->with('redis')->andReturn($context->cache); + $cacheManager = Double::for(CacheContract::class); + $cacheManager->expects('store')->with('redis')->returns($context->cache); $this->app->instance(CacheContract::class, $cacheManager); } } diff --git a/tests/Cache/Redis/ExceptionPropagationTest.php b/tests/Cache/Redis/ExceptionPropagationTest.php index d1d424ddfa..af468125d6 100644 --- a/tests/Cache/Redis/ExceptionPropagationTest.php +++ b/tests/Cache/Redis/ExceptionPropagationTest.php @@ -24,8 +24,9 @@ class ExceptionPropagationTest extends RedisCacheTestCase public function testPutThrowsOnRedisError(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('setex') - ->andThrow(new RedisException('Connection refused')); + $connection->client()->allows('getLastError')->returns(null); + $connection->client()->expects('setex') + ->throws(new RedisException('Connection refused')); $store = $this->createStore($connection); @@ -38,8 +39,9 @@ public function testPutThrowsOnRedisError(): void public function testGetThrowsOnRedisError(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get') - ->andThrow(new RedisException('Connection timed out')); + $connection->client()->allows('getLastError')->returns(null); + $connection->client()->expects('get') + ->throws(new RedisException('Connection timed out')); $store = $this->createStore($connection); @@ -52,8 +54,9 @@ public function testGetThrowsOnRedisError(): void public function testForgetThrowsOnRedisError(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('del') - ->andThrow(new RedisException('READONLY You can\'t write against a read only replica')); + $connection->client()->allows('getLastError')->returns('READONLY You can\'t write against a read only replica'); + $connection->client()->expects('del') + ->throws(new RedisException('READONLY You can\'t write against a read only replica')); $store = $this->createStore($connection); @@ -66,8 +69,9 @@ public function testForgetThrowsOnRedisError(): void public function testIncrementThrowsOnRedisError(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('incrby') - ->andThrow(new RedisException('OOM command not allowed when used memory > maxmemory')); + $connection->client()->allows('getLastError')->returns('OOM command not allowed when used memory > maxmemory'); + $connection->client()->expects('incrby') + ->throws(new RedisException('OOM command not allowed when used memory > maxmemory')); $store = $this->createStore($connection); @@ -80,8 +84,9 @@ public function testIncrementThrowsOnRedisError(): void public function testDecrementThrowsOnRedisError(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('decrby') - ->andThrow(new RedisException('NOAUTH Authentication required')); + $connection->client()->allows('getLastError')->returns('NOAUTH Authentication required'); + $connection->client()->expects('decrby') + ->throws(new RedisException('NOAUTH Authentication required')); $store = $this->createStore($connection); @@ -94,8 +99,9 @@ public function testDecrementThrowsOnRedisError(): void public function testForeverThrowsOnRedisError(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('set') - ->andThrow(new RedisException('ERR invalid DB index')); + $connection->client()->allows('getLastError')->returns('ERR invalid DB index'); + $connection->client()->expects('set') + ->throws(new RedisException('ERR invalid DB index')); $store = $this->createStore($connection); @@ -114,8 +120,8 @@ public function testTaggedPutThrowsOnRedisError(): void $connection = $this->mockConnection(); // Tagged put uses evalWithShaCache for Lua script - $connection->shouldReceive('evalWithShaCache') - ->andThrow(new RedisException('Connection lost')); + $connection->expects('evalWithShaCache') + ->throws(new RedisException('Connection lost')); $store = $this->createStore($connection, tagMode: 'any'); $taggedCache = new AnyTaggedCache($store, new AnyTagSet($store, ['test-tag'])); @@ -131,8 +137,8 @@ public function testTaggedIncrementThrowsOnRedisError(): void $connection = $this->mockConnection(); // Tagged increment uses evalWithShaCache for Lua script - $connection->shouldReceive('evalWithShaCache') - ->andThrow(new RedisException('Connection reset by peer')); + $connection->expects('evalWithShaCache') + ->throws(new RedisException('Connection reset by peer')); $store = $this->createStore($connection, tagMode: 'any'); $taggedCache = new AnyTaggedCache($store, new AnyTagSet($store, ['test-tag'])); @@ -148,8 +154,9 @@ public function testTaggedFlushThrowsOnRedisError(): void $connection = $this->mockConnection(); // Flush calls hlen to check hash size - $connection->shouldReceive('hlen') - ->andThrow(new RedisException('ERR unknown command')); + $connection->client()->allows('getLastError')->returns('ERR unknown command'); + $connection->client()->expects('hlen') + ->throws(new RedisException('ERR unknown command')); $store = $this->createStore($connection, tagMode: 'any'); $taggedCache = new AnyTaggedCache($store, new AnyTagSet($store, ['test-tag'])); @@ -169,8 +176,8 @@ public function testPutManyThrowsOnRedisError(): void $connection = $this->mockConnection(); // PutMany uses evalWithShaCache for Lua script - $connection->shouldReceive('evalWithShaCache') - ->andThrow(new RedisException('CLUSTERDOWN The cluster is down')); + $connection->expects('evalWithShaCache') + ->throws(new RedisException('CLUSTERDOWN The cluster is down')); $store = $this->createStore($connection); @@ -183,8 +190,9 @@ public function testPutManyThrowsOnRedisError(): void public function testManyThrowsOnRedisError(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('mget') - ->andThrow(new RedisException('LOADING Redis is loading the dataset in memory')); + $connection->client()->allows('getLastError')->returns('LOADING Redis is loading the dataset in memory'); + $connection->client()->expects('mget') + ->throws(new RedisException('LOADING Redis is loading the dataset in memory')); $store = $this->createStore($connection); @@ -201,8 +209,9 @@ public function testManyThrowsOnRedisError(): void public function testFlushThrowsOnRedisError(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('flushdb') - ->andThrow(new RedisException('MISCONF Redis is configured to save RDB snapshots')); + $connection->client()->allows('getLastError')->returns('MISCONF Redis is configured to save RDB snapshots'); + $connection->client()->expects('flushdb') + ->throws(new RedisException('MISCONF Redis is configured to save RDB snapshots')); $store = $this->createStore($connection); diff --git a/tests/Cache/Redis/Operations/AddTest.php b/tests/Cache/Redis/Operations/AddTest.php index ca4faf9ad0..b6ee4e77a1 100644 --- a/tests/Cache/Redis/Operations/AddTest.php +++ b/tests/Cache/Redis/Operations/AddTest.php @@ -19,10 +19,9 @@ public function testAddReturnsTrueWhenKeyDoesNotExist(): void $connection = $this->mockConnection(); // SET returns true/OK when key was set - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:foo', serialize('bar'), ['EX' => 60, 'NX']) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $result = $redis->add('foo', 'bar', 60); @@ -33,11 +32,10 @@ public function testAddReturnsFalseWhenKeyExists(): void { $connection = $this->mockConnection(); - // SET with NX returns null/false when key already exists - $connection->shouldReceive('set') - ->once() + // Native phpredis returns false when NX finds an existing key. + $connection->client()->expects('set') ->with('prefix:foo', serialize('bar'), ['EX' => 60, 'NX']) - ->andReturn(null); + ->returns(false); $redis = $this->createStore($connection); $result = $redis->add('foo', 'bar', 60); @@ -49,10 +47,9 @@ public function testAddWithNumericValue(): void $connection = $this->mockConnection(); // Numeric values are NOT serialized (optimization) - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:foo', 42, ['EX' => 60, 'NX']) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $result = $redis->add('foo', 42, 60); @@ -64,10 +61,9 @@ public function testAddEnforcesMinimumTtlOfOne(): void $connection = $this->mockConnection(); // TTL should be at least 1 - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:foo', serialize('bar'), ['EX' => 1, 'NX']) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $result = $redis->add('foo', 'bar', 0); @@ -80,10 +76,9 @@ public function testAddWithArrayValue(): void $value = ['key' => 'value', 'nested' => ['a', 'b']]; - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:foo', serialize($value), ['EX' => 120, 'NX']) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $result = $redis->add('foo', $value, 120); diff --git a/tests/Cache/Redis/Operations/AllTag/AddEntryTest.php b/tests/Cache/Redis/Operations/AllTag/AddEntryTest.php index 72d47b4c3c..78a1b6e7b8 100644 --- a/tests/Cache/Redis/Operations/AllTag/AddEntryTest.php +++ b/tests/Cache/Redis/Operations/AllTag/AddEntryTest.php @@ -24,16 +24,14 @@ public function testAddEntryWithTtl(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1301, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1301.0, 'mykey') + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1]); + $connection->client()->expects('exec') + ->returns([1]); $store = $this->createStore($connection); $operation = new AddEntry($store->getContext()); @@ -45,16 +43,14 @@ public function testAddEntryWithZeroTtlStoresNegativeOne(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', -1, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', -1.0, 'mykey') + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1]); + $connection->client()->expects('exec') + ->returns([1]); $store = $this->createStore($connection); $operation = new AddEntry($store->getContext()); @@ -66,16 +62,14 @@ public function testAddEntryWithNegativeTtlStoresNegativeOne(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', -1, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', -1.0, 'mykey') + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1]); + $connection->client()->expects('exec') + ->returns([1]); $store = $this->createStore($connection); $operation = new AddEntry($store->getContext()); @@ -87,16 +81,14 @@ public function testAddEntryWithUpdateWhenNxCondition(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'mykey') - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1]); + $connection->client()->expects('exec') + ->returns([1]); $store = $this->createStore($connection); $operation = new AddEntry($store->getContext()); @@ -108,16 +100,14 @@ public function testAddEntryWithUpdateWhenXxCondition(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['XX'], -1, 'mykey') - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1]); + $connection->client()->expects('exec') + ->returns([1]); $store = $this->createStore($connection); $operation = new AddEntry($store->getContext()); @@ -129,16 +119,14 @@ public function testAddEntryWithUpdateWhenGtCondition(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['GT'], 1061, 'mykey') - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1]); + $connection->client()->expects('exec') + ->returns([1]); $store = $this->createStore($connection); $operation = new AddEntry($store->getContext()); @@ -150,20 +138,17 @@ public function testAddEntryWithMultipleTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1061, 'mykey') - ->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:posts:entries', 1061, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1061.0, 'mykey') + ->returns($connection->client()); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:posts:entries', 1061.0, 'mykey') + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1, 1]); + $connection->client()->expects('exec') + ->returns([1, 1]); $store = $this->createStore($connection); $operation = new AddEntry($store->getContext()); @@ -176,8 +161,8 @@ public function testAddEntryWithEmptyTagsArrayDoesNothing(): void $connection = $this->mockConnection(); // No pipeline or zadd calls should be made - $connection->shouldNotReceive('pipeline'); - $connection->shouldNotReceive('zadd'); + $connection->client()->expects('pipeline')->never(); + $connection->client()->expects('zadd')->never(); $store = $this->createStore($connection); $operation = new AddEntry($store->getContext()); @@ -189,16 +174,14 @@ public function testAddEntryUsesCorrectPrefix(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('custom_prefix:_all:tag:users:entries', -1, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('custom_prefix:_all:tag:users:entries', -1.0, 'mykey') + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1]); + $connection->client()->expects('exec') + ->returns([1]); $store = $this->createStore($connection, 'custom_prefix:'); $operation = new AddEntry($store->getContext()); @@ -208,16 +191,12 @@ public function testAddEntryUsesCorrectPrefix(): void public function testAddEntryClusterModeUsesSequentialCommands(): void { - [$store, , $connection] = $this->createClusterStore(); - - // Should NOT use pipeline in cluster mode - $connection->shouldNotReceive('pipeline'); + [$store, $client] = $this->createClusterStore(); // Should use sequential zadd calls directly on connection - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1301, 'mykey') - ->andReturn(1); + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1301.0, 'mykey') + ->returns(1); $operation = new AddEntry($store->getContext()); $operation->execute('mykey', 300, ['_all:tag:users:entries']); @@ -225,25 +204,19 @@ public function testAddEntryClusterModeUsesSequentialCommands(): void public function testAddEntryClusterModeWithMultipleTags(): void { - [$store, , $connection] = $this->createClusterStore(); - - // Should NOT use pipeline in cluster mode - $connection->shouldNotReceive('pipeline'); + [$store, $client] = $this->createClusterStore(); // Should use sequential zadd calls for each tag - $expectedScore = 1061; - $connection->shouldReceive('zadd') - ->once() + $expectedScore = 1061.0; + $client->expects('zadd') ->with('prefix:_all:tag:users:entries', $expectedScore, 'mykey') - ->andReturn(1); - $connection->shouldReceive('zadd') - ->once() + ->returns(1); + $client->expects('zadd') ->with('prefix:_all:tag:posts:entries', $expectedScore, 'mykey') - ->andReturn(1); - $connection->shouldReceive('zadd') - ->once() + ->returns(1); + $client->expects('zadd') ->with('prefix:_all:tag:comments:entries', $expectedScore, 'mykey') - ->andReturn(1); + ->returns(1); $operation = new AddEntry($store->getContext()); $operation->execute('mykey', 60, ['_all:tag:users:entries', '_all:tag:posts:entries', '_all:tag:comments:entries']); @@ -251,13 +224,12 @@ public function testAddEntryClusterModeWithMultipleTags(): void public function testAddEntryClusterModeWithUpdateWhenFlag(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); // Should use zadd with NX flag as array (phpredis requires array for options) - $connection->shouldReceive('zadd') - ->once() + $client->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'mykey') - ->andReturn(1); + ->returns(1); $operation = new AddEntry($store->getContext()); $operation->execute('mykey', 0, ['_all:tag:users:entries'], 'NX'); @@ -265,13 +237,12 @@ public function testAddEntryClusterModeWithUpdateWhenFlag(): void public function testAddEntryClusterModeWithZeroTtlStoresNegativeOne(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); // Score should be -1 for forever items (TTL = 0) - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', -1, 'mykey') - ->andReturn(1); + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', -1.0, 'mykey') + ->returns(1); $operation = new AddEntry($store->getContext()); $operation->execute('mykey', 0, ['_all:tag:users:entries']); diff --git a/tests/Cache/Redis/Operations/AllTag/AddTest.php b/tests/Cache/Redis/Operations/AllTag/AddTest.php index cdacb7df35..941cbbd224 100644 --- a/tests/Cache/Redis/Operations/AllTag/AddTest.php +++ b/tests/Cache/Redis/Operations/AllTag/AddTest.php @@ -6,7 +6,7 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; -use Mockery as m; +use JMac\Testing\Matching\Argument; /** * Tests for the Add operation (intersection tags). @@ -23,8 +23,8 @@ public function testAddWithTagsReturnsTrueWhenKeyAdded(): void $connection = $this->mockConnection(); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:mykey', 'prefix:_all:tag:users:entries'], [serialize('myvalue'), 60, 1061, 'mykey']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:mykey', 'prefix:_all:tag:users:entries'], [serialize('myvalue'), 60, 1061, 'mykey']) + ->returns(1); $store = $this->createStore($connection); $result = $store->allTagOps()->add()->execute( @@ -41,8 +41,8 @@ public function testAddWithTagsReturnsFalseWhenKeyExists(): void { $connection = $this->mockConnection(); - $connection->expects('evalWithShaCache')->andReturn(0); - $connection->shouldNotReceive('zadd'); + $connection->expects('evalWithShaCache')->returns(0); + $connection->client()->expects('zadd')->never(); $store = $this->createStore($connection); $result = $store->allTagOps()->add()->execute( @@ -63,11 +63,11 @@ public function testAddWithMultipleTags(): void $connection->expects('evalWithShaCache') ->with( - m::type('string'), + Argument::type('string'), ['prefix:mykey', 'prefix:_all:tag:users:entries', 'prefix:_all:tag:posts:entries'], [serialize('myvalue'), 120, 1121, 'mykey'], ) - ->andReturn(1); + ->returns(1); $store = $this->createStore($connection); $result = $store->allTagOps()->add()->execute( @@ -84,13 +84,12 @@ public function testAddWithEmptyTagsSkipsLua(): void { $connection = $this->mockConnection(); - $connection->shouldNotReceive('evalWithShaCache'); + $connection->expects('evalWithShaCache')->never(); // Only SET NX EX for add - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:mykey', serialize('myvalue'), ['EX' => 60, 'NX']) - ->andReturn(true); + ->returns(true); $store = $this->createStore($connection); $result = $store->allTagOps()->add()->execute( @@ -107,21 +106,16 @@ public function testAddInClusterModeUsesSequentialCommands(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - // Should NOT use pipeline in cluster mode - $connection->shouldNotReceive('pipeline'); - - $connection->shouldReceive('set') - ->once() + $client->expects('set') ->with('prefix:mykey', serialize('myvalue'), ['EX' => 60, 'NX']) - ->andReturn(true) + ->returns(true) ->ordered(); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1061, 'mykey') - ->andReturn(0) + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1061.0, 'mykey') + ->returns(0) ->ordered(); $result = $store->allTagOps()->add()->execute( @@ -138,15 +132,14 @@ public function testAddInClusterModeReturnsFalseWhenKeyExists(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->shouldReceive('set') - ->once() + $client->expects('set') ->with('prefix:mykey', serialize('myvalue'), ['EX' => 60, 'NX']) - ->andReturn(false) + ->returns(false) ->ordered(); - $connection->shouldNotReceive('zadd'); + $client->expects('zadd')->never(); $result = $store->allTagOps()->add()->execute( 'mykey', @@ -161,7 +154,7 @@ public function testAddInClusterModeReturnsFalseWhenKeyExists(): void public function testAddReturnsFalseWhenScriptExecutionFails(): void { $connection = $this->mockConnection(); - $connection->expects('evalWithShaCache')->andReturn(false); + $connection->expects('evalWithShaCache')->returns(false); $store = $this->createStore($connection); @@ -175,9 +168,9 @@ public function testAddReturnsFalseWhenScriptExecutionFails(): void public function testAddReturnsFalseWhenClusterMembershipWriteFails(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldReceive('set')->once()->andReturn(true); - $connection->shouldReceive('zadd')->once()->andReturn(false); + [$store, $client] = $this->createClusterStore(); + $client->expects('set')->returns(true); + $client->expects('zadd')->returns(false); $this->assertFalse($store->allTagOps()->add()->execute( 'mykey', @@ -193,8 +186,8 @@ public function testAddEnforcesMinimumTtlOfOne(): void $connection = $this->mockConnection(); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:mykey', 'prefix:_all:tag:users:entries'], [serialize('myvalue'), 1, 1002, 'mykey']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:mykey', 'prefix:_all:tag:users:entries'], [serialize('myvalue'), 1, 1002, 'mykey']) + ->returns(1); $store = $this->createStore($connection); $result = $store->allTagOps()->add()->execute( @@ -212,8 +205,8 @@ public function testAddWithNumericValue(): void $connection = $this->mockConnection(); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:mykey', 'prefix:_all:tag:users:entries'], ['42', 60, 946684860, 'mykey']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:mykey', 'prefix:_all:tag:users:entries'], ['42', 60, 946684860, 'mykey']) + ->returns(1); $store = $this->createStore($connection); $result = $store->allTagOps()->add()->execute( diff --git a/tests/Cache/Redis/Operations/AllTag/DecrementTest.php b/tests/Cache/Redis/Operations/AllTag/DecrementTest.php index 3a50861574..a88dc30e20 100644 --- a/tests/Cache/Redis/Operations/AllTag/DecrementTest.php +++ b/tests/Cache/Redis/Operations/AllTag/DecrementTest.php @@ -15,23 +15,20 @@ public function testDecrementWithTagsInPipelineMode(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('decrby') - ->once() + $connection->client()->expects('decrby') ->with('prefix:counter', 1) - ->andReturn($connection) + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'counter') - ->andReturn($connection) + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('exec') - ->once() - ->andReturn([5, 1]); + $connection->client()->expects('exec') + ->returns([5, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->decrement()->execute( @@ -47,21 +44,18 @@ public function testDecrementWithCustomValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'counter') - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('decrby') - ->once() + $connection->client()->expects('decrby') ->with('prefix:counter', 10) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([-5, 0]); // 0 means tag membership already existed + $connection->client()->expects('exec') + ->returns([-5, 0]); // 0 means tag membership already existed $store = $this->createStore($connection); $result = $store->allTagOps()->decrement()->execute( @@ -77,26 +71,22 @@ public function testDecrementWithMultipleTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // ZADD NX for each tag - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'counter') - ->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() + ->returns($connection->client()); + $connection->client()->expects('zadd') ->with('prefix:_all:tag:posts:entries', ['NX'], -1, 'counter') - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('decrby') - ->once() + $connection->client()->expects('decrby') ->with('prefix:counter', 1) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([9, 1, 1]); + $connection->client()->expects('exec') + ->returns([9, 1, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->decrement()->execute( @@ -112,17 +102,15 @@ public function testDecrementWithEmptyTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // No ZADD calls expected - $connection->shouldReceive('decrby') - ->once() + $connection->client()->expects('decrby') ->with('prefix:counter', 1) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([-1]); + $connection->client()->expects('exec') + ->returns([-1]); $store = $this->createStore($connection); $result = $store->allTagOps()->decrement()->execute( @@ -136,18 +124,15 @@ public function testDecrementWithEmptyTags(): void public function testDecrementInClusterModeUsesSequentialCommands(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->shouldNotReceive('pipeline'); - - $connection->expects('decrby') + $client->expects('decrby') ->with('prefix:counter', 1) - ->andReturn(0) + ->returns(0) ->ordered(); - $connection->expects('zadd') - ->once() + $client->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'counter') - ->andReturn(1) + ->returns(1) ->ordered(); $result = $store->allTagOps()->decrement()->execute( @@ -161,10 +146,10 @@ public function testDecrementInClusterModeUsesSequentialCommands(): void public function testDecrementInClusterModeDoesNotPublishTagsWhenTheCounterFails(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->expects('decrby')->with('prefix:counter', 1)->andReturnFalse(); - $connection->shouldNotReceive('zadd'); + $client->expects('decrby')->with('prefix:counter', 1)->returns(false); + $client->expects('zadd')->never(); $this->assertFalse($store->allTagOps()->decrement()->execute( 'counter', @@ -177,14 +162,13 @@ public function testDecrementReturnsFalseOnPipelineFailure(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); - $connection->shouldReceive('decrby')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); + $connection->client()->allows('decrby')->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn(false); + $connection->client()->expects('exec') + ->returns(false); $store = $this->createStore($connection); $result = $store->allTagOps()->decrement()->execute( diff --git a/tests/Cache/Redis/Operations/AllTag/FlushStaleTest.php b/tests/Cache/Redis/Operations/AllTag/FlushStaleTest.php index ad938d5bbb..d9d2dea33d 100644 --- a/tests/Cache/Redis/Operations/AllTag/FlushStaleTest.php +++ b/tests/Cache/Redis/Operations/AllTag/FlushStaleTest.php @@ -7,7 +7,7 @@ use Hypervel\Cache\Redis\Operations\AllTag\FlushStale; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; -use Mockery as m; +use JMac\Testing\Matching\Argument; /** * Tests for the FlushStale operation. @@ -18,14 +18,13 @@ public function testFlushStaleEntriesRemovesExpiredEntries(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zRemRangeByScore') - ->once() + $connection->client()->expects('zRemRangeByScore') ->with('prefix:_all:tag:users:entries', '0', (string) now()->getTimestamp()) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec')->once(); + $connection->client()->expects('exec'); $store = $this->createStore($connection); $operation = new FlushStale($store->getContext()); @@ -37,23 +36,20 @@ public function testFlushStaleEntriesWithMultipleTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // All tags should be processed in a single pipeline - $connection->shouldReceive('zRemRangeByScore') - ->once() + $connection->client()->expects('zRemRangeByScore') ->with('prefix:_all:tag:users:entries', '0', (string) now()->getTimestamp()) - ->andReturn($connection); - $connection->shouldReceive('zRemRangeByScore') - ->once() + ->returns($connection->client()); + $connection->client()->expects('zRemRangeByScore') ->with('prefix:_all:tag:posts:entries', '0', (string) now()->getTimestamp()) - ->andReturn($connection); - $connection->shouldReceive('zRemRangeByScore') - ->once() + ->returns($connection->client()); + $connection->client()->expects('zRemRangeByScore') ->with('prefix:_all:tag:comments:entries', '0', (string) now()->getTimestamp()) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec')->once(); + $connection->client()->expects('exec'); $store = $this->createStore($connection); $operation = new FlushStale($store->getContext()); @@ -66,7 +62,7 @@ public function testFlushStaleEntriesWithEmptyTagIdsReturnsEarly(): void $connection = $this->mockConnection(); // Should NOT create pipeline or execute any commands for empty array - $connection->shouldNotReceive('pipeline'); + $connection->client()->expects('pipeline')->never(); $store = $this->createStore($connection); $operation = new FlushStale($store->getContext()); @@ -78,14 +74,13 @@ public function testFlushStaleEntriesUsesCorrectPrefix(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zRemRangeByScore') - ->once() + $connection->client()->expects('zRemRangeByScore') ->with('custom_prefix:_all:tag:users:entries', '0', (string) now()->getTimestamp()) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec')->once(); + $connection->client()->expects('exec'); $store = $this->createStore($connection, 'custom_prefix:'); $operation = new FlushStale($store->getContext()); @@ -101,16 +96,15 @@ public function testFlushStaleEntriesUsesCurrentTimestampAsUpperBound(): void $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // Lower bound is '0' (to exclude -1 forever items) // Upper bound is current timestamp - $connection->shouldReceive('zRemRangeByScore') - ->once() + $connection->client()->expects('zRemRangeByScore') ->with('prefix:_all:tag:users:entries', '0', $expectedTimestamp) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec')->once(); + $connection->client()->expects('exec'); $store = $this->createStore($connection); $operation = new FlushStale($store->getContext()); @@ -129,12 +123,11 @@ public function testFlushStaleDoesNotReachCeiledScoreBeforeRequestedLifetime(): CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1001.900000')); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('zRemRangeByScore') - ->once() + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('zRemRangeByScore') ->with('prefix:_all:tag:users:entries', '0', '1001') - ->andReturn($connection); - $connection->shouldReceive('exec')->once(); + ->returns($connection->client()); + $connection->client()->expects('exec'); (new FlushStale($store->getContext()))->execute(['_all:tag:users:entries']); } @@ -145,22 +138,21 @@ public function testFlushStaleEntriesDoesNotRemoveForeverItems(): void // intentionally excludes items with score -1 (forever items) $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // The lower bound is '0', not '-inf', so -1 scores are excluded - $connection->shouldReceive('zRemRangeByScore') - ->once() - ->with('prefix:_all:tag:users:entries', '0', m::type('string')) - ->andReturnUsing(function ($key, $min, $max) use ($connection) { + $connection->client()->expects('zRemRangeByScore') + ->with('prefix:_all:tag:users:entries', '0', Argument::type('string')) + ->resolves(function ($key, $min, $max) use ($connection) { // Verify lower bound excludes -1 forever items $this->assertSame('0', $min); // Verify upper bound is a valid timestamp $this->assertIsNumeric($max); - return $connection; + return $connection->client(); }); - $connection->shouldReceive('exec')->once(); + $connection->client()->expects('exec'); $store = $this->createStore($connection); $operation = new FlushStale($store->getContext()); @@ -170,15 +162,13 @@ public function testFlushStaleEntriesDoesNotRemoveForeverItems(): void public function testFlushStaleEntriesClusterModeUsesSequentialCommands(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->shouldNotReceive('pipeline'); - $connection->shouldNotReceive('multi'); + $client->expects('multi')->never(); - $connection->shouldReceive('zRemRangeByScore') - ->once() + $client->expects('zRemRangeByScore') ->with('prefix:_all:tag:users:entries', '0', (string) now()->getTimestamp()) - ->andReturn(5); + ->returns(5); $operation = new FlushStale($store->getContext()); $operation->execute(['_all:tag:users:entries']); @@ -186,24 +176,20 @@ public function testFlushStaleEntriesClusterModeUsesSequentialCommands(): void public function testFlushStaleEntriesClusterModeWithMultipleTags(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->shouldNotReceive('pipeline'); - $connection->shouldNotReceive('multi'); + $client->expects('multi')->never(); $timestamp = (string) now()->getTimestamp(); - $connection->shouldReceive('zRemRangeByScore') - ->once() + $client->expects('zRemRangeByScore') ->with('prefix:_all:tag:users:entries', '0', $timestamp) - ->andReturn(3); - $connection->shouldReceive('zRemRangeByScore') - ->once() + ->returns(3); + $client->expects('zRemRangeByScore') ->with('prefix:_all:tag:posts:entries', '0', $timestamp) - ->andReturn(2); - $connection->shouldReceive('zRemRangeByScore') - ->once() + ->returns(2); + $client->expects('zRemRangeByScore') ->with('prefix:_all:tag:comments:entries', '0', $timestamp) - ->andReturn(0); + ->returns(0); $operation = new FlushStale($store->getContext()); $operation->execute(['_all:tag:users:entries', '_all:tag:posts:entries', '_all:tag:comments:entries']); @@ -211,14 +197,13 @@ public function testFlushStaleEntriesClusterModeWithMultipleTags(): void public function testFlushStaleEntriesClusterModeUsesCorrectPrefix(): void { - [$store, , $connection] = $this->createClusterStore(prefix: 'custom_prefix:'); + [$store, $client] = $this->createClusterStore(prefix: 'custom_prefix:'); - $connection->shouldNotReceive('multi'); + $client->expects('multi')->never(); - $connection->shouldReceive('zRemRangeByScore') - ->once() + $client->expects('zRemRangeByScore') ->with('custom_prefix:_all:tag:users:entries', '0', (string) now()->getTimestamp()) - ->andReturn(1); + ->returns(1); $operation = new FlushStale($store->getContext()); $operation->execute(['_all:tag:users:entries']); diff --git a/tests/Cache/Redis/Operations/AllTag/FlushTest.php b/tests/Cache/Redis/Operations/AllTag/FlushTest.php index c4bfa812d6..9b661e88a1 100644 --- a/tests/Cache/Redis/Operations/AllTag/FlushTest.php +++ b/tests/Cache/Redis/Operations/AllTag/FlushTest.php @@ -11,7 +11,10 @@ use Hypervel\Redis\RedisProxy; use Hypervel\Support\LazyCollection; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; -use Mockery as m; +use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; /** * Tests for the Flush operation. @@ -23,15 +26,14 @@ public function testFlushDeletesCacheEntriesAndScannedMemberships(): void $connection = $this->mockConnection(); // Mock GetEntries to return cache keys - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:users:entries']) - ->andReturn(new LazyCollection(['key1', 'key2'])); + ->returns(new LazyCollection(['key1', 'key2'])); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:users:entries', 'prefix:key1', 'prefix:key2'], ['key1', 'key2']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_all:tag:users:entries', 'prefix:key1', 'prefix:key2'], ['key1', 'key2']) + ->returns(1); $store = $this->createStore($connection); $operation = new Flush($store->getContext(), $getEntries); @@ -43,27 +45,24 @@ public function testFlushWithMultipleTagsOnlyRemovesEntriesFromTheirOwnTag(): vo { $connection = $this->mockConnection(); - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:people:entries']) - ->andReturn(new LazyCollection(['person-1', 'person-2'])); - $getEntries->shouldReceive('execute') - ->once() + ->returns(new LazyCollection(['person-1', 'person-2'])); + $getEntries->expects('execute') ->with(['_all:tag:artist:entries']) - ->andReturn(new LazyCollection(['person-2', 'person-3'])); - $getEntries->shouldReceive('execute') - ->once() + ->returns(new LazyCollection(['person-2', 'person-3'])); + $getEntries->expects('execute') ->with(['_all:tag:empty:entries']) - ->andReturn(new LazyCollection([])); + ->returns(new LazyCollection([])); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:people:entries', 'prefix:person-1', 'prefix:person-2'], ['person-1', 'person-2']) - ->andReturn(1) + ->with(Argument::type('string'), ['prefix:_all:tag:people:entries', 'prefix:person-1', 'prefix:person-2'], ['person-1', 'person-2']) + ->returns(1) ->ordered(); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:artist:entries', 'prefix:person-2', 'prefix:person-3'], ['person-2', 'person-3']) - ->andReturn(1) + ->with(Argument::type('string'), ['prefix:_all:tag:artist:entries', 'prefix:person-2', 'prefix:person-3'], ['person-2', 'person-3']) + ->returns(1) ->ordered(); $store = $this->createStore($connection); @@ -77,14 +76,13 @@ public function testFlushWithNoEntriesDoesNotDeleteTagSets(): void $connection = $this->mockConnection(); // Mock GetEntries to return empty collection - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:users:entries']) - ->andReturn(new LazyCollection([])); + ->returns(new LazyCollection([])); - $connection->shouldNotReceive('del'); - $connection->shouldNotReceive('evalWithShaCache'); + $connection->client()->expects('del')->never(); + $connection->expects('evalWithShaCache')->never(); $store = $this->createStore($connection); $operation = new Flush($store->getContext(), $getEntries); @@ -103,11 +101,10 @@ public function testFlushChunksLargeEntrySets(): void } // Mock GetEntries to return many cache keys - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:users:entries']) - ->andReturn(new LazyCollection($entries)); + ->returns(new LazyCollection($entries)); // First chunk: 1000 entries. $firstChunkArgs = []; @@ -115,8 +112,8 @@ public function testFlushChunksLargeEntrySets(): void $firstChunkArgs[] = "prefix:key{$i}"; } $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:users:entries', ...$firstChunkArgs], array_slice($entries, 0, 1000)) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_all:tag:users:entries', ...$firstChunkArgs], array_slice($entries, 0, 1000)) + ->returns(1); // Second chunk: 500 entries. $secondChunkArgs = []; @@ -124,8 +121,8 @@ public function testFlushChunksLargeEntrySets(): void $secondChunkArgs[] = "prefix:key{$i}"; } $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:users:entries', ...$secondChunkArgs], array_slice($entries, 1000)) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_all:tag:users:entries', ...$secondChunkArgs], array_slice($entries, 1000)) + ->returns(1); $store = $this->createStore($connection); $operation = new Flush($store->getContext(), $getEntries); @@ -135,41 +132,32 @@ public function testFlushChunksLargeEntrySets(): void public function testFlushReleasesScanConnectionsBeforeCheckingOutEachDeletionChunk(): void { - $connection = $this->mockConnection(); $entries = []; for ($i = 1; $i <= 1001; ++$i) { $entries["key{$i}"] = 1; } - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) use ($entries) { - $cursor = 0; - - return $entries; - }); + $client = new FakeRedisClient( + zScanResults: [ + 'prefix:_all:tag:users:entries' => [['members' => $entries, 'iterator' => 0]], + ], + evalShaResults: [1, 1], + ); + $connection = (new PhpRedisConnectionStub)->setActiveConnection($client)->shouldTransform(false); $firstChunk = []; for ($i = 1; $i <= 1000; ++$i) { $firstChunk[] = "prefix:key{$i}"; } - $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:users:entries', ...$firstChunk], array_slice(array_keys($entries), 0, 1000)) - ->andReturn(1); - $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:users:entries', 'prefix:key1001'], ['key1001']) - ->andReturn(1); - $active = false; - $proxy = m::mock(RedisProxy::class); - $proxy->shouldReceive('isCluster')->once()->andReturnFalse(); - $proxy->shouldReceive('withConnection') + $proxy = Double::for(RedisProxy::class); + $proxy->expects('isCluster')->returns(false); + $proxy->expects('withConnection') ->times(3) - ->with(m::type('callable'), false) - ->andReturnUsing(function (callable $callback) use ($connection, &$active) { + ->with(Argument::type('callable'), false) + ->resolves(function (callable $callback) use ($connection, &$active) { $this->assertFalse($active); $active = true; @@ -180,17 +168,30 @@ public function testFlushReleasesScanConnectionsBeforeCheckingOutEachDeletionChu } }); - $redis = m::mock(RedisFactory::class); - $redis->shouldReceive('connection') + $redis = Double::for(RedisFactory::class); + $redis->expects('connection') ->times(4) ->with('default') - ->andReturn($proxy); + ->returns($proxy); $store = new RedisStore($redis, 'prefix:', 'default'); $context = $store->getContext(); $operation = new Flush($context, new GetEntries($context)); $operation->execute(['_all:tag:users:entries']); + + $this->assertSame([ + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); + $calls = $client->getEvalShaCalls(); + $this->assertCount(2, $calls); + $this->assertSame( + ['prefix:_all:tag:users:entries', ...$firstChunk, ...array_slice(array_keys($entries), 0, 1000)], + $calls[0]['args'], + ); + $this->assertSame(1001, $calls[0]['num_keys']); + $this->assertSame(['prefix:_all:tag:users:entries', 'prefix:key1001', 'key1001'], $calls[1]['args']); + $this->assertSame(2, $calls[1]['num_keys']); } public function testFlushUsesCorrectPrefix(): void @@ -198,15 +199,14 @@ public function testFlushUsesCorrectPrefix(): void $connection = $this->mockConnection(); // Mock GetEntries to return cache keys - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:users:entries']) - ->andReturn(new LazyCollection(['mykey'])); + ->returns(new LazyCollection(['mykey'])); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['custom_prefix:_all:tag:users:entries', 'custom_prefix:mykey'], ['mykey']) - ->andReturn(1); + ->with(Argument::type('string'), ['custom_prefix:_all:tag:users:entries', 'custom_prefix:mykey'], ['mykey']) + ->returns(1); $store = $this->createStore($connection, 'custom_prefix:'); $operation = new Flush($store->getContext(), $getEntries); @@ -218,11 +218,11 @@ public function testFlushWithEmptyTagIds(): void { $connection = $this->mockConnection(); - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldNotReceive('execute'); + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute')->never(); - $connection->shouldNotReceive('del'); - $connection->shouldNotReceive('evalWithShaCache'); + $connection->client()->expects('del')->never(); + $connection->expects('evalWithShaCache')->never(); $store = $this->createStore($connection); $operation = new Flush($store->getContext(), $getEntries); @@ -235,14 +235,13 @@ public function testFlushTagKeyFormat(): void $connection = $this->mockConnection(); // Mock GetEntries - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() - ->andReturn(new LazyCollection(['key'])); + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') + ->returns(new LazyCollection(['key'])); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_all:tag:my-special-tag:entries', 'prefix:key'], ['key']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_all:tag:my-special-tag:entries', 'prefix:key'], ['key']) + ->returns(1); $store = $this->createStore($connection); $operation = new Flush($store->getContext(), $getEntries); @@ -252,26 +251,21 @@ public function testFlushTagKeyFormat(): void public function testFlushInClusterModeUsesSequentialDel(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); // Mock GetEntries to return cache keys - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:users:entries']) - ->andReturn(new LazyCollection(['key1', 'key2'])); - - // Cluster mode should NOT use pipeline - $connection->shouldNotReceive('pipeline'); + ->returns(new LazyCollection(['key1', 'key2'])); - $connection->expects('zrem') + $client->expects('zrem') ->with('prefix:_all:tag:users:entries', 'key1', 'key2') - ->andReturn(2)->ordered(); + ->returns(2)->ordered(); - $connection->shouldReceive('del') - ->once() + $client->expects('del') ->with('prefix:key1', 'prefix:key2') - ->andReturn(2)->ordered(); + ->returns(2)->ordered(); $operation = new Flush($store->getContext(), $getEntries); $operation->execute(['_all:tag:users:entries']); @@ -279,7 +273,7 @@ public function testFlushInClusterModeUsesSequentialDel(): void public function testFlushInClusterModeChunksLargeSets(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); // Create more than CHUNK_SIZE (1000) entries $entries = []; @@ -288,40 +282,34 @@ public function testFlushInClusterModeChunksLargeSets(): void } // Mock GetEntries to return many cache keys - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:users:entries']) - ->andReturn(new LazyCollection($entries)); - - // Cluster mode should NOT use pipeline - $connection->shouldNotReceive('pipeline'); + ->returns(new LazyCollection($entries)); // First chunk: 1000 entries (sequential DEL) $firstChunkArgs = []; for ($i = 1; $i <= 1000; ++$i) { $firstChunkArgs[] = "prefix:key{$i}"; } - $connection->expects('zrem') + $client->expects('zrem') ->with('prefix:_all:tag:users:entries', ...array_slice($entries, 0, 1000)) - ->andReturn(1000)->ordered(); - $connection->shouldReceive('del') - ->once() + ->returns(1000)->ordered(); + $client->expects('del') ->with(...$firstChunkArgs) - ->andReturn(1000)->ordered(); + ->returns(1000)->ordered(); // Second chunk: 500 entries (sequential DEL) $secondChunkArgs = []; for ($i = 1001; $i <= 1500; ++$i) { $secondChunkArgs[] = "prefix:key{$i}"; } - $connection->expects('zrem') + $client->expects('zrem') ->with('prefix:_all:tag:users:entries', ...array_slice($entries, 1000)) - ->andReturn(500)->ordered(); - $connection->shouldReceive('del') - ->once() + ->returns(500)->ordered(); + $client->expects('del') ->with(...$secondChunkArgs) - ->andReturn(500)->ordered(); + ->returns(500)->ordered(); $operation = new Flush($store->getContext(), $getEntries); $operation->execute(['_all:tag:users:entries']); @@ -329,33 +317,28 @@ public function testFlushInClusterModeChunksLargeSets(): void public function testFlushInClusterModeWithMultipleTags(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:users:entries']) - ->andReturn(new LazyCollection(['user_key1', 'shared_key'])); - $getEntries->shouldReceive('execute') - ->once() + ->returns(new LazyCollection(['user_key1', 'shared_key'])); + $getEntries->expects('execute') ->with(['_all:tag:posts:entries']) - ->andReturn(new LazyCollection(['shared_key', 'post_key1'])); + ->returns(new LazyCollection(['shared_key', 'post_key1'])); - // Cluster mode should NOT use pipeline - $connection->shouldNotReceive('pipeline'); - - $connection->expects('zrem') + $client->expects('zrem') ->with('prefix:_all:tag:users:entries', 'user_key1', 'shared_key') - ->andReturn(2)->ordered(); - $connection->expects('del') + ->returns(2)->ordered(); + $client->expects('del') ->with('prefix:user_key1', 'prefix:shared_key') - ->andReturn(2)->ordered(); - $connection->expects('zrem') + ->returns(2)->ordered(); + $client->expects('zrem') ->with('prefix:_all:tag:posts:entries', 'shared_key', 'post_key1') - ->andReturn(2)->ordered(); - $connection->expects('del') + ->returns(2)->ordered(); + $client->expects('del') ->with('prefix:shared_key', 'prefix:post_key1') - ->andReturn(1)->ordered(); + ->returns(1)->ordered(); $operation = new Flush($store->getContext(), $getEntries); $operation->execute(['_all:tag:users:entries', '_all:tag:posts:entries']); @@ -363,20 +346,16 @@ public function testFlushInClusterModeWithMultipleTags(): void public function testFlushInClusterModeWithNoEntries(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); // Mock GetEntries to return empty collection - $getEntries = m::mock(GetEntries::class); - $getEntries->shouldReceive('execute') - ->once() + $getEntries = Double::for(GetEntries::class); + $getEntries->expects('execute') ->with(['_all:tag:users:entries']) - ->andReturn(new LazyCollection([])); - - // Cluster mode should NOT use pipeline - $connection->shouldNotReceive('pipeline'); + ->returns(new LazyCollection([])); - $connection->shouldNotReceive('del'); - $connection->shouldNotReceive('zrem'); + $client->expects('del')->never(); + $client->expects('zrem')->never(); $operation = new Flush($store->getContext(), $getEntries); $operation->execute(['_all:tag:users:entries']); diff --git a/tests/Cache/Redis/Operations/AllTag/ForeverTest.php b/tests/Cache/Redis/Operations/AllTag/ForeverTest.php index b8e3018774..16600ed0a6 100644 --- a/tests/Cache/Redis/Operations/AllTag/ForeverTest.php +++ b/tests/Cache/Redis/Operations/AllTag/ForeverTest.php @@ -15,23 +15,20 @@ public function testForeverStoresValueWithTagsInPipelineMode(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:mykey', serialize('myvalue')) - ->andReturn($connection) + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', -1, 'mykey') - ->andReturn($connection) + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', -1.0, 'mykey') + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 0]); + $connection->client()->expects('exec') + ->returns([true, 0]); $store = $this->createStore($connection); $result = $store->allTagOps()->forever()->execute( @@ -47,27 +44,23 @@ public function testForeverWithMultipleTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // ZADD for each tag with score -1 - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', -1, 'mykey') - ->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:posts:entries', -1, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', -1.0, 'mykey') + ->returns($connection->client()); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:posts:entries', -1.0, 'mykey') + ->returns($connection->client()); // SET for cache value - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:mykey', serialize('myvalue')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1, 1]); + $connection->client()->expects('exec') + ->returns([true, 1, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->forever()->execute( @@ -83,17 +76,15 @@ public function testForeverWithEmptyTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // SET for cache value only - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:mykey', serialize('myvalue')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true]); + $connection->client()->expects('exec') + ->returns([true]); $store = $this->createStore($connection); $result = $store->allTagOps()->forever()->execute( @@ -107,21 +98,16 @@ public function testForeverWithEmptyTags(): void public function testForeverInClusterModeUsesSequentialCommands(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - // Should NOT use pipeline in cluster mode - $connection->shouldNotReceive('pipeline'); - - $connection->shouldReceive('set') - ->once() + $client->expects('set') ->with('prefix:mykey', serialize('myvalue')) - ->andReturn(true) + ->returns(true) ->ordered(); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', -1, 'mykey') - ->andReturn(0) + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', -1.0, 'mykey') + ->returns(0) ->ordered(); $result = $store->allTagOps()->forever()->execute( @@ -137,15 +123,14 @@ public function testForeverReturnsFalseOnFailure(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); - $connection->shouldReceive('set')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); + $connection->client()->allows('set')->returns($connection->client()); // SET returns false (failure) - $connection->shouldReceive('exec') - ->once() - ->andReturn([false, 1]); + $connection->client()->expects('exec') + ->returns([false, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->forever()->execute( @@ -160,10 +145,10 @@ public function testForeverReturnsFalseOnFailure(): void public function testForeverReturnsFalseWhenPipelineMembershipWriteFails(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('set')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, false]); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('set')->returns($connection->client()); + $connection->client()->expects('zadd')->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, false]); $store = $this->createStore($connection); @@ -176,18 +161,18 @@ public function testForeverReturnsFalseWhenPipelineMembershipWriteFails(): void public function testForeverInClusterModeDoesNotPublishTagsWhenTheValueWriteFails(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->expects('set')->with('prefix:mykey', serialize('myvalue'))->andReturnFalse(); - $connection->shouldNotReceive('zadd'); + [$store, $client] = $this->createClusterStore(); + $client->expects('set')->with('prefix:mykey', serialize('myvalue'))->returns(false); + $client->expects('zadd')->never(); $this->assertFalse($store->allTagOps()->forever()->execute('mykey', 'myvalue', ['_all:tag:users:entries'])); } public function testForeverReturnsFalseWhenClusterMembershipWriteFails(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldReceive('set')->once()->andReturn(true); - $connection->shouldReceive('zadd')->once()->andReturn(false); + [$store, $client] = $this->createClusterStore(); + $client->expects('set')->returns(true); + $client->expects('zadd')->returns(false); $this->assertFalse($store->allTagOps()->forever()->execute( 'mykey', @@ -200,21 +185,18 @@ public function testForeverUsesCorrectPrefix(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('custom:_all:tag:users:entries', -1, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('custom:_all:tag:users:entries', -1.0, 'mykey') + ->returns($connection->client()); - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('custom:mykey', serialize('myvalue')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection, 'custom:'); $result = $store->allTagOps()->forever()->execute( @@ -230,19 +212,17 @@ public function testForeverWithNumericValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); // Numeric values are NOT serialized (optimization) - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:mykey', 42) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->forever()->execute( diff --git a/tests/Cache/Redis/Operations/AllTag/GetEntriesTest.php b/tests/Cache/Redis/Operations/AllTag/GetEntriesTest.php index e85e0bae94..cd2883e210 100644 --- a/tests/Cache/Redis/Operations/AllTag/GetEntriesTest.php +++ b/tests/Cache/Redis/Operations/AllTag/GetEntriesTest.php @@ -10,7 +10,10 @@ use Hypervel\Redis\RedisProxy; use Hypervel\Support\LazyCollection; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; -use Mockery as m; +use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; /** * Tests for the GetEntries operation. @@ -19,123 +22,74 @@ class GetEntriesTest extends RedisCacheTestCase { public function testGetEntriesReturnsLazyCollection(): void { - $connection = $this->mockConnection(); - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; + $client = new FakeRedisClient(zScanResults: [ + 'prefix:_all:tag:users:entries' => [ + ['members' => ['key1' => 1, 'key2' => 2], 'iterator' => 0], + ], + ]); - return ['key1' => 1, 'key2' => 2]; - }); - - $store = $this->createStore($connection); + $store = $this->createStoreWithFakeClient($client); $operation = new GetEntries($store->getContext()); $entries = $operation->execute(['_all:tag:users:entries']); $this->assertInstanceOf(LazyCollection::class, $entries); $this->assertSame(['key1', 'key2'], $entries->all()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); } public function testGetEntriesWithEmptyTagReturnsEmptyCollection(): void { - $connection = $this->mockConnection(); - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; + $client = new FakeRedisClient(zScanResults: [ + 'prefix:_all:tag:users:entries' => [ + ['members' => [], 'iterator' => 0], + ], + ]); - return []; - }); - - $store = $this->createStore($connection); + $store = $this->createStoreWithFakeClient($client); $operation = new GetEntries($store->getContext()); $entries = $operation->execute(['_all:tag:users:entries']); $this->assertSame([], $entries->all()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); } public function testGetEntriesWithMultipleTags(): void { - $connection = $this->mockConnection(); - - // First tag - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['user_key1' => 1, 'user_key2' => 2]; - }); - - // Second tag - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:posts:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['post_key1' => 1]; - }); - - $store = $this->createStore($connection); + $client = new FakeRedisClient(zScanResults: [ + 'prefix:_all:tag:users:entries' => [ + ['members' => ['user_key1' => 1, 'user_key2' => 2], 'iterator' => 0], + ], + 'prefix:_all:tag:posts:entries' => [ + ['members' => ['post_key1' => 1], 'iterator' => 0], + ], + ]); + + $store = $this->createStoreWithFakeClient($client); $operation = new GetEntries($store->getContext()); $entries = $operation->execute(['_all:tag:users:entries', '_all:tag:posts:entries']); // Should combine entries from both tags $this->assertSame(['user_key1', 'user_key2', 'post_key1'], $entries->all()); - } - - public function testGetEntriesReturnsTheMembersInEachPage(): void - { - $connection = $this->mockConnection(); - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['key1' => 1, 'key2' => 2]; - }); - - $store = $this->createStore($connection); - $operation = new GetEntries($store->getContext()); - - $entries = $operation->execute(['_all:tag:users:entries']); - - $this->assertSame(['key1', 'key2'], $entries->all()); - } - - public function testGetEntriesHandlesNullScanResult(): void - { - $connection = $this->mockConnection(); - // zScan returns null/false when done or empty - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnNull(); - - $store = $this->createStore($connection); - $operation = new GetEntries($store->getContext()); - - $entries = $operation->execute(['_all:tag:users:entries']); - - $this->assertSame([], $entries->all()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ['key' => 'prefix:_all:tag:posts:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); } public function testGetEntriesHandlesFalseScanResult(): void { $connection = $this->mockConnection(); - // zScan can return false in some cases - $connection->shouldReceive('zScan') - ->once() + // Native zScan returns false when no members are available. + $connection->client()->expects('zScan') ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturn(false); + ->returns(false); $store = $this->createStore($connection); $operation = new GetEntries($store->getContext()); @@ -149,7 +103,7 @@ public function testGetEntriesWithEmptyTagIdsArrayReturnsEmptyCollection(): void { $connection = $this->mockConnection(); // No zScan calls should be made - $connection->shouldNotReceive('zScan'); + $connection->expects('zScan')->never(); $store = $this->createStore($connection); $operation = new GetEntries($store->getContext()); @@ -161,92 +115,74 @@ public function testGetEntriesWithEmptyTagIdsArrayReturnsEmptyCollection(): void public function testGetEntriesUsesCorrectPrefix(): void { - $connection = $this->mockConnection(); - $connection->shouldReceive('zScan') - ->once() - ->with('custom_prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['key1' => 1]; - }); + $client = new FakeRedisClient(zScanResults: [ + 'custom_prefix:_all:tag:users:entries' => [ + ['members' => ['key1' => 1], 'iterator' => 0], + ], + ]); - $store = $this->createStore($connection, 'custom_prefix:'); + $store = $this->createStoreWithFakeClient($client, 'custom_prefix:'); $operation = new GetEntries($store->getContext()); $entries = $operation->execute(['_all:tag:users:entries']); $this->assertSame(['key1'], $entries->all()); + $this->assertSame([ + ['key' => 'custom_prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); } public function testGetEntriesHandlesPaginatedResults(): void { - $connection = $this->mockConnection(); - - // First page - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 123; // Non-zero cursor indicates more data - - return ['key1' => 1, 'key2' => 2]; - }); - - // Second page (returns remaining entries) - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', 123, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; // Zero cursor indicates end - - return ['key3' => 3]; - }); - - $store = $this->createStore($connection); + $client = new FakeRedisClient(zScanResults: [ + 'prefix:_all:tag:users:entries' => [ + ['members' => ['key1' => 1, 'key2' => 2], 'iterator' => 123], + ['members' => ['key3' => 3], 'iterator' => 0], + ], + ]); + + $store = $this->createStoreWithFakeClient($client); $operation = new GetEntries($store->getContext()); $entries = $operation->execute(['_all:tag:users:entries']); $this->assertSame(['key1', 'key2', 'key3'], $entries->all()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => 123, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); } public function testGetEntriesContinuesAfterAnEmptyNonterminalPageAndChecksOutPerPage(): void { - $connection = $this->mockConnection(); - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 123; - - return []; - }); - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', 123, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['key1' => 1]; - }); - - $proxy = m::mock(RedisProxy::class); - $proxy->shouldReceive('withConnection') - ->twice() - ->with(m::type('callable'), false) - ->andReturnUsing(fn (callable $callback) => $callback($connection)); - - $redis = m::mock(RedisFactory::class); - $redis->shouldReceive('connection') - ->twice() + $client = new FakeRedisClient(zScanResults: [ + 'prefix:_all:tag:users:entries' => [ + ['members' => [], 'iterator' => 123], + ['members' => ['key1' => 1], 'iterator' => 0], + ], + ]); + + $connection = (new PhpRedisConnectionStub)->setActiveConnection($client)->shouldTransform(false); + $proxy = Double::for(RedisProxy::class); + $proxy->expects('withConnection') + ->times(2) + ->with(Argument::type('callable'), false) + ->resolves(fn (callable $callback) => $callback($connection)); + + $redis = Double::for(RedisFactory::class); + $redis->expects('connection') + ->times(2) ->with('default') - ->andReturn($proxy); + ->returns($proxy); $store = new RedisStore($redis, 'prefix:', 'default'); $operation = new GetEntries($store->getContext()); $this->assertSame(['key1'], $operation->execute(['_all:tag:users:entries'])->all()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => 123, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); } /** @@ -256,34 +192,25 @@ public function testGetEntriesContinuesAfterAnEmptyNonterminalPageAndChecksOutPe */ public function testGetEntriesDoesNotDeduplicateAcrossTags(): void { - $connection = $this->mockConnection(); - - // First tag has 'shared_key' - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:users:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['shared_key' => 1, 'user_only' => 2]; - }); - - // Second tag also has 'shared_key' - $connection->shouldReceive('zScan') - ->once() - ->with('prefix:_all:tag:posts:entries', null, '*', 1000) - ->andReturnUsing(function ($key, &$cursor) { - $cursor = 0; - - return ['shared_key' => 1, 'post_only' => 2]; - }); - - $store = $this->createStore($connection); + $client = new FakeRedisClient(zScanResults: [ + 'prefix:_all:tag:users:entries' => [ + ['members' => ['shared_key' => 1, 'user_only' => 2], 'iterator' => 0], + ], + 'prefix:_all:tag:posts:entries' => [ + ['members' => ['shared_key' => 1, 'post_only' => 2], 'iterator' => 0], + ], + ]); + + $store = $this->createStoreWithFakeClient($client); $operation = new GetEntries($store->getContext()); $entries = $operation->execute(['_all:tag:users:entries', '_all:tag:posts:entries']); // 'shared_key' appears twice - once from each tag $this->assertSame(['shared_key', 'user_only', 'shared_key', 'post_only'], $entries->all()); + $this->assertSame([ + ['key' => 'prefix:_all:tag:users:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ['key' => 'prefix:_all:tag:posts:entries', 'iterator' => null, 'pattern' => '*', 'count' => 1000], + ], $client->getZScanCalls()); } } diff --git a/tests/Cache/Redis/Operations/AllTag/IncrementTest.php b/tests/Cache/Redis/Operations/AllTag/IncrementTest.php index a9de624872..be9831ff75 100644 --- a/tests/Cache/Redis/Operations/AllTag/IncrementTest.php +++ b/tests/Cache/Redis/Operations/AllTag/IncrementTest.php @@ -15,23 +15,20 @@ public function testIncrementWithTagsInPipelineMode(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('incrby') - ->once() + $connection->client()->expects('incrby') ->with('prefix:counter', 1) - ->andReturn($connection) + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'counter') - ->andReturn($connection) + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('exec') - ->once() - ->andReturn([5, 1]); + $connection->client()->expects('exec') + ->returns([5, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->increment()->execute( @@ -47,21 +44,18 @@ public function testIncrementWithCustomValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'counter') - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('incrby') - ->once() + $connection->client()->expects('incrby') ->with('prefix:counter', 10) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([15, 0]); // 0 means tag membership already existed + $connection->client()->expects('exec') + ->returns([15, 0]); // 0 means tag membership already existed $store = $this->createStore($connection); $result = $store->allTagOps()->increment()->execute( @@ -77,26 +71,22 @@ public function testIncrementWithMultipleTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // ZADD NX for each tag - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'counter') - ->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() + ->returns($connection->client()); + $connection->client()->expects('zadd') ->with('prefix:_all:tag:posts:entries', ['NX'], -1, 'counter') - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('incrby') - ->once() + $connection->client()->expects('incrby') ->with('prefix:counter', 1) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1, 1, 1]); + $connection->client()->expects('exec') + ->returns([1, 1, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->increment()->execute( @@ -112,17 +102,15 @@ public function testIncrementWithEmptyTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // No ZADD calls expected - $connection->shouldReceive('incrby') - ->once() + $connection->client()->expects('incrby') ->with('prefix:counter', 1) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([1]); + $connection->client()->expects('exec') + ->returns([1]); $store = $this->createStore($connection); $result = $store->allTagOps()->increment()->execute( @@ -136,18 +124,15 @@ public function testIncrementWithEmptyTags(): void public function testIncrementInClusterModeUsesSequentialCommands(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->shouldNotReceive('pipeline'); - - $connection->expects('incrby') + $client->expects('incrby') ->with('prefix:counter', 1) - ->andReturn(10) + ->returns(10) ->ordered(); - $connection->expects('zadd') - ->once() + $client->expects('zadd') ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'counter') - ->andReturn(1) + ->returns(1) ->ordered(); $result = $store->allTagOps()->increment()->execute( @@ -161,10 +146,10 @@ public function testIncrementInClusterModeUsesSequentialCommands(): void public function testIncrementInClusterModeDoesNotPublishTagsWhenTheCounterFails(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->expects('incrby')->with('prefix:counter', 1)->andReturnFalse(); - $connection->shouldNotReceive('zadd'); + $client->expects('incrby')->with('prefix:counter', 1)->returns(false); + $client->expects('zadd')->never(); $this->assertFalse($store->allTagOps()->increment()->execute( 'counter', @@ -177,14 +162,13 @@ public function testIncrementReturnsFalseOnPipelineFailure(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); - $connection->shouldReceive('incrby')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); + $connection->client()->allows('incrby')->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn(false); + $connection->client()->expects('exec') + ->returns(false); $store = $this->createStore($connection); $result = $store->allTagOps()->increment()->execute( diff --git a/tests/Cache/Redis/Operations/AllTag/PruneTest.php b/tests/Cache/Redis/Operations/AllTag/PruneTest.php index 20efaf8d98..da4a8027c0 100644 --- a/tests/Cache/Redis/Operations/AllTag/PruneTest.php +++ b/tests/Cache/Redis/Operations/AllTag/PruneTest.php @@ -7,6 +7,9 @@ use Hypervel\Cache\Redis\Operations\AllTag\Prune; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; +use Hypervel\Tests\Redis\Fixtures\FakeRedisClusterClient; +use Hypervel\Tests\Redis\Fixtures\PhpRedisClusterConnectionStub; +use RedisCluster; class PruneTest extends RedisCacheTestCase { @@ -310,113 +313,75 @@ public function testPruneContinuesAfterAnEmptyNonterminalMemberPage(): void public function testClusterPruneBatchesOrphansThatRemainRemoved(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldNotReceive('pipeline'); - $connection->shouldReceive('isCluster')->once()->andReturn(true); - $connection->shouldReceive('getShouldTransform')->once()->andReturn(false); - $connection->shouldReceive('masters')->once()->andReturn([['127.0.0.1', 7000]]); - $connection->shouldReceive('scan') - ->once() - ->andReturnUsing(function (&$iterator, $master, $pattern, $count): array { - $iterator = 0; - - return ['prefix:_all:tag:users:entries']; - }); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zScan') - ->once() - ->andReturnUsing(function ($tagKey, &$iterator): array { - $iterator = 0; - - return ['live' => 1.0, 'orphan1' => 2.0, 'orphan2' => 3.0]; - }); - $connection->shouldReceive('exists')->once()->with('prefix:live')->andReturn(1); - $connection->shouldReceive('exists')->twice()->with('prefix:orphan1')->andReturn(0); - $connection->shouldReceive('exists')->twice()->with('prefix:orphan2')->andReturn(0); - $connection->shouldReceive('zrem') - ->once() - ->with('prefix:_all:tag:users:entries', 'orphan1', 'orphan2') - ->andReturn(2); - $connection->shouldReceive('zCard')->once()->andReturn(1); + $client = new PruneRedisClusterClient( + ['live' => 1.0, 'orphan1' => 2.0, 'orphan2' => 3.0], + ['prefix:live' => [1], 'prefix:orphan1' => [0, 0], 'prefix:orphan2' => [0, 0]], + removed: 2, + ); + $connection = (new PhpRedisClusterConnectionStub)->setActiveConnection($client); + $store = $this->createStore($connection); $result = (new Prune($store->getContext()))->execute(); $this->assertSame(3, $result['entries_checked']); $this->assertSame(2, $result['orphans_removed']); + $this->assertSame([ + ['zRemRangeByScore', 'prefix:_all:tag:users:entries'], + ['zscan', 'prefix:_all:tag:users:entries', null, '*', 1000], + ['exists', 'prefix:live'], + ['exists', 'prefix:orphan1'], + ['exists', 'prefix:orphan2'], + ['zrem', 'prefix:_all:tag:users:entries', 'orphan1', 'orphan2'], + ['exists', 'prefix:orphan1'], + ['exists', 'prefix:orphan2'], + ['zCard', 'prefix:_all:tag:users:entries'], + ], $client->commands); + $this->assertCount(1, $client->getScanCalls()); + $this->assertSame(1, $client->mastersRequested); } public function testClusterPruneRepairsMembershipWithoutOverwritingAWriterScore(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldReceive('isCluster')->once()->andReturn(true); - $connection->shouldReceive('getShouldTransform')->once()->andReturn(false); - $connection->shouldReceive('masters')->once()->andReturn([['127.0.0.1', 7000]]); - $connection->shouldReceive('scan') - ->once() - ->andReturnUsing(function (&$iterator, $master, $pattern, $count): array { - $iterator = 0; - - return ['prefix:_all:tag:users:entries']; - }); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zScan') - ->once() - ->andReturnUsing(function ($tagKey, &$iterator): array { - $iterator = 0; - - return ['raced' => 1.0]; - }); - $connection->shouldReceive('exists') - ->twice() - ->with('prefix:raced') - ->andReturn(0, 1); - $connection->shouldReceive('zrem')->once()->andReturn(1); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'raced') - ->andReturn(0); - $connection->shouldReceive('zCard')->once()->andReturn(1); + $client = new PruneRedisClusterClient(['raced' => 1.0], ['prefix:raced' => [0, 1]], removed: 1); + $connection = (new PhpRedisClusterConnectionStub)->setActiveConnection($client); + $store = $this->createStore($connection); $result = (new Prune($store->getContext()))->execute(); $this->assertSame(0, $result['orphans_removed']); + $this->assertSame([ + ['zRemRangeByScore', 'prefix:_all:tag:users:entries'], + ['zscan', 'prefix:_all:tag:users:entries', null, '*', 1000], + ['exists', 'prefix:raced'], + ['zrem', 'prefix:_all:tag:users:entries', 'raced'], + ['exists', 'prefix:raced'], + ['zadd', 'prefix:_all:tag:users:entries', ['NX'], -1, 'raced'], + ['zCard', 'prefix:_all:tag:users:entries'], + ], $client->commands); + $this->assertCount(1, $client->getScanCalls()); + $this->assertSame(1, $client->mastersRequested); } public function testClusterPruneRepairsMembershipAfterConcurrentRemovalReturnsZero(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldReceive('isCluster')->once()->andReturn(true); - $connection->shouldReceive('getShouldTransform')->once()->andReturn(false); - $connection->shouldReceive('masters')->once()->andReturn([['127.0.0.1', 7000]]); - $connection->shouldReceive('scan') - ->once() - ->andReturnUsing(function (&$iterator): array { - $iterator = 0; - - return ['prefix:_all:tag:users:entries']; - }); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zScan') - ->once() - ->andReturnUsing(function ($tagKey, &$iterator): array { - $iterator = 0; - - return ['raced' => 1.0]; - }); - $connection->shouldReceive('exists') - ->twice() - ->with('prefix:raced') - ->andReturn(0, 1); - $connection->shouldReceive('zrem')->once()->andReturn(0); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', ['NX'], -1, 'raced') - ->andReturn(0); - $connection->shouldReceive('zCard')->once()->andReturn(1); + $client = new PruneRedisClusterClient(['raced' => 1.0], ['prefix:raced' => [0, 1]], removed: 0); + $connection = (new PhpRedisClusterConnectionStub)->setActiveConnection($client); + $store = $this->createStore($connection); $result = (new Prune($store->getContext()))->execute(); $this->assertSame(0, $result['orphans_removed']); + $this->assertSame([ + ['zRemRangeByScore', 'prefix:_all:tag:users:entries'], + ['zscan', 'prefix:_all:tag:users:entries', null, '*', 1000], + ['exists', 'prefix:raced'], + ['zrem', 'prefix:_all:tag:users:entries', 'raced'], + ['exists', 'prefix:raced'], + ['zadd', 'prefix:_all:tag:users:entries', ['NX'], -1, 'raced'], + ['zCard', 'prefix:_all:tag:users:entries'], + ], $client->commands); + $this->assertCount(1, $client->getScanCalls()); + $this->assertSame(1, $client->mastersRequested); } public function testPruneHandlesOptPrefixCorrectly(): void @@ -450,3 +415,83 @@ public function testPruneHandlesOptPrefixCorrectly(): void $this->assertSame(1, $result['tags_scanned']); } } + +/** + * Simulate changing key existence while preserving native scan cursor updates. + */ +class PruneRedisClusterClient extends FakeRedisClusterClient +{ + public array $commands = []; + + /** + * Configure the members and successive existence checks for one tag. + */ + public function __construct(private array $members, private array $existence, private int $removed) + { + parent::__construct( + masters: [['127.0.0.1', 7000]], + scanResults: ['127.0.0.1:7000' => [['keys' => ['prefix:_all:tag:users:entries'], 'iterator' => 0]]], + ); + } + + /** + * Return the tag members and finish the scan. + */ + public function zscan(string $key, int|string|null &$iterator, ?string $pattern = null, int $count = 0): RedisCluster|array|false + { + $this->commands[] = ['zscan', $key, $iterator, $pattern, $count]; + $iterator = 0; + + return $this->members; + } + + /** + * Return the next existence result for the key. + */ + public function exists(mixed $key, mixed ...$other_keys): RedisCluster|int|bool + { + $this->commands[] = ['exists', $key, ...$other_keys]; + + return array_shift($this->existence[$key]); + } + + /** + * Record the batched removal and return its configured result. + */ + public function zrem(mixed $key, mixed $member, mixed ...$other_members): RedisCluster|int|false + { + $this->commands[] = ['zrem', $key, $member, ...$other_members]; + + return $this->removed; + } + + /** + * Record the membership repair without replacing the writer's score. + */ + public function zadd(string $key, array|float $score_or_options, mixed ...$more_scores_and_mems): RedisCluster|int|float|false + { + $this->commands[] = ['zadd', $key, $score_or_options, ...$more_scores_and_mems]; + + return 0; + } + + /** + * Keep the tag set nonempty after pruning. + */ + public function zCard(string $key): RedisCluster|int|false + { + $this->commands[] = ['zCard', $key]; + + return 1; + } + + /** + * Keep the configured members available for orphan checks. + */ + public function zRemRangeByScore(string $key, string $min, string $max): RedisCluster|int|false + { + $this->commands[] = ['zRemRangeByScore', $key]; + + return 0; + } +} diff --git a/tests/Cache/Redis/Operations/AllTag/PutManyTest.php b/tests/Cache/Redis/Operations/AllTag/PutManyTest.php index 6ddfb1af7a..9d05bbb3da 100644 --- a/tests/Cache/Redis/Operations/AllTag/PutManyTest.php +++ b/tests/Cache/Redis/Operations/AllTag/PutManyTest.php @@ -23,31 +23,27 @@ public function testPutManyWithTagsInPipelineMode(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $expectedScore = 1061; - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:foo', 60, serialize('bar')) - ->andReturn($connection) + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:baz', 60, serialize('qux')) - ->andReturn($connection) + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', $expectedScore, 'ns:foo', $expectedScore, 'ns:baz') - ->andReturn($connection) + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', (float) $expectedScore, 'ns:foo', $expectedScore, 'ns:baz') + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, true, 0]); + $connection->client()->expects('exec') + ->returns([true, true, 0]); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -64,29 +60,25 @@ public function testPutManyWithMultipleTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $expectedScore = 1121; // Variadic ZADD for each tag (one command per tag, all keys as members) - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', $expectedScore, 'ns:foo') - ->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:posts:entries', $expectedScore, 'ns:foo') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', (float) $expectedScore, 'ns:foo') + ->returns($connection->client()); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:posts:entries', (float) $expectedScore, 'ns:foo') + ->returns($connection->client()); // SETEX for the key - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:foo', 120, serialize('bar')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1, 1]); + $connection->client()->expects('exec') + ->returns([true, 1, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -103,17 +95,15 @@ public function testPutManyWithEmptyTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // Only SETEX, no ZADD - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:foo', 60, serialize('bar')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true]); + $connection->client()->expects('exec') + ->returns([true]); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -131,7 +121,7 @@ public function testPutManyWithEmptyValuesReturnsTrue(): void $connection = $this->mockConnection(); // No pipeline operations for empty values - $connection->shouldNotReceive('pipeline'); + $connection->client()->expects('pipeline')->never(); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -146,29 +136,23 @@ public function testPutManyWithEmptyValuesReturnsTrue(): void public function testPutManyInClusterModeUsesVariadicZadd(): void { - [$store, , $connection] = $this->createClusterStore(); - - // Should NOT use pipeline in cluster mode - $connection->shouldNotReceive('pipeline'); + [$store, $client] = $this->createClusterStore(); $expectedScore = 1061; - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:foo', 60, serialize('bar')) - ->andReturn(true) + ->returns(true) ->ordered(); - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:baz', 60, serialize('qux')) - ->andReturn(true) + ->returns(true) ->ordered(); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', $expectedScore, 'ns:foo', $expectedScore, 'ns:baz') - ->andReturn(0) + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', (float) $expectedScore, 'ns:foo', $expectedScore, 'ns:baz') + ->returns(0) ->ordered(); $result = $store->allTagOps()->putMany()->execute( @@ -185,15 +169,14 @@ public function testPutManyReturnsFalseOnFailure(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); - $connection->shouldReceive('setex')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); + $connection->client()->allows('setex')->returns($connection->client()); // One SETEX fails - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, false, 1]); + $connection->client()->expects('exec') + ->returns([true, false, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -210,15 +193,14 @@ public function testPutManyReturnsFalseOnPipelineFailure(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); - $connection->shouldReceive('setex')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); + $connection->client()->allows('setex')->returns($connection->client()); // Pipeline fails entirely - $connection->shouldReceive('exec') - ->once() - ->andReturn(false); + $connection->client()->expects('exec') + ->returns(false); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -234,10 +216,10 @@ public function testPutManyReturnsFalseOnPipelineFailure(): void public function testPutManyReturnsFalseWhenPipelineMembershipWriteFails(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('setex')->twice()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, true, false]); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('setex')->times(2)->returns($connection->client()); + $connection->client()->expects('zadd')->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, true, false]); $store = $this->createStore($connection); @@ -253,22 +235,19 @@ public function testPutManyEnforcesMinimumTtlOfOne(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1002, 'ns:foo') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1002.0, 'ns:foo') + ->returns($connection->client()); // TTL should be at least 1 - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:foo', 1, serialize('bar')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -285,19 +264,17 @@ public function testPutManyWithNumericValues(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); // Numeric values are NOT serialized (optimization) - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:count', 60, 42) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -314,24 +291,21 @@ public function testPutManyUsesCorrectPrefix(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $expectedScore = 1031; // Custom prefix should be used - $connection->shouldReceive('zadd') - ->once() - ->with('custom:_all:tag:users:entries', $expectedScore, 'ns:foo') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('custom:_all:tag:users:entries', (float) $expectedScore, 'ns:foo') + ->returns($connection->client()); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('custom:ns:foo', 30, serialize('bar')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection, 'custom:'); $result = $store->allTagOps()->putMany()->execute( @@ -353,41 +327,35 @@ public function testPutManyWithMultipleTagsAndMultipleKeys(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); $expectedScore = 1061; // Variadic ZADD for first tag with all keys - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', $expectedScore, 'ns:a', $expectedScore, 'ns:b', $expectedScore, 'ns:c') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', (float) $expectedScore, 'ns:a', $expectedScore, 'ns:b', $expectedScore, 'ns:c') + ->returns($connection->client()); // Variadic ZADD for second tag with all keys - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:posts:entries', $expectedScore, 'ns:a', $expectedScore, 'ns:b', $expectedScore, 'ns:c') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:posts:entries', (float) $expectedScore, 'ns:a', $expectedScore, 'ns:b', $expectedScore, 'ns:c') + ->returns($connection->client()); // SETEX for each key - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:a', 60, serialize('val-a')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:b', 60, serialize('val-b')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:ns:c', 60, serialize('val-c')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, true, true, 3, 3]); + $connection->client()->expects('exec') + ->returns([true, true, true, 3, 3]); $store = $this->createStore($connection); $result = $store->allTagOps()->putMany()->execute( @@ -402,31 +370,27 @@ public function testPutManyWithMultipleTagsAndMultipleKeys(): void public function testPutManyInClusterModeWithMultipleTags(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); $expectedScore = 1061; // Variadic ZADD for each tag (different slots, separate commands) - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', $expectedScore, 'ns:foo', $expectedScore, 'ns:bar') - ->andReturn(2); + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', (float) $expectedScore, 'ns:foo', $expectedScore, 'ns:bar') + ->returns(2); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:posts:entries', $expectedScore, 'ns:foo', $expectedScore, 'ns:bar') - ->andReturn(2); + $client->expects('zadd') + ->with('prefix:_all:tag:posts:entries', (float) $expectedScore, 'ns:foo', $expectedScore, 'ns:bar') + ->returns(2); // SETEXs for each key - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:foo', 60, serialize('value1')) - ->andReturn(true); + ->returns(true); - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:bar', 60, serialize('value2')) - ->andReturn(true); + ->returns(true); $result = $store->allTagOps()->putMany()->execute( ['foo' => 'value1', 'bar' => 'value2'], @@ -440,16 +404,15 @@ public function testPutManyInClusterModeWithMultipleTags(): void public function testPutManyInClusterModeWithEmptyTags(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); // No ZADD calls for empty tags - $connection->shouldNotReceive('zadd'); + $client->expects('zadd')->never(); // Only SETEXs - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:foo', 60, serialize('bar')) - ->andReturn(true); + ->returns(true); $result = $store->allTagOps()->putMany()->execute( ['foo' => 'bar'], @@ -463,25 +426,22 @@ public function testPutManyInClusterModeWithEmptyTags(): void public function testPutManyInClusterModeReturnsFalseOnSetexFailure(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); $expectedScore = 1061; - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', $expectedScore, 'ns:foo') - ->andReturn(1); + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', (float) $expectedScore, 'ns:foo') + ->returns(1); // First SETEX succeeds, second fails - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:foo', 60, serialize('value1')) - ->andReturn(true); + ->returns(true); - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:bar', 60, serialize('value2')) - ->andReturn(false); + ->returns(false); $result = $store->allTagOps()->putMany()->execute( ['foo' => 'value1', 'bar' => 'value2'], @@ -495,19 +455,17 @@ public function testPutManyInClusterModeReturnsFalseOnSetexFailure(): void public function testPutManyInClusterModeSkipsMembershipsWhenAllWritesFail(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:foo', 60, serialize('value1')) - ->andReturn(false); + ->returns(false); - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:ns:bar', 60, serialize('value2')) - ->andReturn(false); + ->returns(false); - $connection->shouldNotReceive('zadd'); + $client->expects('zadd')->never(); $result = $store->allTagOps()->putMany()->execute( ['foo' => 'value1', 'bar' => 'value2'], @@ -521,10 +479,10 @@ public function testPutManyInClusterModeSkipsMembershipsWhenAllWritesFail(): voi public function testPutManyInClusterModeReturnsFalseWhenMembershipWriteFails(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - $connection->shouldReceive('setex')->once()->andReturn(true); - $connection->shouldReceive('zadd')->once()->andReturn(false); + $client->expects('setex')->returns(true); + $client->expects('zadd')->returns(false); $this->assertFalse($store->allTagOps()->putMany()->execute( ['foo' => 'bar'], @@ -536,11 +494,11 @@ public function testPutManyInClusterModeReturnsFalseWhenMembershipWriteFails(): public function testPutManyInClusterModeWithEmptyValuesReturnsTrue(): void { - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); // No operations for empty values - $connection->shouldNotReceive('zadd'); - $connection->shouldNotReceive('setex'); + $client->expects('zadd')->never(); + $client->expects('setex')->never(); $result = $store->allTagOps()->putMany()->execute( [], diff --git a/tests/Cache/Redis/Operations/AllTag/PutTest.php b/tests/Cache/Redis/Operations/AllTag/PutTest.php index 9b336c9da5..6e009a4b53 100644 --- a/tests/Cache/Redis/Operations/AllTag/PutTest.php +++ b/tests/Cache/Redis/Operations/AllTag/PutTest.php @@ -18,23 +18,20 @@ public function testPutStoresValueWithTagsInPipelineMode(): void $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:mykey', 60, serialize('myvalue')) - ->andReturn($connection) + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1061, 'mykey') - ->andReturn($connection) + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1061.0, 'mykey') + ->returns($connection->client()) ->ordered(); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->put()->execute( @@ -53,29 +50,25 @@ public function testPutWithMultipleTags(): void $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $expectedScore = 1121; + $expectedScore = 1121.0; // ZADD for each tag - $connection->shouldReceive('zadd') - ->once() + $connection->client()->expects('zadd') ->with('prefix:_all:tag:users:entries', $expectedScore, 'mykey') - ->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() + ->returns($connection->client()); + $connection->client()->expects('zadd') ->with('prefix:_all:tag:posts:entries', $expectedScore, 'mykey') - ->andReturn($connection); + ->returns($connection->client()); // SETEX for cache value - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:mykey', 120, serialize('myvalue')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1, 1]); + $connection->client()->expects('exec') + ->returns([true, 1, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->put()->execute( @@ -92,18 +85,16 @@ public function testPutWithEmptyTagsStillStoresValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); // No ZADD calls expected // SETEX for cache value - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:mykey', 60, serialize('myvalue')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true]); + $connection->client()->expects('exec') + ->returns([true]); $store = $this->createStore($connection); $result = $store->allTagOps()->put()->execute( @@ -122,21 +113,18 @@ public function testPutUsesCorrectPrefix(): void $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('custom:_all:tag:users:entries', 1031, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('custom:_all:tag:users:entries', 1031.0, 'mykey') + ->returns($connection->client()); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('custom:mykey', 30, serialize('myvalue')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection, 'custom:'); $result = $store->allTagOps()->put()->execute( @@ -153,15 +141,14 @@ public function testPutReturnsFalseOnFailure(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); - $connection->shouldReceive('setex')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); + $connection->client()->allows('setex')->returns($connection->client()); // SETEX returns false (failure) - $connection->shouldReceive('exec') - ->once() - ->andReturn([false, 1]); + $connection->client()->expects('exec') + ->returns([false, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->put()->execute( @@ -177,10 +164,10 @@ public function testPutReturnsFalseOnFailure(): void public function testPutReturnsFalseWhenPipelineMembershipWriteFails(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('setex')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, false]); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('setex')->returns($connection->client()); + $connection->client()->expects('zadd')->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, false]); $store = $this->createStore($connection); @@ -195,10 +182,10 @@ public function testPutReturnsFalseWhenPipelineMembershipWriteFails(): void public function testPutTreatsZeroPipelineMembershipResultAsSuccess(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); - $connection->shouldReceive('setex')->once()->andReturn($connection); - $connection->shouldReceive('zadd')->once()->andReturn($connection); - $connection->shouldReceive('exec')->once()->andReturn([true, 0]); + $connection->client()->expects('pipeline')->returns($connection->client()); + $connection->client()->expects('setex')->returns($connection->client()); + $connection->client()->expects('zadd')->returns($connection->client()); + $connection->client()->expects('exec')->returns([true, 0]); $store = $this->createStore($connection); @@ -214,21 +201,16 @@ public function testPutInClusterModeUsesSequentialCommands(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); - [$store, , $connection] = $this->createClusterStore(); + [$store, $client] = $this->createClusterStore(); - // Should NOT use pipeline in cluster mode - $connection->shouldNotReceive('pipeline'); - - $connection->shouldReceive('setex') - ->once() + $client->expects('setex') ->with('prefix:mykey', 60, serialize('myvalue')) - ->andReturn(true) + ->returns(true) ->ordered(); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1061, 'mykey') - ->andReturn(1) + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1061.0, 'mykey') + ->returns(1) ->ordered(); $result = $store->allTagOps()->put()->execute( @@ -243,18 +225,18 @@ public function testPutInClusterModeUsesSequentialCommands(): void public function testPutInClusterModeDoesNotPublishTagsWhenTheValueWriteFails(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->expects('setex')->with('prefix:mykey', 60, serialize('myvalue'))->andReturnFalse(); - $connection->shouldNotReceive('zadd'); + [$store, $client] = $this->createClusterStore(); + $client->expects('setex')->with('prefix:mykey', 60, serialize('myvalue'))->returns(false); + $client->expects('zadd')->never(); $this->assertFalse($store->allTagOps()->put()->execute('mykey', 'myvalue', 60, ['_all:tag:users:entries'])); } public function testPutReturnsFalseWhenClusterMembershipWriteFails(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldReceive('setex')->once()->andReturn(true); - $connection->shouldReceive('zadd')->once()->andReturn(false); + [$store, $client] = $this->createClusterStore(); + $client->expects('setex')->returns(true); + $client->expects('zadd')->returns(false); $this->assertFalse($store->allTagOps()->put()->execute( 'mykey', @@ -266,9 +248,9 @@ public function testPutReturnsFalseWhenClusterMembershipWriteFails(): void public function testPutTreatsZeroClusterMembershipResultAsSuccess(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldReceive('setex')->once()->andReturn(true); - $connection->shouldReceive('zadd')->once()->andReturn(0); + [$store, $client] = $this->createClusterStore(); + $client->expects('setex')->returns(true); + $client->expects('zadd')->returns(0); $this->assertTrue($store->allTagOps()->put()->execute( 'mykey', @@ -283,22 +265,19 @@ public function testPutEnforcesMinimumTtlOfOne(): void CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1002, 'mykey') - ->andReturn($connection); + $connection->client()->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1002.0, 'mykey') + ->returns($connection->client()); // TTL should be at least 1 - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:mykey', 1, serialize('myvalue')) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->put()->execute( @@ -315,19 +294,17 @@ public function testPutWithNumericValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('pipeline')->once()->andReturn($connection); + $connection->client()->expects('pipeline')->returns($connection->client()); - $connection->shouldReceive('zadd')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); // Numeric values are NOT serialized (optimization) - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:mykey', 60, 42) - ->andReturn($connection); + ->returns($connection->client()); - $connection->shouldReceive('exec') - ->once() - ->andReturn([true, 1]); + $connection->client()->expects('exec') + ->returns([true, 1]); $store = $this->createStore($connection); $result = $store->allTagOps()->put()->execute( diff --git a/tests/Cache/Redis/Operations/AllTag/TouchTest.php b/tests/Cache/Redis/Operations/AllTag/TouchTest.php index cd432e9750..f722488f14 100644 --- a/tests/Cache/Redis/Operations/AllTag/TouchTest.php +++ b/tests/Cache/Redis/Operations/AllTag/TouchTest.php @@ -6,7 +6,7 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; -use Mockery as m; +use JMac\Testing\Matching\Argument; class TouchTest extends RedisCacheTestCase { @@ -15,14 +15,13 @@ public function testTouchRoundsTagScoreUpAtFractionalSecondInLuaMode(): void CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() + $connection->expects('evalWithShaCache') ->with( - m::type('string'), + Argument::type('string'), ['prefix:mykey', 'prefix:_all:tag:users:entries'], [60, 1061, 'mykey'], ) - ->andReturn(1); + ->returns(1); $store = $this->createStore($connection); @@ -37,15 +36,13 @@ public function testTouchRoundsTagScoreUpAtFractionalSecondInClusterMode(): void { CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000')); - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldReceive('expire') - ->once() + [$store, $client] = $this->createClusterStore(); + $client->expects('expire') ->with('prefix:mykey', 60) - ->andReturn(true); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_all:tag:users:entries', 1061, 'mykey') - ->andReturn(0); + ->returns(true); + $client->expects('zadd') + ->with('prefix:_all:tag:users:entries', 1061.0, 'mykey') + ->returns(0); $this->assertTrue($store->allTagOps()->touch()->execute( 'mykey', @@ -56,9 +53,9 @@ public function testTouchRoundsTagScoreUpAtFractionalSecondInClusterMode(): void public function testTouchReturnsFalseWhenClusterMembershipWriteFails(): void { - [$store, , $connection] = $this->createClusterStore(); - $connection->shouldReceive('expire')->once()->andReturn(true); - $connection->shouldReceive('zadd')->once()->andReturn(false); + [$store, $client] = $this->createClusterStore(); + $client->expects('expire')->returns(true); + $client->expects('zadd')->returns(false); $this->assertFalse($store->allTagOps()->touch()->execute( 'mykey', diff --git a/tests/Cache/Redis/Operations/AnyTag/AddTest.php b/tests/Cache/Redis/Operations/AnyTag/AddTest.php index 75f3e502f3..c864f1a583 100644 --- a/tests/Cache/Redis/Operations/AnyTag/AddTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/AddTest.php @@ -6,6 +6,7 @@ use Hypervel\Cache\Redis\Support\StoreContext; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; +use JMac\Testing\Matching\Argument; class AddTest extends RedisCacheTestCase { @@ -14,9 +15,8 @@ public function testAddWithTagsReturnsTrueWhenKeyAdded(): void $connection = $this->mockConnection(); // evalWithShaCache returns true (key added) - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args) { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args) { $this->assertStringContainsString('SET', $script); $this->assertStringContainsString('NX', $script); $this->assertStringContainsString("redis.call('HSETEX', tagHash, 'EX', ttl, 'FIELDS', 1, rawKey, '1')", $script); @@ -24,8 +24,8 @@ public function testAddWithTagsReturnsTrueWhenKeyAdded(): void $this->assertSame(60, $args[1]); return true; - }) - ->andReturn(true); + })) + ->returns(true); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -38,9 +38,8 @@ public function testAddWithTagsReturnsFalseWhenKeyExists(): void $connection = $this->mockConnection(); // Lua script returns false when key already exists (SET NX fails) - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(false); + $connection->expects('evalWithShaCache') + ->returns(false); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -50,57 +49,51 @@ public function testAddWithTagsReturnsFalseWhenKeyExists(): void public function testAddWithoutTtlIsPermanentInClusterMode(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); - $connection->shouldReceive('set') - ->once() + $client->expects('set') ->with('prefix:foo', serialize('bar'), ['NX']) - ->andReturn(true); - $connection->shouldReceive('multi')->once()->andReturnSelf(); - $connection->shouldReceive('sadd')->once()->with('prefix:foo:_any:tags', 'users')->andReturnSelf(); - $connection->shouldNotReceive('expire'); - $connection->shouldReceive('exec')->once()->andReturn([]); - $connection->shouldReceive('hSet') - ->once() + ->returns(true); + $client->expects('multi')->returns($client); + $client->expects('sadd')->with('prefix:foo:_any:tags', 'users')->returns($client); + $client->expects('expire')->never(); + $client->expects('exec')->returns([]); + $client->expects('hSet') ->with('prefix:_any:tag:users:entries', 'foo', StoreContext::TAG_FIELD_VALUE) - ->andReturn(1); - $connection->shouldNotReceive('hsetex'); - $connection->shouldReceive('zadd') - ->once() + ->returns(1); + $client->expects('hsetex')->never(); + $client->expects('zadd') ->with('prefix:_any:tag:registry', ['GT'], StoreContext::MAX_EXPIRY, 'users') - ->andReturn(1); + ->returns(1); $this->assertTrue($redis->anyTagOps()->add()->execute('foo', 'bar', null, ['users'])); } public function testAddNormalizesExpiringMetadataInClusterMode(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); $startedAt = time(); - $connection->shouldReceive('set') - ->once() + $client->expects('set') ->with('prefix:foo', serialize('bar'), ['EX' => 1, 'NX']) - ->andReturn(true); - $connection->shouldReceive('multi')->once()->andReturnSelf(); - $connection->shouldReceive('sadd')->once()->with('prefix:foo:_any:tags', 'users')->andReturnSelf(); - $connection->shouldReceive('expire')->once()->with('prefix:foo:_any:tags', 1)->andReturnSelf(); - $connection->shouldReceive('exec')->once()->andReturn([]); - $connection->shouldReceive('hsetex') - ->once() + ->returns(true); + $client->expects('multi')->returns($client); + $client->expects('sadd')->with('prefix:foo:_any:tags', 'users')->returns($client); + $client->expects('expire')->with('prefix:foo:_any:tags', 1)->returns($client); + $client->expects('exec')->returns([]); + $client->expects('hsetex') ->with('prefix:_any:tag:users:entries', ['foo' => '1'], ['EX' => 1]) - ->andReturn(1); - $connection->shouldReceive('zadd') - ->once() - ->withArgs(function (string $key, array $options, int $expiresAt, string $tag) use ($startedAt): bool { + ->returns(1); + $client->expects('zadd') + ->with(Argument::all(function (string $key, array $options, int $expiresAt, string $tag) use ($startedAt): bool { $this->assertSame('prefix:_any:tag:registry', $key); $this->assertSame(['GT'], $options); $this->assertGreaterThan($startedAt, $expiresAt); $this->assertSame('users', $tag); return true; - }) - ->andReturn(1); + })) + ->returns(1); $this->assertTrue($redis->anyTagOps()->add()->execute('foo', 'bar', -60, ['users'])); } @@ -108,9 +101,8 @@ public function testAddNormalizesExpiringMetadataInClusterMode(): void public function testAddWithoutTtlUsesPermanentLuaBranch(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function (string $script, array $keys, array $args): bool { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function (string $script, array $keys, array $args): bool { $this->assertStringContainsString("redis.call('SET', key, val, 'NX')", $script); $this->assertStringContainsString('if not permanent then', $script); $this->assertStringContainsString((string) StoreContext::MAX_EXPIRY, $script); @@ -118,8 +110,8 @@ public function testAddWithoutTtlUsesPermanentLuaBranch(): void $this->assertSame(0, $args[1]); return true; - }) - ->andReturn(true); + })) + ->returns(true); $redis = $this->createStore($connection, tagMode: 'any'); diff --git a/tests/Cache/Redis/Operations/AnyTag/DecrementTest.php b/tests/Cache/Redis/Operations/AnyTag/DecrementTest.php index 7297449b6d..087ef28525 100644 --- a/tests/Cache/Redis/Operations/AnyTag/DecrementTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/DecrementTest.php @@ -6,6 +6,7 @@ use Hypervel\Cache\Redis\Support\StoreContext; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; +use JMac\Testing\Matching\Argument; /** * Tests for the Decrement operation (union tags). @@ -16,17 +17,16 @@ public function testDecrementWithTagsReturnsNewValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args) { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args) { $this->assertStringContainsString('DECRBY', $script); $this->assertStringContainsString('TTL', $script); $this->assertStringContainsString((string) StoreContext::MAX_EXPIRY, $script); $this->assertCount(2, $keys); return true; - }) - ->andReturn(5); // New value after decrement + })) + ->returns(5); // New value after decrement $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -36,53 +36,53 @@ public function testDecrementWithTagsReturnsNewValue(): void public function testDecrementWithTagsUpdatesMetadataAfterAClusterCounterSucceeds(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); - - $connection->expects('multi')->twice()->andReturnSelf(); - $connection->expects('decrBy')->with('prefix:counter', 5)->andReturnSelf(); - $connection->expects('ttl')->with('prefix:counter')->andReturnSelf(); - $connection->expects('exec')->twice()->andReturn([5, -1], []); - $connection->expects('smembers')->with('prefix:counter:_any:tags')->andReturn([]); - $connection->expects('del')->with('prefix:counter:_any:tags')->andReturnSelf(); - $connection->expects('sadd')->with('prefix:counter:_any:tags', 'stats')->andReturnSelf(); - $connection->expects('hSet') + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); + + $client->expects('multi')->times(2)->returns($client); + $client->expects('decrBy')->with('prefix:counter', 5)->returns($client); + $client->expects('ttl')->with('prefix:counter')->returns($client); + $client->expects('exec')->times(2)->returns([5, -1], []); + $client->expects('smembers')->with('prefix:counter:_any:tags')->returns([]); + $client->expects('del')->with('prefix:counter:_any:tags')->returns($client); + $client->expects('sadd')->with('prefix:counter:_any:tags', 'stats')->returns($client); + $client->expects('hSet') ->with('prefix:_any:tag:stats:entries', 'counter', StoreContext::TAG_FIELD_VALUE) - ->andReturn(1); - $connection->expects('zadd') + ->returns(1); + $client->expects('zadd') ->with('prefix:_any:tag:registry', ['GT'], StoreContext::MAX_EXPIRY, 'stats') - ->andReturn(1); + ->returns(1); $this->assertSame(5, $redis->anyTagOps()->decrement()->execute('counter', 5, ['stats'])); } public function testDecrementWithTagsReturnsFalseWithoutMetadataWhenClusterTransactionFails(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); - $connection->expects('multi')->andReturnSelf(); - $connection->expects('decrBy')->with('prefix:counter', 5)->andReturnSelf(); - $connection->expects('ttl')->with('prefix:counter')->andReturnSelf(); - $connection->expects('exec')->andReturnFalse(); - $connection->shouldNotReceive('smembers'); - $connection->shouldNotReceive('sadd'); - $connection->shouldNotReceive('hSet'); - $connection->shouldNotReceive('zadd'); + $client->expects('multi')->returns($client); + $client->expects('decrBy')->with('prefix:counter', 5)->returns($client); + $client->expects('ttl')->with('prefix:counter')->returns($client); + $client->expects('exec')->returns(false); + $client->expects('smembers')->never(); + $client->expects('sadd')->never(); + $client->expects('hSet')->never(); + $client->expects('zadd')->never(); $this->assertFalse($redis->anyTagOps()->decrement()->execute('counter', 5, ['stats'])); } public function testDecrementWithTagsReturnsFalseWithoutMetadataWhenClusterCounterFails(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); - - $connection->expects('multi')->andReturnSelf(); - $connection->expects('decrBy')->with('prefix:counter', 5)->andReturnSelf(); - $connection->expects('ttl')->with('prefix:counter')->andReturnSelf(); - $connection->expects('exec')->andReturn([false, -1]); - $connection->shouldNotReceive('smembers'); - $connection->shouldNotReceive('sadd'); - $connection->shouldNotReceive('hSet'); - $connection->shouldNotReceive('zadd'); + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); + + $client->expects('multi')->returns($client); + $client->expects('decrBy')->with('prefix:counter', 5)->returns($client); + $client->expects('ttl')->with('prefix:counter')->returns($client); + $client->expects('exec')->returns([false, -1]); + $client->expects('smembers')->never(); + $client->expects('sadd')->never(); + $client->expects('hSet')->never(); + $client->expects('zadd')->never(); $this->assertFalse($redis->anyTagOps()->decrement()->execute('counter', 5, ['stats'])); } diff --git a/tests/Cache/Redis/Operations/AnyTag/FlushTest.php b/tests/Cache/Redis/Operations/AnyTag/FlushTest.php index b426997569..a33d34a43d 100644 --- a/tests/Cache/Redis/Operations/AnyTag/FlushTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/FlushTest.php @@ -10,7 +10,8 @@ use Hypervel\Cache\Redis\Operations\AnyTag\RemoveEmptyTags; use Hypervel\Cache\Redis\Support\StoreContext; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; /** * Tests for the Flush operation (union tags). @@ -22,21 +23,20 @@ public function testFlushDeletesCacheEntriesReverseIndexesAndScannedFields(): vo $connection = $this->mockConnection(); // Mock GetTaggedKeys to return cache keys - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->shouldReceive('execute') - ->once() + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute') ->with('users') - ->andReturn($this->arrayToGenerator(['key1', 'key2'])); + ->returns($this->arrayToGenerator(['key1', 'key2'])); $connection->expects('evalWithShaCache') ->with( - m::type('string'), + Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key2:_any:tags', 'prefix:key1', 'prefix:key2'], [2, 'key1', 'key2'], - )->andReturn(1)->ordered(); + )->returns(1)->ordered(); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) - ->andReturn([1, 1])->ordered(); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) + ->returns([1, 1])->ordered(); $store = $this->createStore($connection); $store->setTagMode('any'); @@ -50,31 +50,29 @@ public function testFlushWithMultipleTagsOnlyRemovesKeysFromTheirOwnTag(): void { $connection = $this->mockConnection(); - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->shouldReceive('execute') - ->once() + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute') ->with('users') - ->andReturn($this->arrayToGenerator(['shared_key', 'user_only'])); - $getTaggedKeys->shouldReceive('execute') - ->once() + ->returns($this->arrayToGenerator(['shared_key', 'user_only'])); + $getTaggedKeys->expects('execute') ->with('posts') - ->andReturn($this->arrayToGenerator(['shared_key', 'post_only'])); + ->returns($this->arrayToGenerator(['shared_key', 'post_only'])); $connection->expects('evalWithShaCache') ->with( - m::type('string'), + Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:shared_key:_any:tags', 'prefix:user_only:_any:tags', 'prefix:shared_key', 'prefix:user_only'], [2, 'shared_key', 'user_only'], - )->andReturn(1)->ordered(); + )->returns(1)->ordered(); $connection->expects('evalWithShaCache') ->with( - m::type('string'), + Argument::type('string'), ['prefix:_any:tag:posts:entries', 'prefix:shared_key:_any:tags', 'prefix:post_only:_any:tags', 'prefix:shared_key', 'prefix:post_only'], [2, 'shared_key', 'post_only'], - )->andReturn(1)->ordered(); + )->returns(1)->ordered(); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries', 'prefix:_any:tag:posts:entries'], ['users', 'posts']) - ->andReturn([2, 2])->ordered(); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries', 'prefix:_any:tag:posts:entries'], ['users', 'posts']) + ->returns([2, 2])->ordered(); $store = $this->createStore($connection); $store->setTagMode('any'); @@ -89,16 +87,15 @@ public function testFlushWithNoEntriesChecksForEmptyTags(): void $connection = $this->mockConnection(); // Mock GetTaggedKeys to return empty - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->shouldReceive('execute') - ->once() + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute') ->with('users') - ->andReturn($this->arrayToGenerator([])); + ->returns($this->arrayToGenerator([])); - $connection->shouldNotReceive('del'); + $connection->client()->expects('del')->never(); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) - ->andReturn([1, 1]); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) + ->returns([1, 1]); $store = $this->createStore($connection); $store->setTagMode('any'); @@ -111,9 +108,9 @@ public function testFlushWithNoEntriesChecksForEmptyTags(): void public function testFlushWithNoTagsDoesNotSendCommands(): void { $connection = $this->mockConnection(); - $connection->shouldNotReceive('evalWithShaCache'); - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->shouldNotReceive('execute'); + $connection->expects('evalWithShaCache')->never(); + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute')->never(); $store = $this->createStore($connection); $operation = new Flush($store->getContext(), $getTaggedKeys, new RemoveEmptyTags($store->getContext())); @@ -124,18 +121,17 @@ public function testFlushUsesCorrectPrefix(): void { $connection = $this->mockConnection(); - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->shouldReceive('execute') - ->once() + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute') ->with('users') - ->andReturn($this->arrayToGenerator(['mykey'])); + ->returns($this->arrayToGenerator(['mykey'])); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['custom_prefix:_any:tag:users:entries', 'custom_prefix:mykey:_any:tags', 'custom_prefix:mykey'], [1, 'mykey']) - ->andReturn(1)->ordered(); + ->with(Argument::type('string'), ['custom_prefix:_any:tag:users:entries', 'custom_prefix:mykey:_any:tags', 'custom_prefix:mykey'], [1, 'mykey']) + ->returns(1)->ordered(); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['custom_prefix:_any:tag:registry', 'custom_prefix:_any:tag:users:entries'], ['users']) - ->andReturn([1, 1])->ordered(); + ->with(Argument::type('string'), ['custom_prefix:_any:tag:registry', 'custom_prefix:_any:tag:users:entries'], ['users']) + ->returns([1, 1])->ordered(); $store = $this->createStore($connection, 'custom_prefix:'); $store->setTagMode('any'); @@ -147,69 +143,83 @@ public function testFlushUsesCorrectPrefix(): void public function testFlushClusterModeUsesSequentialCommands(): void { - [$store, , $connection] = $this->createClusterStore(tagMode: 'any'); + [$store, $client] = $this->createClusterStore(tagMode: 'any'); - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->shouldReceive('execute') - ->once() + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute') ->with('users') - ->andReturn($this->arrayToGenerator(['key1', 'key2'])); + ->returns($this->arrayToGenerator(['key1', 'key2'])); - // Cluster mode: NO pipeline calls - $connection->shouldNotReceive('pipeline'); - - $connection->expects('hdel') + $cleanup = []; + $client->expects('hdel') ->with('prefix:_any:tag:users:entries', 'key1', 'key2') - ->andReturn(2)->ordered(); + ->resolves(function () use (&$cleanup): int { + $cleanup[] = 'hdel'; + + return 2; + }); // Sequential del for reverse indexes - $connection->shouldReceive('del') - ->once() + $client->expects('del') ->with('prefix:key1:_any:tags', 'prefix:key2:_any:tags') - ->andReturn(2)->ordered(); + ->resolves(function () use (&$cleanup): int { + $cleanup[] = 'del'; + + return 2; + }); // Sequential unlink for cache keys - $connection->shouldReceive('unlink') - ->once() + $client->expects('unlink') ->with('prefix:key1', 'prefix:key2') - ->andReturn(2)->ordered(); + ->resolves(function () use (&$cleanup): int { + $cleanup[] = 'unlink'; + + return 2; + }); + + $client->expects('hlen')->times(2) + ->with('prefix:_any:tag:users:entries') + ->resolves(function () use (&$cleanup): int { + $cleanup[] = 'hlen'; - $connection->expects('hlen')->with('prefix:_any:tag:users:entries')->andReturn(0)->ordered(); + return 0; + }); // Sequential zrem for registry - $connection->shouldReceive('zrem') - ->once() + $client->expects('zrem') ->with('prefix:_any:tag:registry', 'users') - ->andReturn(1)->ordered(); - $connection->expects('hlen')->with('prefix:_any:tag:users:entries')->andReturn(0)->ordered(); + ->resolves(function () use (&$cleanup): int { + $cleanup[] = 'zrem'; + + return 1; + }); $operation = new Flush($store->getContext(), $getTaggedKeys, new RemoveEmptyTags($store->getContext())); $result = $operation->execute(['users']); $this->assertTrue($result); + $this->assertSame(['hdel', 'del', 'unlink', 'hlen', 'zrem', 'hlen'], $cleanup); } public function testFlushClusterModeWithMultipleTags(): void { - [$store, , $connection] = $this->createClusterStore(tagMode: 'any'); + [$store, $client] = $this->createClusterStore(tagMode: 'any'); - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->shouldReceive('execute') - ->once() + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute') ->with('users') - ->andReturn($this->arrayToGenerator(['user_key', 'shared_key'])); - $getTaggedKeys->shouldReceive('execute') - ->once() + ->returns($this->arrayToGenerator(['user_key', 'shared_key'])); + $getTaggedKeys->expects('execute') ->with('posts') - ->andReturn($this->arrayToGenerator(['shared_key', 'post_key'])); + ->returns($this->arrayToGenerator(['shared_key', 'post_key'])); // Each tag's chunk only removes fields from that tag's hash. - $connection->expects('hdel')->with('prefix:_any:tag:users:entries', 'user_key', 'shared_key')->andReturn(2); - $connection->expects('hdel')->with('prefix:_any:tag:posts:entries', 'shared_key', 'post_key')->andReturn(2); - $connection->expects('hlen')->with('prefix:_any:tag:users:entries')->twice()->andReturn(0); - $connection->expects('hlen')->with('prefix:_any:tag:posts:entries')->twice()->andReturn(0); - $connection->shouldReceive('del')->andReturn(1); - $connection->shouldReceive('unlink')->andReturn(1); - $connection->shouldReceive('zrem')->andReturn(1); + $client->expects('hdel')->with('prefix:_any:tag:users:entries', 'user_key', 'shared_key')->returns(2); + $client->expects('hdel')->with('prefix:_any:tag:posts:entries', 'shared_key', 'post_key')->returns(2); + $client->expects('hlen')->with('prefix:_any:tag:users:entries')->times(2)->returns(0); + $client->expects('hlen')->with('prefix:_any:tag:posts:entries')->times(2)->returns(0); + $client->allows('del')->returns(1); + $client->allows('unlink')->returns(1); + $client->allows('zrem')->returns(1); $operation = new Flush($store->getContext(), $getTaggedKeys, new RemoveEmptyTags($store->getContext())); $result = $operation->execute(['users', 'posts']); @@ -221,19 +231,19 @@ public function testFlushViaRedisStoreMethod(): void $connection = $this->mockConnection(); // Mock hlen/hkeys for GetTaggedKeys internal calls - $connection->shouldReceive('hlen') + $connection->client()->allows('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(1); - $connection->shouldReceive('hkeys') + ->returns(1); + $connection->client()->allows('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['mykey']); + ->returns(['mykey']); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:users:entries', 'prefix:mykey:_any:tags', 'prefix:mykey'], [1, 'mykey']) - ->andReturn(1); + ->with(Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:mykey:_any:tags', 'prefix:mykey'], [1, 'mykey']) + ->returns(1); $connection->expects('evalWithShaCache') - ->with(m::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) - ->andReturn([1, 1]); + ->with(Argument::type('string'), ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], ['users']) + ->returns([1, 1]); $store = $this->createStore($connection); $store->setTagMode('any'); @@ -243,12 +253,12 @@ public function testFlushViaRedisStoreMethod(): void public function testClusterFlushPreservesRegistrationWhenTheHashWasRepopulated(): void { - [$store, , $connection] = $this->createClusterStore(tagMode: 'any'); - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->expects('execute')->with('users')->andReturn($this->arrayToGenerator([])); + [$store, $client] = $this->createClusterStore(tagMode: 'any'); + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute')->with('users')->returns($this->arrayToGenerator([])); - $connection->expects('hlen')->with('prefix:_any:tag:users:entries')->andReturn(1); - $connection->shouldNotReceive('zrem'); + $client->expects('hlen')->with('prefix:_any:tag:users:entries')->returns(1); + $client->expects('zrem')->never(); $operation = new Flush($store->getContext(), $getTaggedKeys, new RemoveEmptyTags($store->getContext())); @@ -257,18 +267,38 @@ public function testClusterFlushPreservesRegistrationWhenTheHashWasRepopulated() public function testClusterFlushRestoresRegistrationWhenAWriterRacesWithDeregistration(): void { - [$store, , $connection] = $this->createClusterStore(tagMode: 'any'); - $getTaggedKeys = m::mock(GetTaggedKeys::class); - $getTaggedKeys->expects('execute')->with('users')->andReturn($this->arrayToGenerator([])); + [$store, $client] = $this->createClusterStore(tagMode: 'any'); + $getTaggedKeys = Double::for(GetTaggedKeys::class); + $getTaggedKeys->expects('execute')->with('users')->returns($this->arrayToGenerator([])); + + $cleanup = []; + $lengths = [0, 1]; + $client->expects('hlen')->times(2) + ->with('prefix:_any:tag:users:entries') + ->resolves(function () use (&$cleanup, &$lengths): int { + $cleanup[] = 'hlen'; + + return array_shift($lengths); + }); + $client->expects('zrem') + ->with('prefix:_any:tag:registry', 'users') + ->resolves(function () use (&$cleanup): int { + $cleanup[] = 'zrem'; + + return 1; + }); + $client->expects('zadd') + ->with('prefix:_any:tag:registry', ['NX'], StoreContext::MAX_EXPIRY, 'users') + ->resolves(function () use (&$cleanup): int { + $cleanup[] = 'zadd'; - $connection->expects('hlen')->with('prefix:_any:tag:users:entries')->andReturn(0)->ordered(); - $connection->expects('zrem')->with('prefix:_any:tag:registry', 'users')->andReturn(1)->ordered(); - $connection->expects('hlen')->with('prefix:_any:tag:users:entries')->andReturn(1)->ordered(); - $connection->expects('zadd')->with('prefix:_any:tag:registry', ['NX'], StoreContext::MAX_EXPIRY, 'users')->andReturn(1)->ordered(); + return 1; + }); $operation = new Flush($store->getContext(), $getTaggedKeys, new RemoveEmptyTags($store->getContext())); $this->assertTrue($operation->execute(['users'])); + $this->assertSame(['hlen', 'zrem', 'hlen', 'zadd'], $cleanup); } /** diff --git a/tests/Cache/Redis/Operations/AnyTag/ForeverTest.php b/tests/Cache/Redis/Operations/AnyTag/ForeverTest.php index 1df9da4099..44663d5058 100644 --- a/tests/Cache/Redis/Operations/AnyTag/ForeverTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/ForeverTest.php @@ -6,6 +6,7 @@ use Hypervel\Cache\Redis\Support\StoreContext; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; +use JMac\Testing\Matching\Argument; /** * Tests for the Forever operation (union tags). @@ -16,9 +17,8 @@ public function testForeverWithTagsUsesLuaScript(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args) { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args) { // Forever uses SET (no TTL), HSET (no expiration), ZADD with max expiry $this->assertStringContainsString("redis.call('SET'", $script); $this->assertStringContainsString('HSET', $script); @@ -26,8 +26,8 @@ public function testForeverWithTagsUsesLuaScript(): void $this->assertCount(2, $keys); return true; - }) - ->andReturn(true); + })) + ->returns(true); $redis = $this->createStore($connection); $redis->setTagMode('any'); diff --git a/tests/Cache/Redis/Operations/AnyTag/GetTagItemsTest.php b/tests/Cache/Redis/Operations/AnyTag/GetTagItemsTest.php index d3b2a6c774..e8202b0a13 100644 --- a/tests/Cache/Redis/Operations/AnyTag/GetTagItemsTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/GetTagItemsTest.php @@ -16,20 +16,17 @@ public function testTagItemsReturnsKeyValuePairs(): void $connection = $this->mockConnection(); // GetTaggedKeys mock - $connection->shouldReceive('hlen') - ->once() + $connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(2); - $connection->shouldReceive('hkeys') - ->once() + ->returns(2); + $connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['foo', 'bar']); + ->returns(['foo', 'bar']); // MGET to fetch values - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with(['prefix:foo', 'prefix:bar']) - ->andReturn([serialize('value1'), serialize('value2')]); + ->returns([serialize('value1'), serialize('value2')]); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -42,20 +39,17 @@ public function testTagItemsSkipsNonExistentKeys(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('hlen') - ->once() + $connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(3); - $connection->shouldReceive('hkeys') - ->once() + ->returns(3); + $connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['foo', 'bar', 'baz']); + ->returns(['foo', 'bar', 'baz']); // bar doesn't exist (returns null) - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with(['prefix:foo', 'prefix:bar', 'prefix:baz']) - ->andReturn([serialize('value1'), null, serialize('value3')]); + ->returns([serialize('value1'), null, serialize('value3')]); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -69,34 +63,28 @@ public function testTagItemsDeduplicatesAcrossTags(): void $connection = $this->mockConnection(); // First tag 'users' has keys foo, bar - $connection->shouldReceive('hlen') - ->once() + $connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(2); - $connection->shouldReceive('hkeys') - ->once() + ->returns(2); + $connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['foo', 'bar']); + ->returns(['foo', 'bar']); // Second tag 'posts' has keys bar, baz (bar is duplicate) - $connection->shouldReceive('hlen') - ->once() + $connection->client()->expects('hlen') ->with('prefix:_any:tag:posts:entries') - ->andReturn(2); - $connection->shouldReceive('hkeys') - ->once() + ->returns(2); + $connection->client()->expects('hkeys') ->with('prefix:_any:tag:posts:entries') - ->andReturn(['bar', 'baz']); + ->returns(['bar', 'baz']); // MGET called twice (batches of keys from each tag) - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with(['prefix:foo', 'prefix:bar']) - ->andReturn([serialize('v1'), serialize('v2')]); - $connection->shouldReceive('mget') - ->once() + ->returns([serialize('v1'), serialize('v2')]); + $connection->client()->expects('mget') ->with(['prefix:baz']) // bar already seen, only baz - ->andReturn([serialize('v3')]); + ->returns([serialize('v3')]); $redis = $this->createStore($connection); $redis->setTagMode('any'); diff --git a/tests/Cache/Redis/Operations/AnyTag/GetTaggedKeysTest.php b/tests/Cache/Redis/Operations/AnyTag/GetTaggedKeysTest.php index 554552a6f8..c7b33700fe 100644 --- a/tests/Cache/Redis/Operations/AnyTag/GetTaggedKeysTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/GetTaggedKeysTest.php @@ -17,14 +17,12 @@ public function testGetTaggedKeysUsesHkeysForSmallHashes(): void $connection = $this->mockConnection(); // Small hash (below threshold) uses HKEYS - $connection->shouldReceive('hlen') - ->once() + $connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') - ->andReturn(5); - $connection->shouldReceive('hkeys') - ->once() + ->returns(5); + $connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') - ->andReturn(['key1', 'key2', 'key3']); + ->returns(['key1', 'key2', 'key3']); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -35,43 +33,34 @@ public function testGetTaggedKeysUsesHkeysForSmallHashes(): void public function testGetTaggedKeysUsesHscanForLargeHashes(): void { - $connection = $this->mockConnection(); - - // Large hash (above threshold of 1000) uses HSCAN - $connection->shouldReceive('hlen') - ->once() - ->with('prefix:_any:tag:users:entries') - ->andReturn(5000); - - // HSCAN returns key-value pairs, iterator updates by reference - $connection->shouldReceive('hscan') - ->once() - ->withArgs(function ($key, &$iterator, $pattern, $count) { - $this->assertNull($iterator); - $iterator = 0; // Done after first iteration - return true; - }) - ->andReturn(['key1' => '1', 'key2' => '1', 'key3' => '1']); + $tagKey = 'prefix:_any:tag:users:entries'; + $client = new FakeRedisClient( + hLenResults: [$tagKey => 5000], + hScanResults: [ + $tagKey => [['fields' => ['key1' => '1', 'key2' => '1', 'key3' => '1'], 'iterator' => 0]], + ], + ); + $store = $this->createStoreWithFakeClient($client, tagMode: 'any'); - $redis = $this->createStore($connection); - $redis->setTagMode('any'); - $keys = iterator_to_array($redis->anyTagOps()->getTaggedKeys()->execute('users')); + $keys = iterator_to_array($store->anyTagOps()->getTaggedKeys()->execute('users')); $this->assertSame(['key1', 'key2', 'key3'], $keys); + $this->assertSame([$tagKey], $client->getHLenCalls()); + $this->assertSame([ + ['key' => $tagKey, 'iterator' => null, 'pattern' => null, 'count' => 1000], + ], $client->getHScanCalls()); } public function testGetTaggedKeysReturnsEmptyForNonExistentTag(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('hlen') - ->once() + $connection->client()->expects('hlen') ->with('prefix:_any:tag:nonexistent:entries') - ->andReturn(0); - $connection->shouldReceive('hkeys') - ->once() + ->returns(0); + $connection->client()->expects('hkeys') ->with('prefix:_any:tag:nonexistent:entries') - ->andReturn([]); + ->returns([]); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -84,8 +73,7 @@ public function testGetTaggedKeysReturnsEmptyForNonExistentTag(): void * Verifies that HSCAN correctly handles multiple batches with per-batch connection checkout. * The iterator must be passed by reference correctly across withConnection() calls. * - * Uses FakeRedisClient instead of Mockery because Mockery doesn't properly propagate - * modifications to reference parameters (like &$iterator) back to the caller. + * A concrete fake preserves the scan cursor changes that generated doubles cannot return. */ public function testGetTaggedKeysHandlesMultipleHscanBatches(): void { @@ -114,7 +102,7 @@ public function testGetTaggedKeysHandlesMultipleHscanBatches(): void $this->assertSame(['key1', 'key2', 'key3', 'key4', 'key5'], $keys); // Verify all 3 HSCAN batches were called - $this->assertSame(3, $fakeClient->getHScanCallCount()); + $this->assertSame([null, 100, 200], array_column($fakeClient->getHScanCalls(), 'iterator')); } public function testGetTaggedKeysContinuesAfterAnEmptyNonterminalPage(): void diff --git a/tests/Cache/Redis/Operations/AnyTag/IncrementTest.php b/tests/Cache/Redis/Operations/AnyTag/IncrementTest.php index 9670c9f099..aba44eefec 100644 --- a/tests/Cache/Redis/Operations/AnyTag/IncrementTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/IncrementTest.php @@ -6,6 +6,7 @@ use Hypervel\Cache\Redis\Support\StoreContext; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; +use JMac\Testing\Matching\Argument; /** * Tests for the Increment operation (union tags). @@ -17,17 +18,16 @@ public function testIncrementWithTagsReturnsNewValue(): void $connection = $this->mockConnection(); // Lua script returns the incremented value - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args) { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args) { $this->assertStringContainsString('INCRBY', $script); $this->assertStringContainsString('TTL', $script); $this->assertStringContainsString((string) StoreContext::MAX_EXPIRY, $script); $this->assertCount(2, $keys); return true; - }) - ->andReturn(15); // New value after increment + })) + ->returns(15); // New value after increment $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -37,53 +37,53 @@ public function testIncrementWithTagsReturnsNewValue(): void public function testIncrementWithTagsUpdatesMetadataAfterAClusterCounterSucceeds(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); - - $connection->expects('multi')->twice()->andReturnSelf(); - $connection->expects('incrBy')->with('prefix:counter', 5)->andReturnSelf(); - $connection->expects('ttl')->with('prefix:counter')->andReturnSelf(); - $connection->expects('exec')->twice()->andReturn([15, -1], []); - $connection->expects('smembers')->with('prefix:counter:_any:tags')->andReturn([]); - $connection->expects('del')->with('prefix:counter:_any:tags')->andReturnSelf(); - $connection->expects('sadd')->with('prefix:counter:_any:tags', 'stats')->andReturnSelf(); - $connection->expects('hSet') + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); + + $client->expects('multi')->times(2)->returns($client); + $client->expects('incrBy')->with('prefix:counter', 5)->returns($client); + $client->expects('ttl')->with('prefix:counter')->returns($client); + $client->expects('exec')->times(2)->returns([15, -1], []); + $client->expects('smembers')->with('prefix:counter:_any:tags')->returns([]); + $client->expects('del')->with('prefix:counter:_any:tags')->returns($client); + $client->expects('sadd')->with('prefix:counter:_any:tags', 'stats')->returns($client); + $client->expects('hSet') ->with('prefix:_any:tag:stats:entries', 'counter', StoreContext::TAG_FIELD_VALUE) - ->andReturn(1); - $connection->expects('zadd') + ->returns(1); + $client->expects('zadd') ->with('prefix:_any:tag:registry', ['GT'], StoreContext::MAX_EXPIRY, 'stats') - ->andReturn(1); + ->returns(1); $this->assertSame(15, $redis->anyTagOps()->increment()->execute('counter', 5, ['stats'])); } public function testIncrementWithTagsReturnsFalseWithoutMetadataWhenClusterTransactionFails(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); - $connection->expects('multi')->andReturnSelf(); - $connection->expects('incrBy')->with('prefix:counter', 5)->andReturnSelf(); - $connection->expects('ttl')->with('prefix:counter')->andReturnSelf(); - $connection->expects('exec')->andReturnFalse(); - $connection->shouldNotReceive('smembers'); - $connection->shouldNotReceive('sadd'); - $connection->shouldNotReceive('hSet'); - $connection->shouldNotReceive('zadd'); + $client->expects('multi')->returns($client); + $client->expects('incrBy')->with('prefix:counter', 5)->returns($client); + $client->expects('ttl')->with('prefix:counter')->returns($client); + $client->expects('exec')->returns(false); + $client->expects('smembers')->never(); + $client->expects('sadd')->never(); + $client->expects('hSet')->never(); + $client->expects('zadd')->never(); $this->assertFalse($redis->anyTagOps()->increment()->execute('counter', 5, ['stats'])); } public function testIncrementWithTagsReturnsFalseWithoutMetadataWhenClusterCounterFails(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); - - $connection->expects('multi')->andReturnSelf(); - $connection->expects('incrBy')->with('prefix:counter', 5)->andReturnSelf(); - $connection->expects('ttl')->with('prefix:counter')->andReturnSelf(); - $connection->expects('exec')->andReturn([false, -1]); - $connection->shouldNotReceive('smembers'); - $connection->shouldNotReceive('sadd'); - $connection->shouldNotReceive('hSet'); - $connection->shouldNotReceive('zadd'); + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); + + $client->expects('multi')->returns($client); + $client->expects('incrBy')->with('prefix:counter', 5)->returns($client); + $client->expects('ttl')->with('prefix:counter')->returns($client); + $client->expects('exec')->returns([false, -1]); + $client->expects('smembers')->never(); + $client->expects('sadd')->never(); + $client->expects('hSet')->never(); + $client->expects('zadd')->never(); $this->assertFalse($redis->anyTagOps()->increment()->execute('counter', 5, ['stats'])); } diff --git a/tests/Cache/Redis/Operations/AnyTag/PruneTest.php b/tests/Cache/Redis/Operations/AnyTag/PruneTest.php index 24265e0ac2..929166b0af 100644 --- a/tests/Cache/Redis/Operations/AnyTag/PruneTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/PruneTest.php @@ -4,24 +4,27 @@ namespace Hypervel\Tests\Cache\Redis\Operations\AnyTag; +use Hypervel\Cache\Redis\Operations\AnyTag\RemoveEmptyTags; use Hypervel\Cache\Redis\Support\StoreContext; +use Hypervel\Support\ClassInvoker; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; -use Mockery as m; +use Hypervel\Tests\Redis\Fixtures\FakeRedisClusterClient; +use Hypervel\Tests\Redis\Fixtures\PhpRedisClusterConnectionStub; +use JMac\Testing\Matching\Argument; +use RedisCluster; class PruneTest extends RedisCacheTestCase { public function testPruneReturnsEmptyStatsWhenNoActiveTagsRemain(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('zRemRangeByScore') - ->once() - ->with('prefix:_any:tag:registry', '-inf', m::type('string')) - ->andReturn(2); - $connection->shouldReceive('zRange') - ->once() + $connection->client()->expects('zRemRangeByScore') + ->with('prefix:_any:tag:registry', '-inf', Argument::type('string')) + ->returns(2); + $connection->client()->expects('zRange') ->with('prefix:_any:tag:registry', 0, -1) - ->andReturn([]); + ->returns([]); $store = $this->createStore($connection); $store->setTagMode('any'); @@ -38,201 +41,157 @@ public function testPruneReturnsEmptyStatsWhenNoActiveTagsRemain(): void public function testPruneRemovesOrphansAtomicallyInBoundedPages(): void { - $connection = $this->mockConnection(); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zRange')->once()->andReturn(['users']); - $connection->shouldReceive('hScan') - ->once() - ->with('prefix:_any:tag:users:entries', m::any(), '*', 37) - ->andReturnUsing(function ($tagHash, &$iterator): array { - $this->assertNull($iterator); - $iterator = 0; - - return ['key1' => '1', 'key2' => '1', 'key3' => '1']; - }); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->with( - m::on(fn (string $script): bool => str_contains($script, "redis.call('EXISTS', KEYS[i])")), - [ - 'prefix:_any:tag:users:entries', - 'prefix:key1', - 'prefix:key2', - 'prefix:key3', - ], - ['key1', 'key2', 'key3'], - ) - ->andReturn(1); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->with( - m::on(fn (string $script): bool => str_contains($script, "redis.call('ZREM', KEYS[1], ARGV[i - 1])")), - ['prefix:_any:tag:registry', 'prefix:_any:tag:users:entries'], - ['users'], - ) - ->andReturn([0, 0]); + $tagKey = 'prefix:_any:tag:users:entries'; + $client = new FakeRedisClient( + hScanResults: [$tagKey => [['fields' => ['key1' => '1', 'key2' => '1', 'key3' => '1'], 'iterator' => 0]]], + zRangeResults: ['prefix:_any:tag:registry' => ['users']], + evalShaResults: [1, [0, 0]], + ); + $store = $this->createStoreWithFakeClient($client, tagMode: 'any'); + $operation = $store->anyTagOps()->prune(); - $store = $this->createStore($connection); - $store->setTagMode('any'); - $result = $store->anyTagOps()->prune()->execute(37); + $result = $operation->execute(37); + $this->assertCount(1, $client->getZRemRangeByScoreCalls()); + $this->assertSame(1, $client->getZRangeCallCount()); $this->assertSame(1, $result['hashes_scanned']); $this->assertSame(3, $result['fields_checked']); $this->assertSame(1, $result['orphans_removed']); $this->assertSame(0, $result['empty_hashes_deleted']); $this->assertSame(0, $result['orphaned_tags_removed']); + $this->assertSame([ + ['key' => $tagKey, 'iterator' => null, 'pattern' => '*', 'count' => 37], + ], $client->getHScanCalls()); + $calls = $client->getEvalShaCalls(); + $this->assertCount(2, $calls); + $this->assertSame([$tagKey, 'prefix:key1', 'prefix:key2', 'prefix:key3', 'key1', 'key2', 'key3'], $calls[0]['args']); + $this->assertSame(4, $calls[0]['num_keys']); + $this->assertSame(['prefix:_any:tag:registry', $tagKey, 'users'], $calls[1]['args']); + $this->assertSame(2, $calls[1]['num_keys']); + $script = (new ClassInvoker($operation))->removeOrphanedFieldsScript(); + $this->assertStringContainsString("redis.call('EXISTS', KEYS[i])", $script); + $this->assertSame(sha1($script), $calls[0]['sha']); + $script = (new ClassInvoker(new RemoveEmptyTags($store->getContext())))->removeEmptyTagsScript(); + $this->assertStringContainsString("redis.call('ZREM', KEYS[1], ARGV[i - 1])", $script); + $this->assertSame(sha1($script), $calls[1]['sha']); } public function testPruneRemovesAnEmptyHashFromTheRegistry(): void { - $connection = $this->mockConnection(); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zRange')->once()->andReturn(['forever-tag']); - $connection->shouldReceive('hScan') - ->once() - ->andReturnUsing(function ($tagHash, &$iterator): array { - $iterator = 0; - - return ['orphan' => '1']; - }); - $connection->shouldReceive('evalWithShaCache')->once()->andReturn(1); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->with( - m::type('string'), - ['prefix:_any:tag:registry', 'prefix:_any:tag:forever-tag:entries'], - ['forever-tag'], - ) - ->andReturn([1, 1]); - $connection->shouldNotReceive('del'); - - $store = $this->createStore($connection); - $store->setTagMode('any'); + $client = new FakeRedisClient( + hScanResults: [ + 'prefix:_any:tag:forever-tag:entries' => [['fields' => ['orphan' => '1'], 'iterator' => 0]], + ], + zRangeResults: ['prefix:_any:tag:registry' => ['forever-tag']], + evalShaResults: [1, [1, 1]], + ); + $store = $this->createStoreWithFakeClient($client, tagMode: 'any'); $result = $store->anyTagOps()->prune()->execute(); + $this->assertCount(1, $client->getZRemRangeByScoreCalls()); + $this->assertSame(1, $client->getZRangeCallCount()); $this->assertSame(1, $result['orphans_removed']); $this->assertSame(1, $result['empty_hashes_deleted']); $this->assertSame(1, $result['orphaned_tags_removed']); + $this->assertCount(1, $client->getHScanCalls()); + $calls = $client->getEvalShaCalls(); + $this->assertCount(2, $calls); + $this->assertSame(['prefix:_any:tag:registry', 'prefix:_any:tag:forever-tag:entries', 'forever-tag'], $calls[1]['args']); + $this->assertSame(2, $calls[1]['num_keys']); + $this->assertSame([], $client->getDelCalls()); } public function testClusterPruneBatchesOrphansThatRemainRemoved(): void { - [$store, , $connection] = $this->createClusterStore(tagMode: 'any'); - $connection->shouldNotReceive('pipeline'); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zRange')->once()->andReturn(['users']); - $connection->shouldReceive('hScan') - ->once() - ->andReturnUsing(function ($tagHash, &$iterator): array { - $iterator = 0; - - return ['live' => '1', 'orphan1' => '1', 'orphan2' => '1']; - }); - $connection->shouldReceive('exists')->once()->with('prefix:live')->andReturn(1); - $connection->shouldReceive('exists')->twice()->with('prefix:orphan1')->andReturn(0); - $connection->shouldReceive('exists')->twice()->with('prefix:orphan2')->andReturn(0); - $connection->shouldReceive('hDel') - ->once() - ->with('prefix:_any:tag:users:entries', 'orphan1', 'orphan2') - ->andReturn(2); - $connection->shouldReceive('hLen')->once()->andReturn(1); + $client = new PruneRedisClusterClient( + ['live' => '1', 'orphan1' => '1', 'orphan2' => '1'], + ['prefix:live' => [1], 'prefix:orphan1' => [0, 0], 'prefix:orphan2' => [0, 0]], + removed: 2, + ); + $connection = (new PhpRedisClusterConnectionStub)->setActiveConnection($client); + $store = $this->createStore($connection, tagMode: 'any'); $result = $store->anyTagOps()->prune()->execute(); $this->assertSame(3, $result['fields_checked']); $this->assertSame(2, $result['orphans_removed']); + $this->assertSame([ + ['zRemRangeByScore', 'prefix:_any:tag:registry'], + ['zRange', 'prefix:_any:tag:registry'], + ['hscan', 'prefix:_any:tag:users:entries', null, '*', 1000], + ['exists', 'prefix:live'], + ['exists', 'prefix:orphan1'], + ['exists', 'prefix:orphan2'], + ['hDel', 'prefix:_any:tag:users:entries', 'orphan1', 'orphan2'], + ['exists', 'prefix:orphan1'], + ['exists', 'prefix:orphan2'], + ['hLen', 'prefix:_any:tag:users:entries'], + ], $client->commands); } public function testClusterPruneRepairsAFieldOnlyWhenItIsStillMissing(): void { - [$store, , $connection] = $this->createClusterStore(tagMode: 'any'); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zRange')->once()->andReturn(['users']); - $connection->shouldReceive('hScan') - ->once() - ->andReturnUsing(function ($tagHash, &$iterator): array { - $iterator = 0; - - return ['raced' => '1']; - }); - $connection->shouldReceive('exists') - ->twice() - ->with('prefix:raced') - ->andReturn(0, 1); - $connection->shouldReceive('hDel')->once()->andReturn(1); - $connection->shouldReceive('sismember') - ->once() - ->with('prefix:raced:_any:tags', 'users') - ->andReturn(true); - $connection->shouldReceive('hsetnx') - ->once() - ->with('prefix:_any:tag:users:entries', 'raced', StoreContext::TAG_FIELD_VALUE) - ->andReturn(false); - $connection->shouldReceive('hLen')->once()->andReturn(1); + $client = new PruneRedisClusterClient(['raced' => '1'], ['prefix:raced' => [0, 1]], removed: 1); + $connection = (new PhpRedisClusterConnectionStub)->setActiveConnection($client); + $store = $this->createStore($connection, tagMode: 'any'); $result = $store->anyTagOps()->prune()->execute(); $this->assertSame(0, $result['orphans_removed']); + $this->assertSame([ + ['zRemRangeByScore', 'prefix:_any:tag:registry'], + ['zRange', 'prefix:_any:tag:registry'], + ['hscan', 'prefix:_any:tag:users:entries', null, '*', 1000], + ['exists', 'prefix:raced'], + ['hDel', 'prefix:_any:tag:users:entries', 'raced'], + ['exists', 'prefix:raced'], + ['sismember', 'prefix:raced:_any:tags', 'users'], + ['hsetnx', 'prefix:_any:tag:users:entries', 'raced', StoreContext::TAG_FIELD_VALUE], + ['hLen', 'prefix:_any:tag:users:entries'], + ], $client->commands); } public function testClusterPruneRepairsAFieldAfterConcurrentRemovalReturnsZero(): void { - [$store, , $connection] = $this->createClusterStore(tagMode: 'any'); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zRange')->once()->andReturn(['users']); - $connection->shouldReceive('hScan') - ->once() - ->andReturnUsing(function ($tagHash, &$iterator): array { - $iterator = 0; - - return ['raced' => '1']; - }); - $connection->shouldReceive('exists') - ->twice() - ->with('prefix:raced') - ->andReturn(0, 1); - $connection->shouldReceive('hDel')->once()->andReturn(0); - $connection->shouldReceive('sismember') - ->once() - ->with('prefix:raced:_any:tags', 'users') - ->andReturn(true); - $connection->shouldReceive('hsetnx') - ->once() - ->with('prefix:_any:tag:users:entries', 'raced', StoreContext::TAG_FIELD_VALUE) - ->andReturn(false); - $connection->shouldReceive('hLen')->once()->andReturn(1); + $client = new PruneRedisClusterClient(['raced' => '1'], ['prefix:raced' => [0, 1]], removed: 0); + $connection = (new PhpRedisClusterConnectionStub)->setActiveConnection($client); + $store = $this->createStore($connection, tagMode: 'any'); $result = $store->anyTagOps()->prune()->execute(); $this->assertSame(0, $result['orphans_removed']); + $this->assertSame([ + ['zRemRangeByScore', 'prefix:_any:tag:registry'], + ['zRange', 'prefix:_any:tag:registry'], + ['hscan', 'prefix:_any:tag:users:entries', null, '*', 1000], + ['exists', 'prefix:raced'], + ['hDel', 'prefix:_any:tag:users:entries', 'raced'], + ['exists', 'prefix:raced'], + ['sismember', 'prefix:raced:_any:tags', 'users'], + ['hsetnx', 'prefix:_any:tag:users:entries', 'raced', StoreContext::TAG_FIELD_VALUE], + ['hLen', 'prefix:_any:tag:users:entries'], + ], $client->commands); } public function testClusterPruneRepairsARegistryEntryWithoutOverwritingAWriterScore(): void { - [$store, , $connection] = $this->createClusterStore(tagMode: 'any'); - $connection->shouldReceive('zRemRangeByScore')->once()->andReturn(0); - $connection->shouldReceive('zRange')->once()->andReturn(['users']); - $connection->shouldReceive('hScan') - ->once() - ->andReturnUsing(function ($tagHash, &$iterator): array { - $iterator = 0; - - return []; - }); - $connection->shouldReceive('hLen')->twice()->andReturn(0, 1); - $connection->shouldReceive('zrem') - ->once() - ->with('prefix:_any:tag:registry', 'users') - ->andReturn(1); - $connection->shouldReceive('zadd') - ->once() - ->with('prefix:_any:tag:registry', ['NX'], StoreContext::MAX_EXPIRY, 'users') - ->andReturn(0); + $client = new PruneRedisClusterClient([], [], removed: 0, lengths: [0, 1]); + $connection = (new PhpRedisClusterConnectionStub)->setActiveConnection($client); + $store = $this->createStore($connection, tagMode: 'any'); $result = $store->anyTagOps()->prune()->execute(); $this->assertSame(0, $result['empty_hashes_deleted']); $this->assertSame(0, $result['orphaned_tags_removed']); + $this->assertSame([ + ['zRemRangeByScore', 'prefix:_any:tag:registry'], + ['zRange', 'prefix:_any:tag:registry'], + ['hscan', 'prefix:_any:tag:users:entries', null, '*', 1000], + ['hLen', 'prefix:_any:tag:users:entries'], + ['zrem', 'prefix:_any:tag:registry', 'users'], + ['hLen', 'prefix:_any:tag:users:entries'], + ['zadd', 'prefix:_any:tag:registry', ['NX'], StoreContext::MAX_EXPIRY, 'users'], + ], $client->commands); } public function testPruneContinuesAfterEmptyAndNonterminalHashPages(): void @@ -262,3 +221,120 @@ public function testPruneContinuesAfterEmptyAndNonterminalHashPages(): void $this->assertSame(1, $result['orphans_removed']); } } + +/** + * Simulate concurrent hash changes while preserving HSCAN's reference parameter. + */ +class PruneRedisClusterClient extends FakeRedisClusterClient +{ + public array $commands = []; + + /** + * Configure hash fields and successive existence and length checks. + */ + public function __construct(private array $fields, private array $existence, private int $removed, private array $lengths = [1]) + { + parent::__construct(); + } + + /** + * Return the hash fields and finish scanning. + */ + public function hscan(string $key, int|string|null &$iterator, ?string $pattern = null, int $count = 0): array|bool + { + $this->commands[] = ['hscan', $key, $iterator, $pattern, $count]; + $iterator = 0; + + return $this->fields; + } + + /** + * Return the next existence result. + */ + public function exists(mixed $key, mixed ...$other_keys): RedisCluster|int|bool + { + $this->commands[] = ['exists', $key, ...$other_keys]; + + return array_shift($this->existence[$key]); + } + + /** + * Record the batched field removal. + */ + public function hDel(string $key, string $field, string ...$other_fields): RedisCluster|int|false + { + $this->commands[] = ['hDel', $key, $field, ...$other_fields]; + + return $this->removed; + } + + /** + * Retain the raced value's tag in its reverse index. + */ + public function sismember(string $key, mixed $value): RedisCluster|bool + { + $this->commands[] = ['sismember', $key, $value]; + + return true; + } + + /** + * Record the repair without replacing the writer's field. + */ + public function hsetnx(string $key, string $member, mixed $value): RedisCluster|bool + { + $this->commands[] = ['hsetnx', $key, $member, $value]; + + return false; + } + + /** + * Return the next hash length. + */ + public function hLen(string $key): RedisCluster|int|false + { + $this->commands[] = ['hLen', $key]; + + return array_shift($this->lengths); + } + + /** + * Record tag deregistration. + */ + public function zrem(mixed $key, mixed $member, mixed ...$other_members): RedisCluster|int|false + { + $this->commands[] = ['zrem', $key, $member, ...$other_members]; + + return 1; + } + + /** + * Record registry repair without replacing the writer's score. + */ + public function zadd(string $key, array|float $score_or_options, mixed ...$more_scores_and_mems): RedisCluster|int|float|false + { + $this->commands[] = ['zadd', $key, $score_or_options, ...$more_scores_and_mems]; + + return 0; + } + + /** + * Keep the configured tag active. + */ + public function zRemRangeByScore(string $key, string $min, string $max): RedisCluster|int|false + { + $this->commands[] = ['zRemRangeByScore', $key]; + + return 0; + } + + /** + * Return the active tag. + */ + public function zRange(string $key, mixed $start, mixed $end, array|bool|null $options = null): RedisCluster|array|bool + { + $this->commands[] = ['zRange', $key]; + + return ['users']; + } +} diff --git a/tests/Cache/Redis/Operations/AnyTag/PutManyTest.php b/tests/Cache/Redis/Operations/AnyTag/PutManyTest.php index 274ff9eca9..c22de72cef 100644 --- a/tests/Cache/Redis/Operations/AnyTag/PutManyTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/PutManyTest.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Cache\Redis\Operations\AnyTag; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; +use JMac\Testing\Matching\Argument; /** * Tests for the PutMany operation (union tags). @@ -16,31 +17,30 @@ public function testPutManyWithTagsStoresMultipleItems(): void $connection = $this->mockConnection(); // Standard mode uses pipeline() not multi() - $connection->shouldReceive('pipeline')->twice()->andReturn($connection); + $connection->client()->expects('pipeline')->times(2)->returns($connection->client()); // First pipeline for getting old tags (smembers) - $connection->shouldReceive('smembers')->twice()->andReturn($connection); - $connection->shouldReceive('exec')->twice()->andReturn([[], []], []); + $connection->client()->expects('smembers')->times(2)->returns($connection->client()); + $connection->client()->expects('exec')->times(2)->returns([[], []], []); // Second pipeline for setex, reverse index updates, and tag hashes - $connection->shouldReceive('setex')->twice()->andReturn($connection); - $connection->shouldReceive('del')->twice()->andReturn($connection); - $connection->shouldReceive('sadd')->twice()->andReturn($connection); - $connection->shouldReceive('expire')->twice()->andReturn($connection); + $connection->client()->expects('setex')->times(2)->returns($connection->client()); + $connection->client()->expects('del')->times(2)->returns($connection->client()); + $connection->client()->expects('sadd')->times(2)->returns($connection->client()); + $connection->client()->expects('expire')->times(2)->returns($connection->client()); - $connection->shouldReceive('hsetex') - ->once() + $connection->client()->expects('hsetex') ->with( 'prefix:_any:tag:users:entries', ['foo' => '1', 'baz' => '1'], ['EX' => 60], ) - ->andReturn($connection); - $connection->shouldNotReceive('hSet'); - $connection->shouldNotReceive('hexpire'); + ->returns($connection->client()); + $connection->client()->expects('hSet')->never(); + $connection->client()->expects('hexpire')->never(); // zadd for registry - $connection->shouldReceive('zadd')->andReturn($connection); + $connection->client()->allows('zadd')->returns($connection->client()); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -53,26 +53,25 @@ public function testPutManyWithTagsStoresMultipleItems(): void public function testPutManyUsesOneBatchedHsetexPerTagInClusterMode(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); - - $connection->shouldReceive('smembers')->twice()->andReturn([]); - $connection->shouldReceive('setex')->twice()->andReturnTrue(); - $connection->shouldReceive('multi')->twice()->andReturn($connection); - $connection->shouldReceive('del')->twice()->andReturn($connection); - $connection->shouldReceive('sadd')->twice()->andReturn($connection); - $connection->shouldReceive('expire')->twice()->andReturn($connection); - $connection->shouldReceive('exec')->twice()->andReturn([]); - $connection->shouldReceive('hsetex') - ->once() + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); + + $client->expects('smembers')->times(2)->returns([]); + $client->expects('setex')->times(2)->returns(true); + $client->expects('multi')->times(2)->returns($client); + $client->expects('del')->times(2)->returns($client); + $client->expects('sadd')->times(2)->returns($client); + $client->expects('expire')->times(2)->returns($client); + $client->expects('exec')->times(2)->returns([]); + $client->expects('hsetex') ->with( 'prefix:_any:tag:users:entries', ['foo' => '1', 'baz' => '1'], ['EX' => 60], ) - ->andReturnTrue(); - $connection->shouldNotReceive('hSet'); - $connection->shouldNotReceive('hexpire'); - $connection->shouldReceive('zadd')->once()->andReturn(1); + ->returns(2); + $client->expects('hSet')->never(); + $client->expects('hexpire')->never(); + $client->expects('zadd')->returns(1); $result = $redis->anyTagOps()->putMany()->execute([ 'foo' => 'bar', @@ -87,28 +86,26 @@ public function testPutManyNormalizesExpiringMetadata(): void $connection = $this->mockConnection(); $startedAt = time(); - $connection->shouldReceive('pipeline')->twice()->andReturn($connection); - $connection->shouldReceive('smembers')->once()->with('prefix:foo:_any:tags')->andReturn($connection); - $connection->shouldReceive('exec')->twice()->andReturn([[]], []); - $connection->shouldReceive('setex')->once()->with('prefix:foo', 1, serialize('bar'))->andReturn($connection); - $connection->shouldReceive('del')->once()->with('prefix:foo:_any:tags')->andReturn($connection); - $connection->shouldReceive('sadd')->once()->with('prefix:foo:_any:tags', 'users')->andReturn($connection); - $connection->shouldReceive('expire')->once()->with('prefix:foo:_any:tags', 1)->andReturn($connection); - $connection->shouldReceive('hsetex') - ->once() + $connection->client()->expects('pipeline')->times(2)->returns($connection->client()); + $connection->client()->expects('smembers')->with('prefix:foo:_any:tags')->returns($connection->client()); + $connection->client()->expects('exec')->times(2)->returns([[]], []); + $connection->client()->expects('setex')->with('prefix:foo', 1, serialize('bar'))->returns($connection->client()); + $connection->client()->expects('del')->with('prefix:foo:_any:tags')->returns($connection->client()); + $connection->client()->expects('sadd')->with('prefix:foo:_any:tags', 'users')->returns($connection->client()); + $connection->client()->expects('expire')->with('prefix:foo:_any:tags', 1)->returns($connection->client()); + $connection->client()->expects('hsetex') ->with('prefix:_any:tag:users:entries', ['foo' => '1'], ['EX' => 1]) - ->andReturn($connection); - $connection->shouldReceive('zadd') - ->once() - ->withArgs(function (string $key, array $options, int $expiresAt, string $tag) use ($startedAt): bool { + ->returns($connection->client()); + $connection->client()->expects('zadd') + ->with(Argument::all(function (string $key, array $options, int $expiresAt, string $tag) use ($startedAt): bool { $this->assertSame('prefix:_any:tag:registry', $key); $this->assertSame(['GT'], $options); $this->assertGreaterThan($startedAt, $expiresAt); $this->assertSame('users', $tag); return true; - }) - ->andReturn($connection); + })) + ->returns($connection->client()); $redis = $this->createStore($connection, tagMode: 'any'); diff --git a/tests/Cache/Redis/Operations/AnyTag/PutTest.php b/tests/Cache/Redis/Operations/AnyTag/PutTest.php index 2839dd2987..b789381a59 100644 --- a/tests/Cache/Redis/Operations/AnyTag/PutTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/PutTest.php @@ -5,6 +5,7 @@ namespace Hypervel\Tests\Cache\Redis\Operations\AnyTag; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; +use JMac\Testing\Matching\Argument; /** * Tests for the Put operation (union tags). @@ -16,9 +17,8 @@ public function testPutWithTagsUsesLuaScriptInStandardMode(): void $connection = $this->mockConnection(); // Standard mode uses Lua script via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args) { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args) { // Verify Lua script contains expected commands $this->assertStringContainsString('SETEX', $script); $this->assertStringContainsString('HSETEX', $script); @@ -28,8 +28,8 @@ public function testPutWithTagsUsesLuaScriptInStandardMode(): void $this->assertCount(2, $keys); return true; - }) - ->andReturn(true); + })) + ->returns(true); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -39,24 +39,24 @@ public function testPutWithTagsUsesLuaScriptInStandardMode(): void public function testPutWithTagsUsesSequentialCommandsInClusterMode(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); // Cluster mode expectations - $connection->shouldReceive('smembers')->once()->andReturn([]); - $connection->shouldReceive('setex')->once()->with('prefix:foo', 60, serialize('bar'))->andReturn(true); + $client->expects('smembers')->returns([]); + $client->expects('setex')->with('prefix:foo', 60, serialize('bar'))->returns(true); // Multi for reverse index - $connection->shouldReceive('multi')->andReturn($connection); - $connection->shouldReceive('del')->andReturn($connection); - $connection->shouldReceive('sadd')->andReturn($connection); - $connection->shouldReceive('expire')->andReturn($connection); - $connection->shouldReceive('exec')->andReturn([true, true, true]); + $client->allows('multi')->returns($client); + $client->allows('del')->returns($client); + $client->allows('sadd')->returns($client); + $client->allows('expire')->returns($client); + $client->allows('exec')->returns([true, true, true]); - // HSETEX for tag hashes (2 tags) - use withAnyArgs to bypass type checking - $connection->shouldReceive('hsetex')->withAnyArgs()->twice()->andReturn(true); + // HSETEX for both tag hashes. + $client->expects('hsetex')->times(2)->returns(1); - // ZADD for registry - use withAnyArgs to handle variable args - $connection->shouldReceive('zadd')->withAnyArgs()->once()->andReturn(2); + // ZADD for the registry. + $client->expects('zadd')->returns(2); $result = $redis->anyTagOps()->put()->execute('foo', 'bar', 60, ['users', 'posts']); $this->assertTrue($result); @@ -64,31 +64,29 @@ public function testPutWithTagsUsesSequentialCommandsInClusterMode(): void public function testPutNormalizesExpiringMetadataInClusterMode(): void { - [$redis, , $connection] = $this->createClusterStore(tagMode: 'any'); + [$redis, $client] = $this->createClusterStore(tagMode: 'any'); $startedAt = time(); - $connection->shouldReceive('smembers')->once()->with('prefix:foo:_any:tags')->andReturn([]); - $connection->shouldReceive('setex')->once()->with('prefix:foo', 1, serialize('bar'))->andReturn(true); - $connection->shouldReceive('multi')->once()->andReturnSelf(); - $connection->shouldReceive('del')->once()->with('prefix:foo:_any:tags')->andReturnSelf(); - $connection->shouldReceive('sadd')->once()->with('prefix:foo:_any:tags', 'users')->andReturnSelf(); - $connection->shouldReceive('expire')->once()->with('prefix:foo:_any:tags', 1)->andReturnSelf(); - $connection->shouldReceive('exec')->once()->andReturn([]); - $connection->shouldReceive('hsetex') - ->once() + $client->expects('smembers')->with('prefix:foo:_any:tags')->returns([]); + $client->expects('setex')->with('prefix:foo', 1, serialize('bar'))->returns(true); + $client->expects('multi')->returns($client); + $client->expects('del')->with('prefix:foo:_any:tags')->returns($client); + $client->expects('sadd')->with('prefix:foo:_any:tags', 'users')->returns($client); + $client->expects('expire')->with('prefix:foo:_any:tags', 1)->returns($client); + $client->expects('exec')->returns([]); + $client->expects('hsetex') ->with('prefix:_any:tag:users:entries', ['foo' => '1'], ['EX' => 1]) - ->andReturn(1); - $connection->shouldReceive('zadd') - ->once() - ->withArgs(function (string $key, array $options, int $expiresAt, string $tag) use ($startedAt): bool { + ->returns(1); + $client->expects('zadd') + ->with(Argument::all(function (string $key, array $options, int $expiresAt, string $tag) use ($startedAt): bool { $this->assertSame('prefix:_any:tag:registry', $key); $this->assertSame(['GT'], $options); $this->assertGreaterThan($startedAt, $expiresAt); $this->assertSame('users', $tag); return true; - }) - ->andReturn(1); + })) + ->returns(1); $this->assertTrue($redis->anyTagOps()->put()->execute('foo', 'bar', -60, ['users'])); } @@ -97,9 +95,8 @@ public function testPutWithTagsHandlesEmptyTags(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -111,15 +108,14 @@ public function testPutWithTagsWithNumericValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args) { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args) { // Numeric values should be passed as strings in args // Args array contains: value, ttl, tagPrefix, registryKey, currentTime, rawKey, tagHashSuffix, ...tags $this->assertIsString($args[0]); // Serialized value return true; - }) - ->andReturn(true); + })) + ->returns(true); $redis = $this->createStore($connection); $redis->setTagMode('any'); diff --git a/tests/Cache/Redis/Operations/DecrementTest.php b/tests/Cache/Redis/Operations/DecrementTest.php index 6d8093fc0e..e73ca9d778 100644 --- a/tests/Cache/Redis/Operations/DecrementTest.php +++ b/tests/Cache/Redis/Operations/DecrementTest.php @@ -14,7 +14,7 @@ class DecrementTest extends RedisCacheTestCase public function testDecrementMethodProperlyCallsRedis(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('decrby')->once()->with('prefix:foo', 5)->andReturn(4); + $connection->client()->expects('decrby')->with('prefix:foo', 5)->returns(4); $redis = $this->createStore($connection); $result = $redis->decrement('foo', 5); @@ -25,7 +25,7 @@ public function testDecrementOnNonExistentKeyReturnsDecrementedValue(): void { // Redis DECRBY on non-existent key initializes to 0, then decrements $connection = $this->mockConnection(); - $connection->shouldReceive('decrby')->once()->with('prefix:counter', 1)->andReturn(-1); + $connection->client()->expects('decrby')->with('prefix:counter', 1)->returns(-1); $redis = $this->createStore($connection); $this->assertSame(-1, $redis->decrement('counter')); @@ -34,7 +34,7 @@ public function testDecrementOnNonExistentKeyReturnsDecrementedValue(): void public function testDecrementReturnsFalseWhenRedisRejectsTheOperation(): void { $connection = $this->mockConnection(); - $connection->expects('decrby')->with('prefix:foo', 1)->andReturnFalse(); + $connection->client()->expects('decrby')->with('prefix:foo', 1)->returns(false); $redis = $this->createStore($connection); diff --git a/tests/Cache/Redis/Operations/FlushTest.php b/tests/Cache/Redis/Operations/FlushTest.php index 9826f0f043..e1b57c80f2 100644 --- a/tests/Cache/Redis/Operations/FlushTest.php +++ b/tests/Cache/Redis/Operations/FlushTest.php @@ -6,9 +6,9 @@ use Hypervel\Cache\Redis\Operations\Flush; use Hypervel\Cache\Redis\Support\StoreContext; -use Hypervel\Redis\RedisConnection; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Matching\Argument; /** * Tests for the Flush operation. @@ -18,7 +18,7 @@ class FlushTest extends RedisCacheTestCase public function testFlushesCached(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('flushdb')->once()->andReturn(true); + $connection->client()->expects('flushdb')->returns(true); $redis = $this->createStore($connection); $result = $redis->flush(); @@ -27,12 +27,12 @@ public function testFlushesCached(): void public function testFlushEnablesTransformsAndPropagatesFailure(): void { - $connection = m::mock(RedisConnection::class); - $connection->expects('flushdb')->once()->andReturnFalse(); - $context = m::mock(StoreContext::class); + $connection = $this->mockConnection(); + $connection->client()->expects('flushdb')->returns(false); + $context = Double::for(StoreContext::class); $context->expects('withConnection') - ->with(m::type('callable'), true) - ->andReturnUsing(fn (callable $callback) => $callback($connection)); + ->with(Argument::type('callable'), true) + ->resolves(fn (callable $callback) => $callback($connection->shouldTransform(true))); $this->assertFalse((new Flush($context))->execute()); } diff --git a/tests/Cache/Redis/Operations/ForeverTest.php b/tests/Cache/Redis/Operations/ForeverTest.php index fca569cdfd..d1ea1d50d2 100644 --- a/tests/Cache/Redis/Operations/ForeverTest.php +++ b/tests/Cache/Redis/Operations/ForeverTest.php @@ -14,10 +14,9 @@ class ForeverTest extends RedisCacheTestCase public function testStoreItemForeverProperlyCallsRedis(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:foo', serialize('foo')) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $result = $redis->forever('foo', 'foo'); @@ -27,10 +26,9 @@ public function testStoreItemForeverProperlyCallsRedis(): void public function testForeverWithNumericValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('set') - ->once() + $connection->client()->expects('set') ->with('prefix:foo', 99) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $this->assertTrue($redis->forever('foo', 99)); diff --git a/tests/Cache/Redis/Operations/ForgetTest.php b/tests/Cache/Redis/Operations/ForgetTest.php index 4a4c1d2661..414fd2973d 100644 --- a/tests/Cache/Redis/Operations/ForgetTest.php +++ b/tests/Cache/Redis/Operations/ForgetTest.php @@ -14,7 +14,7 @@ class ForgetTest extends RedisCacheTestCase public function testForgetReturnsTrueWhenKeyExists(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('del')->once()->with('prefix:foo')->andReturn(1); + $connection->client()->expects('del')->with('prefix:foo')->returns(1); $redis = $this->createStore($connection); $this->assertTrue($redis->forget('foo')); @@ -24,7 +24,7 @@ public function testForgetReturnsFalseWhenKeyDoesNotExist(): void { // Redis del() returns 0 when key doesn't exist, cast to bool = false $connection = $this->mockConnection(); - $connection->shouldReceive('del')->once()->with('prefix:nonexistent')->andReturn(0); + $connection->client()->expects('del')->with('prefix:nonexistent')->returns(0); $redis = $this->createStore($connection); $this->assertFalse($redis->forget('nonexistent')); diff --git a/tests/Cache/Redis/Operations/GetTest.php b/tests/Cache/Redis/Operations/GetTest.php index 805f8a8c24..2925bea51b 100644 --- a/tests/Cache/Redis/Operations/GetTest.php +++ b/tests/Cache/Redis/Operations/GetTest.php @@ -14,7 +14,7 @@ class GetTest extends RedisCacheTestCase public function testGetReturnsNullWhenNotFound(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(null); + $connection->client()->expects('get')->with('prefix:foo')->returns(null); $redis = $this->createStore($connection); $this->assertNull($redis->get('foo')); @@ -23,7 +23,7 @@ public function testGetReturnsNullWhenNotFound(): void public function testRedisValueIsReturned(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('foo')); + $connection->client()->expects('get')->with('prefix:foo')->returns(serialize('foo')); $redis = $this->createStore($connection); $this->assertSame('foo', $redis->get('foo')); @@ -32,7 +32,7 @@ public function testRedisValueIsReturned(): void public function testRedisValueIsReturnedForNumerics(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(1); + $connection->client()->expects('get')->with('prefix:foo')->returns(1); $redis = $this->createStore($connection); $this->assertEquals(1, $redis->get('foo')); @@ -42,7 +42,7 @@ public function testGetReturnsFalseValueAsNull(): void { // Redis returns false for non-existent keys $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(false); + $connection->client()->expects('get')->with('prefix:foo')->returns(false); $redis = $this->createStore($connection); $this->assertNull($redis->get('foo')); @@ -51,7 +51,7 @@ public function testGetReturnsFalseValueAsNull(): void public function testGetReturnsEmptyStringCorrectly(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('')); + $connection->client()->expects('get')->with('prefix:foo')->returns(serialize('')); $redis = $this->createStore($connection); $this->assertSame('', $redis->get('foo')); @@ -60,7 +60,7 @@ public function testGetReturnsEmptyStringCorrectly(): void public function testGetReturnsZeroCorrectly(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(0); + $connection->client()->expects('get')->with('prefix:foo')->returns(0); $redis = $this->createStore($connection); $this->assertSame(0, $redis->get('foo')); @@ -69,7 +69,7 @@ public function testGetReturnsZeroCorrectly(): void public function testGetReturnsFloatCorrectly(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(3.14); + $connection->client()->expects('get')->with('prefix:foo')->returns(3.14); $redis = $this->createStore($connection); $this->assertSame(3.14, $redis->get('foo')); @@ -78,7 +78,7 @@ public function testGetReturnsFloatCorrectly(): void public function testGetReturnsNegativeNumberCorrectly(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(-42); + $connection->client()->expects('get')->with('prefix:foo')->returns(-42); $redis = $this->createStore($connection); $this->assertSame(-42, $redis->get('foo')); diff --git a/tests/Cache/Redis/Operations/IncrementTest.php b/tests/Cache/Redis/Operations/IncrementTest.php index c773833743..b2e9b3bc81 100644 --- a/tests/Cache/Redis/Operations/IncrementTest.php +++ b/tests/Cache/Redis/Operations/IncrementTest.php @@ -14,7 +14,7 @@ class IncrementTest extends RedisCacheTestCase public function testIncrementMethodProperlyCallsRedis(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('incrby')->once()->with('prefix:foo', 5)->andReturn(6); + $connection->client()->expects('incrby')->with('prefix:foo', 5)->returns(6); $redis = $this->createStore($connection); $result = $redis->increment('foo', 5); @@ -25,7 +25,7 @@ public function testIncrementOnNonExistentKeyReturnsIncrementedValue(): void { // Redis INCRBY on non-existent key initializes to 0, then increments $connection = $this->mockConnection(); - $connection->shouldReceive('incrby')->once()->with('prefix:counter', 1)->andReturn(1); + $connection->client()->expects('incrby')->with('prefix:counter', 1)->returns(1); $redis = $this->createStore($connection); $this->assertSame(1, $redis->increment('counter')); @@ -34,7 +34,7 @@ public function testIncrementOnNonExistentKeyReturnsIncrementedValue(): void public function testIncrementWithLargeValue(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('incrby')->once()->with('prefix:foo', 1000000)->andReturn(1000005); + $connection->client()->expects('incrby')->with('prefix:foo', 1000000)->returns(1000005); $redis = $this->createStore($connection); $this->assertSame(1000005, $redis->increment('foo', 1000000)); @@ -43,7 +43,7 @@ public function testIncrementWithLargeValue(): void public function testIncrementReturnsFalseWhenRedisRejectsTheOperation(): void { $connection = $this->mockConnection(); - $connection->expects('incrby')->with('prefix:foo', 1)->andReturnFalse(); + $connection->client()->expects('incrby')->with('prefix:foo', 1)->returns(false); $redis = $this->createStore($connection); diff --git a/tests/Cache/Redis/Operations/ManyTest.php b/tests/Cache/Redis/Operations/ManyTest.php index b4eeca2c7e..0008fd90e7 100644 --- a/tests/Cache/Redis/Operations/ManyTest.php +++ b/tests/Cache/Redis/Operations/ManyTest.php @@ -14,10 +14,9 @@ class ManyTest extends RedisCacheTestCase public function testRedisMultipleValuesAreReturned(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with(['prefix:foo', 'prefix:fizz', 'prefix:norf', 'prefix:null']) - ->andReturn([ + ->returns([ serialize('bar'), serialize('buzz'), serialize('quz'), @@ -47,10 +46,9 @@ public function testManyMaintainsKeyIndexMapping(): void { $connection = $this->mockConnection(); // Return values in same order as requested - $connection->shouldReceive('mget') - ->once() + $connection->client()->expects('mget') ->with(['prefix:a', 'prefix:b', 'prefix:c']) - ->andReturn([ + ->returns([ serialize('value_a'), null, serialize('value_c'), diff --git a/tests/Cache/Redis/Operations/PutManyTest.php b/tests/Cache/Redis/Operations/PutManyTest.php index cdaf8df1b8..9edf8d3437 100644 --- a/tests/Cache/Redis/Operations/PutManyTest.php +++ b/tests/Cache/Redis/Operations/PutManyTest.php @@ -6,6 +6,7 @@ use Hypervel\Redis\Exceptions\LuaScriptException; use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; +use JMac\Testing\Matching\Argument; /** * Tests for the PutMany operation. @@ -17,9 +18,8 @@ public function testPutManyUsesLuaScriptInStandardMode(): void $connection = $this->mockConnection(); // Standard mode (not cluster) uses Lua script via evalWithShaCache - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args) { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args) { // Verify Lua script structure $this->assertStringContainsString('SETEX', $script); // Keys: prefix:foo, prefix:baz, prefix:bar @@ -31,8 +31,8 @@ public function testPutManyUsesLuaScriptInStandardMode(): void $this->assertSame([60, serialize('bar'), serialize('qux'), serialize('norf')], $args); return true; - }) - ->andReturn(true); + })) + ->returns(true); $redis = $this->createStore($connection); $result = $redis->putMany([ @@ -45,10 +45,10 @@ public function testPutManyUsesLuaScriptInStandardMode(): void public function testPutManyUsesSequentialCommandsInClusterMode(): void { - [$redis, , $connection] = $this->createClusterStore(); + [$redis, $client] = $this->createClusterStore(); - $connection->shouldReceive('setex')->once()->with('prefix:foo', 60, serialize('bar'))->andReturnTrue(); - $connection->shouldReceive('setex')->once()->with('prefix:baz', 60, serialize('qux'))->andReturnTrue(); + $client->expects('setex')->with('prefix:foo', 60, serialize('bar'))->returns(true); + $client->expects('setex')->with('prefix:baz', 60, serialize('qux'))->returns(true); $result = $redis->putMany([ 'foo' => 'bar', @@ -59,10 +59,10 @@ public function testPutManyUsesSequentialCommandsInClusterMode(): void public function testPutManyClusterModeReturnsFalseOnFailure(): void { - [$redis, , $connection] = $this->createClusterStore(); + [$redis, $client] = $this->createClusterStore(); - $connection->shouldReceive('setex')->once()->with('prefix:foo', 60, serialize('bar'))->andReturnFalse(); - $connection->shouldReceive('setex')->once()->with('prefix:baz', 60, serialize('qux'))->andReturnTrue(); + $client->expects('setex')->with('prefix:foo', 60, serialize('bar'))->returns(false); + $client->expects('setex')->with('prefix:baz', 60, serialize('qux'))->returns(true); $result = $redis->putMany([ 'foo' => 'bar', @@ -86,9 +86,8 @@ public function testPutManyLuaFailureThrowsException(): void $connection = $this->mockConnection(); // evalWithShaCache throws LuaScriptException on failure - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andThrow(new LuaScriptException('Lua script execution failed')); + $connection->expects('evalWithShaCache') + ->throws(new LuaScriptException('Lua script execution failed')); $this->expectException(LuaScriptException::class); @@ -103,14 +102,13 @@ public function testPutManyEnforcesMinimumTtlOfOne(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->withArgs(function ($script, $keys, $args) { + $connection->expects('evalWithShaCache') + ->with(Argument::all(function ($script, $keys, $args) { // TTL should be 1, not 0 $this->assertSame(1, $args[0]); // TTL is first arg return true; - }) - ->andReturn(true); + })) + ->returns(true); $redis = $this->createStore($connection); $result = $redis->putMany(['foo' => 'bar'], 0); diff --git a/tests/Cache/Redis/Operations/PutTest.php b/tests/Cache/Redis/Operations/PutTest.php index 12febeef60..7fd3e216f1 100644 --- a/tests/Cache/Redis/Operations/PutTest.php +++ b/tests/Cache/Redis/Operations/PutTest.php @@ -14,10 +14,9 @@ class PutTest extends RedisCacheTestCase public function testSetMethodProperlyCallsRedis(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:foo', 60, serialize('foo')) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $result = $redis->put('foo', 'foo', 60); @@ -27,10 +26,9 @@ public function testSetMethodProperlyCallsRedis(): void public function testSetMethodProperlyCallsRedisForNumerics(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:foo', 60, 1) - ->andReturn(false); + ->returns(false); $redis = $this->createStore($connection); $result = $redis->put('foo', 1, 60); @@ -41,10 +39,9 @@ public function testPutPreservesArrayValues(): void { $connection = $this->mockConnection(); $array = ['nested' => ['data' => 'value']]; - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:foo', 60, serialize($array)) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $this->assertTrue($redis->put('foo', $array, 60)); @@ -54,10 +51,9 @@ public function testPutEnforcesMinimumTtlOfOne(): void { $connection = $this->mockConnection(); // TTL of 0 should become 1 (Redis requires positive TTL for SETEX) - $connection->shouldReceive('setex') - ->once() + $connection->client()->expects('setex') ->with('prefix:foo', 1, serialize('bar')) - ->andReturn(true); + ->returns(true); $redis = $this->createStore($connection); $this->assertTrue($redis->put('foo', 'bar', 0)); diff --git a/tests/Cache/Redis/RedisCacheTestCase.php b/tests/Cache/Redis/RedisCacheTestCase.php index d4f88b45ef..331372e814 100644 --- a/tests/Cache/Redis/RedisCacheTestCase.php +++ b/tests/Cache/Redis/RedisCacheTestCase.php @@ -13,42 +13,21 @@ use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Redis\Fixtures\FakeRedisClient; +use Hypervel\Tests\Redis\Fixtures\PhpRedisClusterConnectionStub; use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Redis; use RedisCluster; /** - * Base test case for Redis cache unit tests. - * - * Provides: - * - Mock connection helpers for standard and cluster modes - * - Fixed test time for ZSET timestamp score calculations - * - Automatic Mockery and Carbon cleanup (via Foundation\Testing\TestCase) - * - * ## Usage Examples - * - * ### Standard (non-cluster) tests: - * ```php - * $connection = $this->mockConnection(); - * $client = $connection->_mockClient; - * $client->shouldReceive('set')->once()->andReturn(true); - * - * $store = $this->createStore($connection); - * // or with tag mode: - * $store = $this->createStore($connection, tagMode: 'any'); - * ``` - * - * ### Cluster mode tests: - * ```php - * [$store, $clusterClient] = $this->createClusterStore(); - * $clusterClient->shouldNotReceive('pipeline'); - * $clusterClient->shouldReceive('set')->once()->andReturn(true); - * ``` + * Exercise cache operations through real connection forwarding to native client doubles. */ abstract class RedisCacheTestCase extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -58,106 +37,34 @@ protected function setUp(): void } /** - * Create a mock RedisConnection with standard expectations. - * - * By default creates a mock with a standard Redis client (not cluster). - * Use createClusterStore() for cluster mode tests. - * - * We use an anonymous mock for the client (not m::mock(Redis::class)) - * because mocking the native phpredis extension class can cause - * unexpected fallthrough to real Redis connections when expectations - * don't match. - * - * @return MockInterface|PhpRedisConnection connection with _mockClient property for setting expectations + * Create a standalone connection with an isolated native client. */ - protected function mockConnection(): MockInterface|PhpRedisConnection + protected function mockConnection(): PhpRedisConnection&DoubleInterface { - // Anonymous mock - not bound to Redis extension class - // This prevents fallthrough to real Redis when expectations don't match - $client = m::mock(); - $client->shouldReceive('getOption') - ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE) - ->byDefault(); - $client->shouldReceive('getOption') - ->with(Redis::OPT_PREFIX) - ->andReturn('') - ->byDefault(); - - // Default pipeline() returns self for chaining (can be overridden in tests) - $client->shouldReceive('pipeline')->andReturn($client)->byDefault(); - $client->shouldReceive('exec')->andReturn([])->byDefault(); - - $connection = m::mock(PhpRedisConnection::class); - $connection->allows('isCluster')->andReturn(false)->byDefault(); - $connection->shouldReceive('release')->zeroOrMoreTimes(); - $connection->shouldReceive('withoutScanPrefix') - ->andReturnUsing(fn (callable $callback): mixed => $callback()) - ->byDefault(); - $connection->shouldReceive('serialized')->andReturn(false)->byDefault(); - $connection->shouldReceive('client')->andReturn($client)->byDefault(); - $connection->shouldReceive('getOption') - ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE) - ->byDefault(); - $connection->shouldReceive('getOption') - ->with(Redis::OPT_PREFIX) - ->andReturn('') - ->byDefault(); - - // Default pipeline() returns self for chaining (can be overridden in tests) - $connection->shouldReceive('pipeline')->andReturn($connection)->byDefault(); - $connection->shouldReceive('exec')->andReturn([])->byDefault(); - - // Expose the client for expectation setup. - $connection->_mockClient = $client; - - return $connection; + // Unexpected commands must fail: an extra Redis round trip is a regression. + $client = Double::for(Redis::class)->strict(); + $client->allows('getMode')->returns(Redis::ATOMIC); + $client->allows('getOption')->with(Redis::OPT_SERIALIZER)->returns(Redis::SERIALIZER_NONE); + $client->allows('getOption')->with(Redis::OPT_COMPRESSION)->returns(Redis::COMPRESSION_NONE); + $client->allows('getOption')->with(Redis::OPT_PREFIX)->returns(''); + $client->allows('getOption')->with(Redis::OPT_SCAN)->returns(0); + + return Double::for((new PhpRedisConnectionStub)->setActiveConnection($client))->passthru(); } /** - * Create a mock RedisConnection configured as a cluster connection. - * - * Uses PhpRedisClusterConnection which returns true from isCluster() - * by its class definition, triggering cluster mode (sequential commands - * instead of pipelines). - * - * @return MockInterface|PhpRedisClusterConnection connection with _mockClient property for setting expectations + * Create a cluster connection with an isolated native client. */ - protected function mockClusterConnection(): MockInterface|PhpRedisClusterConnection + protected function mockClusterConnection(): PhpRedisClusterConnection&DoubleInterface { - // Mock that identifies as RedisCluster for instanceof checks - $client = m::mock(RedisCluster::class); - $client->shouldReceive('getOption') - ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE) - ->byDefault(); - $client->shouldReceive('getOption') - ->with(Redis::OPT_PREFIX) - ->andReturn('') - ->byDefault(); - - $connection = m::mock(PhpRedisClusterConnection::class); - $connection->allows('isCluster')->andReturn(true)->byDefault(); - $connection->shouldReceive('release')->zeroOrMoreTimes(); - $connection->shouldReceive('withoutScanPrefix') - ->andReturnUsing(fn (callable $callback): mixed => $callback()) - ->byDefault(); - $connection->shouldReceive('serialized')->andReturn(false)->byDefault(); - $connection->shouldReceive('client')->andReturn($client)->byDefault(); - $connection->shouldReceive('getOption') - ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE) - ->byDefault(); - $connection->shouldReceive('getOption') - ->with(Redis::OPT_PREFIX) - ->andReturn('') - ->byDefault(); - - // Expose the client for expectation setup. - $connection->_mockClient = $client; - - return $connection; + // RedisCluster has no pipeline method, so attempts to pipeline already fail natively. + $client = Double::for(RedisCluster::class)->strict(); + $client->allows('getOption')->with(Redis::OPT_SERIALIZER)->returns(Redis::SERIALIZER_NONE); + $client->allows('getOption')->with(Redis::OPT_COMPRESSION)->returns(Redis::COMPRESSION_NONE); + $client->allows('getOption')->with(Redis::OPT_PREFIX)->returns(''); + $client->allows('getOption')->with(Redis::OPT_SCAN)->returns(0); + + return Double::for((new PhpRedisClusterConnectionStub)->setActiveConnection($client))->passthru(); } /** @@ -166,32 +73,25 @@ protected function mockClusterConnection(): MockInterface|PhpRedisClusterConnect protected function createRedisFactory( RedisConnection $connection, string $connectionName = 'default' - ): MockInterface|RedisFactory { - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldReceive('withConnection') - ->andReturnUsing(fn (callable $callback) => $callback($connection)); - $redisProxy->shouldReceive('isCluster') - ->andReturn($connection instanceof PhpRedisClusterConnection) - ->byDefault(); - - $redisFactory = m::mock(RedisFactory::class); - $redisFactory->shouldReceive('connection') + ): RedisFactory&DoubleInterface { + $redisProxy = Double::for(RedisProxy::class); + $redisProxy->allows('withConnection') + ->resolves(static fn (callable $callback, bool $transform = true): mixed => $callback($connection->shouldTransform($transform))); + $redisProxy->allows('isCluster')->returns($connection->isCluster()); + + $redisFactory = Double::for(RedisFactory::class)->strict(); + $redisFactory->allows('connection') ->with($connectionName) - ->andReturn($redisProxy); + ->returns($redisProxy); return $redisFactory; } /** - * Create a RedisStore with a mocked connection. - * - * @param MockInterface|RedisConnection $connection the mocked connection (from mockConnection()) - * @param string $prefix cache key prefix - * @param string $connectionName Redis connection name - * @param null|string $tagMode optional tag mode ('any' or 'all'). If provided, setTagMode() is called. + * Create a store backed by the given connection. */ protected function createStore( - MockInterface|RedisConnection $connection, + RedisConnection $connection, string $prefix = 'prefix:', string $connectionName = 'default', ?string $tagMode = null, @@ -210,23 +110,9 @@ protected function createStore( } /** - * Create a RedisStore configured for cluster mode testing. - * - * This eliminates the boilerplate of manually setting up RedisCluster mocks, - * connection mocks, pool mocks, and pool factory mocks for each cluster test. - * - * Returns the store, cluster client mock, and connection mock so tests can set expectations: - * ```php - * [$store, $clusterClient, $connection] = $this->createClusterStore(); - * $clusterClient->shouldNotReceive('pipeline'); - * $clusterClient->shouldReceive('zadd')->once()->andReturn(1); - * $connection->shouldReceive('del')->once()->andReturn(1); // connection-level operations - * ``` + * Create a store with its cluster client and connection doubles. * - * @param string $prefix cache key prefix - * @param string $connectionName Redis connection name - * @param null|string $tagMode optional tag mode ('any' or 'all') - * @return array{0: RedisStore, 1: MockInterface, 2: MockInterface} [store, clusterClient, connection] + * @return array{RedisStore, DoubleInterface&RedisCluster, DoubleInterface&PhpRedisClusterConnection} */ protected function createClusterStore( string $prefix = 'prefix:', @@ -234,35 +120,16 @@ protected function createClusterStore( ?string $tagMode = null, ): array { $connection = $this->mockClusterConnection(); - $clusterClient = $connection->_mockClient; - - $store = new RedisStore( - $this->createRedisFactory($connection, $connectionName), - $prefix, - $connectionName - ); - if ($tagMode !== null) { - $store->setTagMode($tagMode); - } - - return [$store, $clusterClient, $connection]; + return [ + $this->createStore($connection, $prefix, $connectionName, $tagMode), + $connection->client(), + $connection, + ]; } /** - * Create a RedisStore with a FakeRedisClient. - * - * Uses PhpRedisConnectionStub (which extends PhpRedisConnection) with FakeRedisClient - * injected as the underlying client. This allows proper reference parameter handling - * (e.g., &$iterator in SCAN/HSCAN/ZSCAN operations) which Mockery cannot propagate. - * - * FakeRedisClient extends Redis, satisfying the Redis|RedisCluster type hint. - * RedisConnection methods naturally delegate to the injected FakeRedisClient. - * - * @param FakeRedisClient $fakeClient pre-configured fake client with expected responses - * @param string $prefix cache key prefix - * @param string $connectionName Redis connection name - * @param null|string $tagMode optional tag mode ('any' or 'all') + * Create a store with explicit by-reference scan cursor responses. */ protected function createStoreWithFakeClient( FakeRedisClient $fakeClient, @@ -270,19 +137,11 @@ protected function createStoreWithFakeClient( string $connectionName = 'default', ?string $tagMode = null, ): RedisStore { - $connection = new PhpRedisConnectionStub; - $connection->setActiveConnection($fakeClient); - - $store = new RedisStore( - $this->createRedisFactory($connection, $connectionName), + return $this->createStore( + (new PhpRedisConnectionStub)->setActiveConnection($fakeClient), $prefix, - $connectionName + $connectionName, + $tagMode, ); - - if ($tagMode !== null) { - $store->setTagMode($tagMode); - } - - return $store; } } diff --git a/tests/Cache/Redis/RedisStoreTest.php b/tests/Cache/Redis/RedisStoreTest.php index 2bdd3d27e6..5a0a75b3cc 100644 --- a/tests/Cache/Redis/RedisStoreTest.php +++ b/tests/Cache/Redis/RedisStoreTest.php @@ -15,7 +15,7 @@ use Hypervel\Redis\RedisProxy; use Hypervel\Support\ClassInvoker; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; use ReflectionClass; use ReflectionNamedType; use ReflectionProperty; @@ -26,13 +26,13 @@ class RedisStoreTest extends RedisCacheTestCase public function testSerializableClassesControlRedisValues(): void { $denyingConnection = $this->mockConnection(); - $denyingConnection->expects('get') + $denyingConnection->client()->expects('get') ->with('prefix:object') - ->andReturn(serialize(new stdClass)); + ->returns(serialize(new stdClass)); $allowingConnection = $this->mockConnection(); - $allowingConnection->expects('get') + $allowingConnection->client()->expects('get') ->with('prefix:object') - ->andReturn(serialize(new stdClass)); + ->returns(serialize(new stdClass)); $denyingStore = new RedisStore( $this->createRedisFactory($denyingConnection), @@ -54,9 +54,9 @@ public function testSerializableClassesControlRedisValues(): void public function testSerializableClassPolicyControlsRedisValues(): void { $connection = $this->mockConnection(); - $connection->expects('get') + $connection->client()->expects('get') ->with('prefix:object') - ->andReturn(serialize(new stdClass)); + ->returns(serialize(new stdClass)); $store = new RedisStore( $this->createRedisFactory($connection), 'prefix:', @@ -70,8 +70,8 @@ public function testSerializableClassPolicyControlsRedisValues(): void public function testCounterFailuresAreReturnedWithoutCoercion(): void { $connection = $this->mockConnection(); - $connection->expects('incrby')->with('prefix:increment', 2)->andReturnFalse(); - $connection->expects('decrby')->with('prefix:decrement', 3)->andReturnFalse(); + $connection->client()->expects('incrby')->with('prefix:increment', 2)->returns(false); + $connection->client()->expects('decrby')->with('prefix:decrement', 3)->returns(false); $redis = $this->createStore($connection); $this->assertFalse($redis->increment('increment', 2)); @@ -81,24 +81,22 @@ public function testCounterFailuresAreReturnedWithoutCoercion(): void public function testSetConnectionClearsCachedInstances(): void { $connection1 = $this->mockConnection(); - $connection1->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('value1')); + $connection1->client()->expects('get')->with('prefix:foo')->returns(serialize('value1')); $connection2 = $this->mockConnection(); - $connection2->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('value2')); + $connection2->client()->expects('get')->with('prefix:foo')->returns(serialize('value2')); - $redisProxy1 = m::mock(RedisProxy::class); - $redisProxy1->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection1)); + $redisProxy1 = Double::for(RedisProxy::class); + $redisProxy1->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection1->shouldTransform(false))); - $redisProxy2 = m::mock(RedisProxy::class); - $redisProxy2->shouldReceive('withConnection') - ->once() - ->andReturnUsing(fn (callable $callback) => $callback($connection2)); + $redisProxy2 = Double::for(RedisProxy::class); + $redisProxy2->expects('withConnection') + ->resolves(fn (callable $callback) => $callback($connection2->shouldTransform(false))); - $redisFactory = m::mock(Redis::class); - $redisFactory->shouldReceive('connection')->once()->with('conn1')->andReturn($redisProxy1); - $redisFactory->shouldReceive('connection')->once()->with('conn2')->andReturn($redisProxy2); + $redisFactory = Double::for(Redis::class)->strict(); + $redisFactory->expects('connection')->with('conn1')->returns($redisProxy1); + $redisFactory->expects('connection')->with('conn2')->returns($redisProxy2); $redis = new RedisStore($redisFactory, 'prefix:', 'conn1'); @@ -112,8 +110,8 @@ public function testSetConnectionClearsCachedInstances(): void public function testSetPrefixClearsCachedOperations(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('old')); - $connection->shouldReceive('get')->once()->with('newprefix:foo')->andReturn(serialize('new')); + $connection->client()->expects('get')->with('prefix:foo')->returns(serialize('old')); + $connection->client()->expects('get')->with('newprefix:foo')->returns(serialize('new')); $redis = $this->createStore($connection); @@ -290,10 +288,9 @@ public function testSetTagModeRejectsInvalidMode(): void public function testTouchUsesPlainExpireInAllMode(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('expire') - ->once() + $connection->client()->expects('expire') ->with('prefix:key', 60) - ->andReturn(1); + ->returns(true); $redis = $this->createStore($connection); @@ -303,9 +300,8 @@ public function testTouchUsesPlainExpireInAllMode(): void public function testTouchUsesAnyTagMetadataOperationInAnyMode(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(true); + $connection->expects('evalWithShaCache') + ->returns(true); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -316,10 +312,9 @@ public function testTouchUsesAnyTagMetadataOperationInAnyMode(): void public function testForgetUsesPlainDeleteInAllMode(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('del') - ->once() + $connection->client()->expects('del') ->with('prefix:key') - ->andReturn(1); + ->returns(1); $redis = $this->createStore($connection); @@ -329,9 +324,8 @@ public function testForgetUsesPlainDeleteInAllMode(): void public function testForgetUsesAnyTagMetadataOperationInAnyMode(): void { $connection = $this->mockConnection(); - $connection->shouldReceive('evalWithShaCache') - ->once() - ->andReturn(1); + $connection->expects('evalWithShaCache') + ->returns(1); $redis = $this->createStore($connection); $redis->setTagMode('any'); @@ -341,9 +335,9 @@ public function testForgetUsesAnyTagMetadataOperationInAnyMode(): void public function testLockReturnsRedisLockInstance(): void { - $redisProxy = m::mock(RedisProxy::class); - $redisFactory = m::mock(Redis::class); - $redisFactory->shouldReceive('connection')->with('default')->andReturn($redisProxy); + $redisProxy = Double::for(RedisProxy::class); + $redisFactory = Double::for(Redis::class)->strict(); + $redisFactory->allows('connection')->with('default')->returns($redisProxy); $redis = new RedisStore( $redisFactory, @@ -358,9 +352,9 @@ public function testLockReturnsRedisLockInstance(): void public function testLockWithOwner(): void { - $redisProxy = m::mock(RedisProxy::class); - $redisFactory = m::mock(Redis::class); - $redisFactory->shouldReceive('connection')->with('default')->andReturn($redisProxy); + $redisProxy = Double::for(RedisProxy::class); + $redisFactory = Double::for(Redis::class)->strict(); + $redisFactory->allows('connection')->with('default')->returns($redisProxy); $redis = new RedisStore( $redisFactory, @@ -375,9 +369,9 @@ public function testLockWithOwner(): void public function testRestoreLockReturnsRedisLockInstance(): void { - $redisProxy = m::mock(RedisProxy::class); - $redisFactory = m::mock(Redis::class); - $redisFactory->shouldReceive('connection')->with('default')->andReturn($redisProxy); + $redisProxy = Double::for(RedisProxy::class); + $redisFactory = Double::for(Redis::class)->strict(); + $redisFactory->allows('connection')->with('default')->returns($redisProxy); $redis = new RedisStore( $redisFactory, @@ -402,11 +396,11 @@ public function testSetLockConnectionReturnsSelf(): void public function testLockUsesLockConnectionWhenSet(): void { - $redisProxy = m::mock(RedisProxy::class); - $lockProxy = m::mock(RedisProxy::class); - $redisFactory = m::mock(Redis::class); - $redisFactory->shouldReceive('connection')->with('default')->andReturn($redisProxy); - $redisFactory->shouldReceive('connection')->with('locks')->andReturn($lockProxy); + $redisProxy = Double::for(RedisProxy::class); + $lockProxy = Double::for(RedisProxy::class); + $redisFactory = Double::for(Redis::class)->strict(); + $redisFactory->allows('connection')->with('default')->returns($redisProxy); + $redisFactory->allows('connection')->with('locks')->returns($lockProxy); $redis = new RedisStore( $redisFactory, @@ -422,7 +416,7 @@ public function testLockUsesLockConnectionWhenSet(): void public function testGetRedisReturnsRedis(): void { - $redisFactory = m::mock(Redis::class); + $redisFactory = Double::for(Redis::class)->strict(); $redis = new RedisStore( $redisFactory, @@ -435,9 +429,9 @@ public function testGetRedisReturnsRedis(): void public function testConnectionReturnsRedisProxy(): void { - $redisProxy = m::mock(RedisProxy::class); - $redisFactory = m::mock(Redis::class); - $redisFactory->shouldReceive('connection')->with('default')->andReturn($redisProxy); + $redisProxy = Double::for(RedisProxy::class); + $redisFactory = Double::for(Redis::class)->strict(); + $redisFactory->allows('connection')->with('default')->returns($redisProxy); $redis = new RedisStore( $redisFactory, diff --git a/tests/Cache/Redis/Support/SerializationTest.php b/tests/Cache/Redis/Support/SerializationTest.php index 7f7ea8342f..7258319b9f 100644 --- a/tests/Cache/Redis/Support/SerializationTest.php +++ b/tests/Cache/Redis/Support/SerializationTest.php @@ -8,12 +8,11 @@ use Hypervel\Cache\Redis\Support\Serialization; use Hypervel\Cache\SerializableClassPolicy; use Hypervel\Redis\PhpRedisConnection; -use Hypervel\Testbench\TestCase; -use Mockery as m; +use Hypervel\Tests\Cache\Redis\RedisCacheTestCase; use Redis; use stdClass; -class SerializationTest extends TestCase +class SerializationTest extends RedisCacheTestCase { private Serialization $serialization; @@ -162,11 +161,11 @@ public function testUnserializeReturnsNumericValuesRaw(): void public function testSerializeForLuaUsesPackWhenSerializerConfigured(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('serialized')->andReturn(true); - $connection->shouldReceive('pack') + $connection = $this->mockConnection(); + $connection->allows('serialized')->returns(true); + $connection->allows('pack') ->with(['test-value']) - ->andReturn(['packed-value']); + ->returns(['packed-value']); $this->assertSame('packed-value', $this->serialization->serializeForLua($connection, 'test-value')); } @@ -177,39 +176,39 @@ public function testSerializeForLuaAppliesCompressionWhenEnabled(): void $this->markTestSkipped('Redis::COMPRESSION_LZF not available (phpredis compiled without LZF support)'); } - $connection = m::mock(PhpRedisConnection::class); + $connection = $this->mockConnection(); - $connection->shouldReceive('serialized')->andReturn(false); - $connection->shouldReceive('getOption') + $connection->allows('serialized')->returns(false); + $connection->client()->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_LZF); - $connection->shouldReceive('pack') + ->returns(Redis::COMPRESSION_LZF); + $connection->allows('pack') ->with([serialize('test-value')]) - ->andReturn(['compressed-value']); + ->returns(['compressed-value']); $this->assertSame('compressed-value', $this->serialization->serializeForLua($connection, 'test-value')); } public function testSerializeForLuaReturnsPhpSerializedWhenNoSerializerOrCompression(): void { - $connection = m::mock(PhpRedisConnection::class); + $connection = $this->mockConnection(); - $connection->shouldReceive('serialized')->andReturn(false); - $connection->shouldReceive('getOption') + $connection->allows('serialized')->returns(false); + $connection->client()->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE); + ->returns(Redis::COMPRESSION_NONE); $this->assertSame(serialize('test-value'), $this->serialization->serializeForLua($connection, 'test-value')); } public function testSerializeForLuaCastsNumericValuesToString(): void { - $connection = m::mock(PhpRedisConnection::class); + $connection = $this->mockConnection(); - $connection->shouldReceive('serialized')->andReturn(false); - $connection->shouldReceive('getOption') + $connection->allows('serialized')->returns(false); + $connection->client()->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_NONE); + ->returns(Redis::COMPRESSION_NONE); // Numeric values should be cast to string for Lua ARGV $this->assertSame('123', $this->serialization->serializeForLua($connection, 123)); @@ -222,15 +221,15 @@ public function testSerializeForLuaPreservesNumericTypesForPackingWithCompressio $this->markTestSkipped('Redis::COMPRESSION_LZF not available (phpredis compiled without LZF support)'); } - $connection = m::mock(PhpRedisConnection::class); + $connection = $this->mockConnection(); - $connection->shouldReceive('serialized')->andReturn(false); - $connection->shouldReceive('getOption') + $connection->allows('serialized')->returns(false); + $connection->client()->allows('getOption') ->with(Redis::OPT_COMPRESSION) - ->andReturn(Redis::COMPRESSION_LZF); - $connection->shouldReceive('pack') + ->returns(Redis::COMPRESSION_LZF); + $connection->allows('pack') ->with([123]) - ->andReturn(['compressed-123']); + ->returns(['compressed-123']); $this->assertSame('compressed-123', $this->serialization->serializeForLua($connection, 123)); } @@ -240,8 +239,8 @@ public function testSerializeForLuaPreservesNumericTypesForPackingWithCompressio */ private function createConnection(bool $serialized = false): PhpRedisConnection { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('serialized')->andReturn($serialized); + $connection = $this->mockConnection(); + $connection->allows('serialized')->returns($serialized); return $connection; } diff --git a/tests/Cache/Redis/Support/StoreContextTest.php b/tests/Cache/Redis/Support/StoreContextTest.php index 600b560298..a68ac5245c 100644 --- a/tests/Cache/Redis/Support/StoreContextTest.php +++ b/tests/Cache/Redis/Support/StoreContextTest.php @@ -10,13 +10,17 @@ use Hypervel\Redis\PhpRedisConnection; use Hypervel\Redis\RedisProxy; use Hypervel\Support\CarbonImmutable; +use Hypervel\Tests\Redis\Fixtures\PhpRedisConnectionStub; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Redis; use RuntimeException; class StoreContextTest extends TestCase { + use VerifiesDoubles; + public function testPrefixReturnsConfiguredPrefix(): void { $context = $this->createContext(prefix: 'myapp:'); @@ -77,13 +81,13 @@ public function testExpirationScoreNeverPrecedesRequestedLifetime(): void public function testWithConnectionExecutesCallbackAndReturnsResult(): void { - $connection = m::mock(PhpRedisConnection::class); + $connection = Double::for(PhpRedisConnection::class); $context = $this->createContextWithRedisFactory('default', function ($callback) use ($connection) { return $callback($connection); }); - $result = $context->withConnection(function ($conn) use ($connection) { - $this->assertSame($connection, $conn); + $result = $context->withConnection(function ($actualConnection) use ($connection) { + $this->assertSame($connection, $actualConnection); return 'callback-result'; }); @@ -93,7 +97,7 @@ public function testWithConnectionExecutesCallbackAndReturnsResult(): void public function testWithConnectionCanEnableLaravelStyleTransforms(): void { - $connection = m::mock(PhpRedisConnection::class); + $connection = Double::for(PhpRedisConnection::class); $transform = null; $context = $this->createContextWithRedisFactory( 'default', @@ -113,7 +117,7 @@ function ($callback, bool $shouldTransform) use ($connection, &$transform) { public function testWithConnectionPropagatesExceptions(): void { $context = $this->createContextWithRedisFactory('default', function ($callback) { - return $callback(m::mock(PhpRedisConnection::class)); + return $callback(Double::for(PhpRedisConnection::class)); }); $this->expectException(RuntimeException::class); @@ -127,7 +131,7 @@ public function testWithConnectionPropagatesExceptions(): void public function testIsClusterReturnsTrueForRedisCluster(): void { $context = $this->createContextWithRedisFactory('default', function ($callback) { - return $callback(m::mock(PhpRedisConnection::class)); + return $callback(Double::for(PhpRedisConnection::class)); }, isCluster: true); $this->assertTrue($context->isCluster()); @@ -136,7 +140,7 @@ public function testIsClusterReturnsTrueForRedisCluster(): void public function testIsClusterReturnsFalseForRegularRedis(): void { $context = $this->createContextWithRedisFactory('default', function ($callback) { - return $callback(m::mock(PhpRedisConnection::class)); + return $callback(Double::for(PhpRedisConnection::class)); }, isCluster: false); $this->assertFalse($context->isCluster()); @@ -144,10 +148,11 @@ public function testIsClusterReturnsFalseForRegularRedis(): void public function testOptPrefixReturnsRedisOptionPrefix(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getOption') + $client = Double::for(Redis::class)->strict(); + $connection = (new PhpRedisConnectionStub)->setActiveConnection($client)->shouldTransform(false); + $client->allows('getOption') ->with(Redis::OPT_PREFIX) - ->andReturn('redis_prefix:'); + ->returns('redis_prefix:'); $context = $this->createContext(prefix: 'cache:'); @@ -156,10 +161,11 @@ public function testOptPrefixReturnsRedisOptionPrefix(): void public function testOptPrefixReturnsEmptyStringWhenNotSet(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getOption') + $client = Double::for(Redis::class)->strict(); + $connection = (new PhpRedisConnectionStub)->setActiveConnection($client)->shouldTransform(false); + $client->allows('getOption') ->with(Redis::OPT_PREFIX) - ->andReturn(null); + ->returns(null); $context = $this->createContext(prefix: 'cache:'); @@ -168,10 +174,11 @@ public function testOptPrefixReturnsEmptyStringWhenNotSet(): void public function testFullTagPrefixIncludesOptPrefix(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getOption') + $client = Double::for(Redis::class)->strict(); + $connection = (new PhpRedisConnectionStub)->setActiveConnection($client)->shouldTransform(false); + $client->allows('getOption') ->with(Redis::OPT_PREFIX) - ->andReturn('redis:'); + ->returns('redis:'); $context = $this->createContext(prefix: 'cache:'); @@ -180,10 +187,11 @@ public function testFullTagPrefixIncludesOptPrefix(): void public function testFullRegistryKeyIncludesOptPrefix(): void { - $connection = m::mock(PhpRedisConnection::class); - $connection->shouldReceive('getOption') + $client = Double::for(Redis::class)->strict(); + $connection = (new PhpRedisConnectionStub)->setActiveConnection($client)->shouldTransform(false); + $client->allows('getOption') ->with(Redis::OPT_PREFIX) - ->andReturn('redis:'); + ->returns('redis:'); $context = $this->createContext(prefix: 'cache:'); @@ -204,7 +212,7 @@ private function createContext( string $prefix = 'prefix:', TagMode $tagMode = TagMode::Any ): StoreContext { - return new StoreContext(m::mock(RedisFactory::class), $connectionName, $prefix, $tagMode); + return new StoreContext(Double::for(RedisFactory::class)->strict(), $connectionName, $prefix, $tagMode); } /** @@ -219,17 +227,16 @@ private function createContextWithRedisFactory( ): StoreContext { $contextConnectionName ??= $expectedConnectionName; - $redisProxy = m::mock(RedisProxy::class); - $redisProxy->shouldReceive('withConnection') - ->andReturnUsing($withConnectionHandler); - $redisProxy->shouldReceive('isCluster') - ->andReturn($isCluster) - ->byDefault(); + $redisProxy = Double::for(RedisProxy::class)->strict(); + $redisProxy->allows('withConnection') + ->resolves($withConnectionHandler); + $redisProxy->allows('isCluster') + ->returns($isCluster); - $redisFactory = m::mock(RedisFactory::class); - $redisFactory->shouldReceive('connection') + $redisFactory = Double::for(RedisFactory::class)->strict(); + $redisFactory->allows('connection') ->with($expectedConnectionName) - ->andReturn($redisProxy); + ->returns($redisProxy); return new StoreContext($redisFactory, $contextConnectionName, $prefix, TagMode::Any); } diff --git a/tests/Console/Scheduling/CallbackEventTest.php b/tests/Console/Scheduling/CallbackEventTest.php index 22ca18fe4c..5f00a0057b 100644 --- a/tests/Console/Scheduling/CallbackEventTest.php +++ b/tests/Console/Scheduling/CallbackEventTest.php @@ -10,9 +10,10 @@ use Hypervel\Engine\Channel; use Hypervel\Testbench\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; -use Mockery\MockInterface; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -22,13 +23,15 @@ class CallbackEventTest extends TestCase { - protected EventMutex&MockInterface $mutex; + use VerifiesDoubles; + + protected EventMutex&DoubleInterface $mutex; protected function setUp(): void { parent::setUp(); - $this->mutex = m::mock(EventMutex::class); + $this->mutex = Double::for(EventMutex::class)->strict(); $this->app->instance(EventMutex::class, $this->mutex); } @@ -98,7 +101,7 @@ public function testWithoutOverlappingThrowsWhenNoDescription(): void public function testWithoutOverlappingSucceedsWithDescription(): void { - $this->mutex->shouldReceive('exists')->andReturn(false); + $this->mutex->allows('exists')->returns(false); $event = new CallbackEvent($this->mutex, fn () => true); $event->name('test-event'); @@ -167,7 +170,7 @@ public function testMutexNameWithoutDescription(): void public function testShouldSkipDueToOverlappingReturnsFalseWithoutDescription(): void { - $this->mutex->shouldReceive('create')->never(); + $this->mutex->expects('create')->never(); $event = new CallbackEvent($this->mutex, fn () => true); $event->withoutOverlapping = true; @@ -177,7 +180,7 @@ public function testShouldSkipDueToOverlappingReturnsFalseWithoutDescription(): public function testShouldSkipDueToOverlappingChecksWhenDescriptionSet(): void { - $this->mutex->shouldReceive('create')->once()->andReturn(false); + $this->mutex->expects('create')->returns(false); $event = new CallbackEvent($this->mutex, fn () => true); $event->name('test-event'); diff --git a/tests/Console/Scheduling/ScheduleRunCommandTest.php b/tests/Console/Scheduling/ScheduleRunCommandTest.php index b3d91ec17f..115e9dff60 100644 --- a/tests/Console/Scheduling/ScheduleRunCommandTest.php +++ b/tests/Console/Scheduling/ScheduleRunCommandTest.php @@ -39,7 +39,9 @@ use Hypervel\Support\Facades\Event as EventFacade; use Hypervel\Support\Sleep; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionMethod; @@ -58,6 +60,8 @@ class ScheduleRunCommandTest extends TestCase { + use VerifiesDoubles; + protected array $dispatched; protected Dispatcher $dispatcher; @@ -70,23 +74,22 @@ protected function setUp(): void $this->dispatched = []; - $this->dispatcher = m::mock(Dispatcher::class); - $this->dispatcher->shouldReceive('hasListeners') - ->byDefault() - ->andReturnTrue(); - $this->dispatcher->shouldReceive('dispatch') - ->andReturnUsing(function ($event) { + $this->dispatcher = Double::for(Dispatcher::class); + $this->dispatcher->allows('hasListeners') + ->returns(true); + $this->dispatcher->allows('dispatch') + ->resolves(function ($event) { $this->dispatched[] = $event; }); - $this->handler = m::mock(ExceptionHandler::class); + $this->handler = Double::for(ExceptionHandler::class)->strict(); } public function testForegroundCallbackDispatchesStartingAndFinishedEvents(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); $callbackEvent = new CallbackEvent($eventMutex, function () { return 0; @@ -124,7 +127,7 @@ public function testScheduledCommandDefersNestedCommandWorkUntilTheTaskFinishes( $this->call('test:deferred-child'); $calls[] = 'parent finished'; }); - $event = new Event(m::mock(EventMutex::class), 'test:deferred-parent'); + $event = new Event(Double::for(EventMutex::class), 'test:deferred-parent'); $event->after(function () use (&$calls): void { $calls[] = 'after'; }); @@ -147,7 +150,7 @@ public function testDeferredCallbacksRespectTheWholeTaskOutcome(string $outcome, { $calls = []; $exception = new RuntimeException('Task failed'); - $event = new CallbackEvent(m::mock(EventMutex::class), function () use (&$calls, $outcome, $exception): bool { + $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls, $outcome, $exception): bool { defer(function () use (&$calls): void { $calls[] = 'ordinary'; }); @@ -167,9 +170,9 @@ public function testDeferredCallbacksRespectTheWholeTaskOutcome(string $outcome, }); } if ($outcome !== 'success') { - $this->handler->shouldReceive('report')->once(); + $this->handler->expects('report'); } - $nextEvent = new CallbackEvent(m::mock(EventMutex::class), function () use (&$calls): void { + $nextEvent = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls): void { defer(function () use (&$calls): void { $calls[] = 'next task'; }); @@ -200,10 +203,10 @@ public function testCanceledCallbackReleasesItsMutexAndPublishesOnlyTheCancellat $calls = []; $cancellation = new CanceledException('Task canceled'); $cleanup = $cleanupThrows ? new RuntimeException('Task cleanup failed.') : null; - $mutex = m::mock(EventMutex::class); - $mutex->shouldReceive('exists')->once()->andReturnFalse(); - $mutex->shouldReceive('create')->once()->andReturnTrue(); - $mutex->shouldReceive('forget')->once(); + $mutex = Double::for(EventMutex::class); + $mutex->expects('exists')->returns(false); + $mutex->expects('create')->returns(true); + $mutex->expects('forget'); $event = new CallbackEvent($mutex, function () use (&$calls, $cancellation, $cleanup): void { defer(function () use (&$calls): void { $calls[] = 'always'; @@ -220,7 +223,7 @@ public function testCanceledCallbackReleasesItsMutexAndPublishesOnlyTheCancellat $event->name('canceled')->withoutOverlapping()->onFailure(function () use (&$calls): void { $calls[] = 'failure'; }); - $this->handler->shouldNotReceive('report'); + $this->handler->expects('report')->never(); try { $this->invokeRunEvents($this->makeCommand(), [$event]); @@ -257,7 +260,7 @@ public function testStartingListenerFailureIsPublishedWithoutARuntimeAndRunsOnly $this->dispatcher->listen(ScheduledTaskFailed::class, function (ScheduledTaskFailed $event) use (&$failed): void { $failed[] = $event; }); - $event = new CallbackEvent(m::mock(EventMutex::class), static fn (): bool => true); + $event = new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true); $caught = null; try { @@ -279,9 +282,9 @@ public function testPreRunCancellationIsPublishedWithAnyEarlierFailure(bool $aft { $cancellation = new CanceledException; $failure = $afterFailure ? new RuntimeException('Starting listener failed') : null; - $this->dispatcher = m::mock(Dispatcher::class); - $this->dispatcher->shouldReceive('hasListeners')->andReturnTrue(); - $this->dispatcher->shouldReceive('dispatch')->andReturnUsing(function (object $event) use ($cancellation, $failure): void { + $this->dispatcher = Double::for(Dispatcher::class); + $this->dispatcher->allows('hasListeners')->returns(true); + $this->dispatcher->allows('dispatch')->resolves(function (object $event) use ($cancellation, $failure): void { $this->dispatched[] = $event; if ($event instanceof ScheduledTaskStarting) { @@ -292,10 +295,10 @@ public function testPreRunCancellationIsPublishedWithAnyEarlierFailure(bool $aft throw $cancellation; } }); - $this->handler->shouldNotReceive('report'); + $this->handler->expects('report')->never(); try { - $this->invokeRunEvents($this->makeCommand(), [new CallbackEvent(m::mock(EventMutex::class), static fn (): bool => true)]); + $this->invokeRunEvents($this->makeCommand(), [new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true)]); $this->fail('Expected the owned task to report cancellation.'); } catch (ChildCancellationException $exception) { $this->assertSame($cancellation, $exception->getPrevious()); @@ -314,16 +317,16 @@ public function testCanceledListenerFailureIsReportedWithoutReplacingTheCancella { $cancellation = new CanceledException; $listenerFailure = new RuntimeException('Canceled listener failed'); - $this->dispatcher = m::mock(Dispatcher::class); - $this->dispatcher->shouldReceive('hasListeners')->andReturnTrue(); - $this->dispatcher->shouldReceive('dispatch')->andReturnUsing(function (object $event) use ($cancellation, $listenerFailure): void { + $this->dispatcher = Double::for(Dispatcher::class); + $this->dispatcher->allows('hasListeners')->returns(true); + $this->dispatcher->allows('dispatch')->resolves(function (object $event) use ($cancellation, $listenerFailure): void { throw $event instanceof ScheduledTaskStarting ? $cancellation : $listenerFailure; }); $this->app->instance(ExceptionHandler::class, $this->handler); - $this->handler->shouldReceive('report')->once()->with($listenerFailure); + $this->handler->expects('report')->with($listenerFailure); try { - $this->invokeRunEvents($this->makeCommand(), [new CallbackEvent(m::mock(EventMutex::class), static fn (): bool => true)]); + $this->invokeRunEvents($this->makeCommand(), [new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true)]); $this->fail('Expected the owned task to report cancellation.'); } catch (ChildCancellationException $exception) { $this->assertSame($cancellation, $exception->getPrevious()); @@ -337,7 +340,7 @@ public function testCancellationDuringDeferredWorkStopsTheRemainingCallbacks(boo $calls = []; $cancellation = new CanceledException('Deferred work canceled'); $cleanup = $cleanupThrows ? new RuntimeException('Deferred cleanup failed.') : null; - $event = new CallbackEvent(m::mock(EventMutex::class), function () use (&$calls, $cancellation, $cleanup): void { + $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls, $cancellation, $cleanup): void { defer(function () use ($cancellation, $cleanup): void { try { throw $cancellation; @@ -386,7 +389,7 @@ public function testDeferredCancellationSupersedesAnEarlierTaskFailure(bool $cle throw new RuntimeException('Starting listener failed.'); }); - $event = new CallbackEvent(m::mock(EventMutex::class), static fn (): bool => true); + $event = new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true); try { $this->invokeRunEvents($this->makeCommand(), [$event]); @@ -414,7 +417,7 @@ public function testBackgroundTaskDrainsItsCallbacksAfterBackgroundFinishedListe $calls[] = 'deferred listener'; }); }); - $event = new Event(m::mock(EventMutex::class), 'test:background-defer'); + $event = new Event(Double::for(EventMutex::class), 'test:background-defer'); $event->runInBackground(); $command = $this->makeCommand(); $concurrent = new Concurrent(1); @@ -432,20 +435,20 @@ public function testBackgroundTaskDrainsItsCallbacksAfterBackgroundFinishedListe #[DataProvider('skippedBackgroundTasks')] public function testSkippedBackgroundTaskDoesNotDispatchCompletion(bool $onAnotherServer): void { - $mutex = m::mock(EventMutex::class); + $mutex = Double::for(EventMutex::class); $event = new Event($mutex, 'test:skipped-background'); $event->runInBackground(); $command = $this->makeCommand(); $output = $this->captureOutput($command); if ($onAnotherServer) { $event->onOneServer(); - $schedule = m::mock(Schedule::class); - $schedule->shouldReceive('serverShouldRun')->once()->with($event, m::type(CarbonInterface::class))->andReturnFalse(); + $schedule = Double::for(Schedule::class); + $schedule->expects('serverShouldRun')->with($event, Argument::type(CarbonInterface::class))->returns(false); (new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule); } else { $event->withoutOverlapping(); - $mutex->shouldReceive('exists')->once()->andReturnFalse(); - $mutex->shouldReceive('create')->once()->andReturnFalse(); + $mutex->expects('exists')->returns(false); + $mutex->expects('create')->returns(false); } $concurrent = new Concurrent(1); (new ReflectionProperty($command, 'concurrent'))->setValue($command, $concurrent); @@ -479,7 +482,7 @@ public static function skippedBackgroundTasks(): array public function testFinishedOutputUsesTheSharedRuntimeFormatterWithoutAppendingUnits(): void { - $event = new ScheduleRunExitCodeEvent(m::mock(EventMutex::class), 0, 'test:duration'); + $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 0, 'test:duration'); $command = $this->makeCommand(command: new ScheduleRunCommandWithFixedRuntime); $output = $this->captureOutput($command); @@ -502,7 +505,7 @@ public function testForegroundTaskEvaluationsUseFiniteCoroutinesWithSelectedLogC $events = []; foreach (['first', 'second'] as $name) { - $event = new CallbackEvent(m::mock(EventMutex::class), function () use (&$observations, &$deferred, $name): int { + $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$observations, &$deferred, $name): int { $observations[$name]['run'] = [Coroutine::getCid(), count($deferred)]; return 0; @@ -549,7 +552,7 @@ public function testRunOncePreservesLogContextAcrossItsOuterCoroutine(): void { ContextRepository::getInstance()->add('trace_id', 'parent-trace'); $observedTraceId = null; - $event = new CallbackEvent(m::mock(EventMutex::class), function () use (&$observedTraceId): int { + $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$observedTraceId): int { $context = CoroutineContext::get(ContextRepository::CONTEXT_KEY); $observedTraceId = $context instanceof ContextRepository ? $context->get('trace_id') @@ -558,11 +561,10 @@ public function testRunOncePreservesLogContextAcrossItsOuterCoroutine(): void return 0; }); - $schedule = m::mock(Schedule::class); - $schedule->shouldReceive('dueEventsAt') - ->once() - ->with($this->app, m::type(CarbonInterface::class)) - ->andReturn(new Collection([$event])); + $schedule = Double::for(Schedule::class); + $schedule->expects('dueEventsAt') + ->with($this->app, Argument::type(CarbonInterface::class)) + ->returns(new Collection([$event])); $command = $this->makeCommand(); (new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule); @@ -577,20 +579,21 @@ public function testRunOncePreservesLogContextAcrossItsOuterCoroutine(): void public function testTaskLifecycleEventsAreNotDispatchedWithoutListeners(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturnTrue(); - $eventMutex->shouldReceive('forget'); + $this->dispatcher = Double::for(Dispatcher::class)->strict(); + $this->dispatcher->expects('dispatch')->never(); + + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); $callbackEvent = new CallbackEvent($eventMutex, fn (): int => 0); - $this->dispatcher->shouldReceive('hasListeners') - ->once() + $this->dispatcher->expects('hasListeners') ->with(ScheduledTaskStarting::class) - ->andReturnFalse(); - $this->dispatcher->shouldReceive('hasListeners') - ->once() + ->returns(false); + $this->dispatcher->expects('hasListeners') ->with(ScheduledTaskFinished::class) - ->andReturnFalse(); + ->returns(false); $command = $this->makeCommand(); $this->invokeRunEvents($command, [$callbackEvent]); @@ -605,9 +608,9 @@ public function testTaskLifecycleEventsRemainVisibleToEventFakes(): void ScheduledTaskFinished::class, ]); - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturnTrue(); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); $callbackEvent = new CallbackEvent($eventMutex, fn (): int => 0); @@ -622,13 +625,13 @@ public function testTaskLifecycleEventsRemainVisibleToEventFakes(): void public function testBackgroundTaskDispatchesAllThreeEvents(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); // Use a partial mock of Event so run() succeeds without executing a real command - $event = m::mock(Event::class, [$eventMutex, 'test:background', null, false])->makePartial(); - $event->shouldReceive('run')->once(); + $event = Double::for(new Event($eventMutex, 'test:background', null, false))->passthru(); + $event->expects('run'); $event->runInBackground(); $command = $this->makeCommand(); @@ -650,16 +653,16 @@ public function testBackgroundTaskDispatchesAllThreeEvents(): void public function testBackgroundTaskStillDispatchesBackgroundFinishedOnFailure(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); $exception = new RuntimeException('Task exploded'); - $event = m::mock(Event::class, [$eventMutex, 'test:failing', null, false])->makePartial(); - $event->shouldReceive('run')->once()->andThrow($exception); + $event = Double::for(new Event($eventMutex, 'test:failing', null, false))->passthru(); + $event->expects('run')->throws($exception); $event->runInBackground(); - $this->handler->shouldReceive('report')->once()->with($exception); + $this->handler->expects('report')->with($exception); $command = $this->makeCommand(); $concurrent = new Concurrent(10); @@ -680,11 +683,11 @@ public function testBackgroundTaskStillDispatchesBackgroundFinishedOnFailure(): public function testThrownRunIsRenderedAsFailedWhenTheEventRetainsAZeroExitCode(): void { $exception = new RuntimeException('Task exploded after an earlier successful run.'); - $event = m::mock(Event::class, [m::mock(EventMutex::class), 'test:stale-exit', null, false])->makePartial(); + $event = Double::for(new Event(Double::for(EventMutex::class), 'test:stale-exit', null, false))->passthru(); $event->finish($this->app, 0); - $event->shouldReceive('run')->once()->andThrow($exception); + $event->expects('run')->throws($exception); - $this->handler->shouldReceive('report')->once()->with($exception); + $this->handler->expects('report')->with($exception); $command = $this->makeCommand(); $output = $this->captureOutput($command); @@ -708,9 +711,9 @@ public function testFinishedListenerFailureIsRenderedAsFailed(): void }); $this->dispatcher = $dispatcher; - $this->handler->shouldReceive('report')->once()->with($exception); + $this->handler->expects('report')->with($exception); - $event = new ScheduleRunExitCodeEvent(m::mock(EventMutex::class), 0, 'test:listener-failure'); + $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 0, 'test:listener-failure'); $command = $this->makeCommand(); $output = $this->captureOutput($command); @@ -726,12 +729,11 @@ public function testFinishedListenerFailureIsRenderedAsFailed(): void public function testNonZeroExitDispatchesAndReportsFailure(): void { - $this->handler->shouldReceive('report') - ->once() - ->with(m::on(fn (Throwable $throwable): bool => $throwable instanceof RuntimeException + $this->handler->expects('report') + ->with(Argument::satisfies(fn (Throwable $throwable): bool => $throwable instanceof RuntimeException && $throwable->getMessage() === 'Scheduled command [test:non-zero] failed with exit code [1].')); - $event = new ScheduleRunExitCodeEvent(m::mock(EventMutex::class), 1, 'test:non-zero'); + $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 1, 'test:non-zero'); $command = $this->makeCommand(); $output = $this->captureOutput($command); @@ -764,12 +766,12 @@ public function testFailureAfterTheTaskFinishesReportsTheTaskRuntime(): void }); $this->dispatcher = $dispatcher; - $this->handler->shouldReceive('report')->once(); + $this->handler->expects('report'); $command = $this->makeCommand(); $this->captureOutput($command); - $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(m::mock(EventMutex::class), 1, 'test:slow-listener')); + $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 1, 'test:slow-listener')); $this->assertInstanceOf(ScheduledTaskFinished::class, $finishedEvent); $this->assertInstanceOf(ScheduledTaskFailed::class, $failedEvent); @@ -779,7 +781,7 @@ public function testFailureAfterTheTaskFinishesReportsTheTaskRuntime(): void public function testDurationHandlerReportsAFailingCommandOnce(): void { $this->dispatcher = $this->app->make(Dispatcher::class); - $this->handler->shouldReceive('report')->once(); + $this->handler->expects('report'); $runtimes = []; @@ -791,7 +793,7 @@ public function testDurationHandlerReportsAFailingCommandOnce(): void $command = $this->makeCommand(); $this->captureOutput($command); - $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(m::mock(EventMutex::class), 1, 'test:slow-failure')); + $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 1, 'test:slow-failure')); $this->assertCount(1, $runtimes); } @@ -800,7 +802,7 @@ public function testDurationHandlerThatThrowsIsNotCalledAgainForTheFailedEvent() { $exception = new RuntimeException('Alert transport failed.'); $this->dispatcher = $this->app->make(Dispatcher::class); - $this->handler->shouldReceive('report')->once()->with($exception); + $this->handler->expects('report')->with($exception); $schedule = new Schedule; $throwingCalls = 0; @@ -819,7 +821,7 @@ public function testDurationHandlerThatThrowsIsNotCalledAgainForTheFailedEvent() $command = $this->makeCommand(); $this->captureOutput($command); - $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(m::mock(EventMutex::class), 0, 'test:throwing-handler')); + $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 0, 'test:throwing-handler')); $this->assertSame(1, $throwingCalls); @@ -829,12 +831,11 @@ public function testDurationHandlerThatThrowsIsNotCalledAgainForTheFailedEvent() public function testBackgroundNonZeroExitDispatchesAndReportsFailureBeforeBackgroundCompletion(): void { - $this->handler->shouldReceive('report') - ->once() - ->with(m::on(fn (Throwable $throwable): bool => $throwable instanceof RuntimeException + $this->handler->expects('report') + ->with(Argument::satisfies(fn (Throwable $throwable): bool => $throwable instanceof RuntimeException && $throwable->getMessage() === 'Scheduled command [test:background-non-zero] failed with exit code [1].')); - $event = new ScheduleRunExitCodeEvent(m::mock(EventMutex::class), 1, 'test:background-non-zero'); + $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 1, 'test:background-non-zero'); $event->runInBackground(); $command = $this->makeCommand(); @@ -855,14 +856,14 @@ public function testBackgroundNonZeroExitDispatchesAndReportsFailureBeforeBackgr public function testOverlapSkipDoesNotReportThePreviousNonZeroExitAgain(): void { - $mutex = m::mock(EventMutex::class); - $mutex->shouldReceive('create')->once()->andReturnFalse(); + $mutex = Double::for(EventMutex::class); + $mutex->expects('create')->returns(false); $event = new ScheduleRunExitCodeEvent($mutex, 1, 'test:overlap-skip'); $event->finish($this->app, 1); $event->withoutOverlapping(); - $this->handler->shouldNotReceive('report'); + $this->handler->expects('report')->never(); $command = $this->makeCommand(); $output = $this->captureOutput($command); @@ -896,9 +897,8 @@ public function testConcurrentOverlapSkipDoesNotHideTheRunningEventsNonZeroFailu ); $event->withoutOverlapping()->everySecond()->runInBackground(); - $this->handler->shouldReceive('report') - ->once() - ->with(m::on(fn (Throwable $throwable): bool => $throwable instanceof RuntimeException + $this->handler->expects('report') + ->with(Argument::satisfies(fn (Throwable $throwable): bool => $throwable instanceof RuntimeException && $throwable->getMessage() === 'Scheduled command [test:concurrent-overlap] failed with exit code [1].')); $command = $this->makeCommand(); @@ -934,27 +934,27 @@ public function testConcurrentOverlapSkipDoesNotHideTheRunningEventsNonZeroFailu public function testBackgroundFinishedEventIsNotDispatchedWithoutListeners(): void { - $eventMutex = m::mock(EventMutex::class); + $this->dispatcher = Double::for(Dispatcher::class)->strict(); + $this->dispatcher->expects('dispatch')->never(); - $event = m::mock(Event::class, [$eventMutex, 'test:background', null, false])->makePartial(); - $event->shouldReceive('run')->once(); + $eventMutex = Double::for(EventMutex::class); + + $event = Double::for(new Event($eventMutex, 'test:background', null, false))->passthru(); + $event->expects('run'); $event->runInBackground(); - $this->dispatcher->shouldReceive('hasListeners') - ->once() + $this->dispatcher->expects('hasListeners') ->with(ScheduledTaskStarting::class) - ->andReturnFalse(); - $this->dispatcher->shouldReceive('hasListeners') - ->once() + ->returns(false); + $this->dispatcher->expects('hasListeners') ->with(ScheduledTaskFinished::class) - ->andReturnFalse(); - $this->dispatcher->shouldReceive('hasListeners') - ->once() + ->returns(false); + $this->dispatcher->expects('hasListeners') ->with(ScheduledBackgroundTaskFinished::class) - ->andReturnFalse(); + ->returns(false); $command = $this->makeCommand(); - $concurrent = new \Hypervel\Coroutine\Concurrent(10); + $concurrent = new Concurrent(10); (new ReflectionProperty($command, 'concurrent'))->setValue($command, $concurrent); $this->invokeRunEvents($command, [$event]); @@ -967,7 +967,7 @@ public function testBackgroundFinishedEventIsNotDispatchedWithoutListeners(): vo public function testSkippedNonRepeatableTaskIsOnlyEvaluatedOncePerMinute(): void { $deferred = []; - $eventMutex = m::mock(EventMutex::class); + $eventMutex = Double::for(EventMutex::class); $callbackEvent = new CallbackEvent($eventMutex, function () { return 0; @@ -994,17 +994,19 @@ public function testSkippedNonRepeatableTaskIsOnlyEvaluatedOncePerMinute(): void public function testSkippedTaskEventIsGuardedByRegisteredListeners(): void { - $eventMutex = m::mock(EventMutex::class); + $this->dispatcher = Double::for(Dispatcher::class)->strict(); + $this->dispatcher->expects('dispatch')->never(); + + $eventMutex = Double::for(EventMutex::class); $callbackEvent = new CallbackEvent($eventMutex, function () { return 0; }); $callbackEvent->when(false); - $this->dispatcher->shouldReceive('hasListeners') - ->once() + $this->dispatcher->expects('hasListeners') ->with(ScheduledTaskSkipped::class) - ->andReturnFalse(); + ->returns(false); $command = $this->makeCommand(); $this->invokeRunEvents($command, [$callbackEvent]); @@ -1014,18 +1016,17 @@ public function testSkippedTaskEventIsGuardedByRegisteredListeners(): void public function testPausedTaskIsSkippedWithoutRunningFilters(): void { - $eventMutex = m::mock(EventMutex::class); + $eventMutex = Double::for(EventMutex::class); - $callbackEvent = m::mock(CallbackEvent::class, [$eventMutex, function () { + $callbackEvent = Double::for(new CallbackEvent($eventMutex, function () { return 0; - }])->makePartial(); - $callbackEvent->shouldReceive('filtersPass')->never(); + }))->passthru(); + $callbackEvent->expects('filtersPass')->never(); - $cache = m::mock(Cache::class); - $cache->shouldReceive('get') - ->once() + $cache = Double::for(Cache::class); + $cache->expects('get') ->with('hypervel:schedule:paused', false) - ->andReturnTrue(); + ->returns(true); $command = $this->makeCommand($cache); $this->invokeRunEvents($command, [$callbackEvent]); @@ -1047,9 +1048,9 @@ public function testPausedTaskListenerDefersWorkWithinItsOwnCoroutine(): void $calls[] = 'deferred'; }); }); - $cache = m::mock(Cache::class); - $cache->shouldReceive('get')->once()->with('hypervel:schedule:paused', false)->andReturnTrue(); - $event = new CallbackEvent(m::mock(EventMutex::class), static fn (): bool => true); + $cache = Double::for(Cache::class); + $cache->expects('get')->with('hypervel:schedule:paused', false)->returns(true); + $event = new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true); $this->invokeRunEvents($this->makeCommand($cache), [$event]); @@ -1062,9 +1063,9 @@ public function testTaskMarkedEvenWhenPausedRunsWhileSchedulerIsPaused(): void { $runCount = 0; - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); $callbackEvent = new CallbackEvent($eventMutex, function () use (&$runCount) { ++$runCount; @@ -1073,11 +1074,10 @@ public function testTaskMarkedEvenWhenPausedRunsWhileSchedulerIsPaused(): void }); $callbackEvent->evenWhenPaused(); - $cache = m::mock(Cache::class); - $cache->shouldReceive('get') - ->once() + $cache = Double::for(Cache::class); + $cache->expects('get') ->with('hypervel:schedule:paused', false) - ->andReturnTrue(); + ->returns(true); $command = $this->makeCommand($cache); $this->invokeRunEvents($command, [$callbackEvent]); @@ -1090,17 +1090,16 @@ public function testTaskMarkedEvenWhenPausedRunsWhileSchedulerIsPaused(): void public function testPausedNonRepeatableTaskIsOnlyEvaluatedOncePerMinute(): void { - $eventMutex = m::mock(EventMutex::class); + $eventMutex = Double::for(EventMutex::class); $callbackEvent = new CallbackEvent($eventMutex, function () { return 0; }); - $cache = m::mock(Cache::class); - $cache->shouldReceive('get') - ->once() + $cache = Double::for(Cache::class); + $cache->expects('get') ->with('hypervel:schedule:paused', false) - ->andReturnTrue(); + ->returns(true); $command = $this->makeCommand($cache); $startedAt = CarbonImmutable::parse('2026-05-28 12:34:00'); @@ -1119,9 +1118,9 @@ public function testPauseAndInterruptChecksDoNotReadTheCacheWhenPollingIsDisable $runCount = 0; - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); $callbackEvent = new CallbackEvent($eventMutex, function () use (&$runCount): int { ++$runCount; @@ -1129,8 +1128,8 @@ public function testPauseAndInterruptChecksDoNotReadTheCacheWhenPollingIsDisable return 0; }); - $cache = m::mock(Cache::class); - $cache->shouldReceive('get')->never(); + $cache = Double::for(Cache::class); + $cache->expects('get')->never(); $command = $this->makeCommand($cache); $this->invokeRunEvents($command, [$callbackEvent]); @@ -1146,9 +1145,9 @@ public function testNonRepeatableEventOnlyRunsOncePerMinute(): void { $runCount = 0; - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); $callbackEvent = new CallbackEvent($eventMutex, function () use (&$runCount) { ++$runCount; @@ -1173,9 +1172,9 @@ public function testRepeatableEventIsThrottledByLastChecked(): void { $runCount = 0; - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); $callbackEvent = new CallbackEvent($eventMutex, function () use (&$runCount) { ++$runCount; @@ -1198,18 +1197,16 @@ public function testRepeatableEventIsThrottledByLastChecked(): void public function testSingleServerEventClaimedElsewhereDoesNotReportThatNoCommandsWereReady(): void { - $event = new Event(m::mock(EventMutex::class), 'test:single-server'); + $event = new Event(Double::for(EventMutex::class), 'test:single-server'); $event->onOneServer(); - $schedule = m::mock(Schedule::class); - $schedule->shouldReceive('dueEventsAt') - ->once() - ->with($this->app, m::type(CarbonInterface::class)) - ->andReturn(new Collection([$event])); - $schedule->shouldReceive('serverShouldRun') - ->once() - ->with($event, m::type(CarbonInterface::class)) - ->andReturnFalse(); + $schedule = Double::for(Schedule::class); + $schedule->expects('dueEventsAt') + ->with($this->app, Argument::type(CarbonInterface::class)) + ->returns(new Collection([$event])); + $schedule->expects('serverShouldRun') + ->with($event, Argument::type(CarbonInterface::class)) + ->returns(false); $command = $this->makeCommand(); (new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule); @@ -1237,7 +1234,7 @@ public function testRepeatEventsPreservesOriginalStartForSingleServerMutex(strin $startedAt = Date::now()->startOfMinute(); $expectedStartedAt = $startedAt->format('Y-m-d H:i:s'); - $eventMutex = m::mock(EventMutex::class); + $eventMutex = Double::for(EventMutex::class); $callbackEvent = new CallbackEvent($eventMutex, function () use ($startedAt): int { Date::setTestNow($startedAt->copy()->addMinute()); @@ -1247,16 +1244,15 @@ public function testRepeatEventsPreservesOriginalStartForSingleServerMutex(strin $callbackEvent->repeatSeconds = 1; $callbackEvent->lastChecked = $startedAt->copy()->subSecond(); - $schedule = m::mock(Schedule::class); - $schedule->shouldReceive('serverShouldRun') - ->once() - ->withArgs(function (Event $event, CarbonInterface $time) use ($callbackEvent, $expectedStartedAt): bool { + $schedule = Double::for(Schedule::class); + $schedule->expects('serverShouldRun') + ->with(Argument::all(function (Event $event, CarbonInterface $time) use ($callbackEvent, $expectedStartedAt): bool { $this->assertSame($callbackEvent, $event); $this->assertSame($expectedStartedAt, $time->format('Y-m-d H:i:s')); return true; - }) - ->andReturnTrue(); + })) + ->returns(true); $command = $this->makeCommand(); (new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule); @@ -1285,11 +1281,9 @@ public function testRepeatEventsUseTheBackgroundDispatchPath(): void Date::setTestNow('2026-05-28 12:34:00'); $startedAt = Date::now()->startOfMinute(); - $event = m::mock(Event::class, [m::mock(EventMutex::class), 'test:repeating-background', null, false]) - ->makePartial(); - $event->shouldReceive('run') - ->once() - ->andReturnUsing(function () use ($startedAt): void { + $event = Double::for(new Event(Double::for(EventMutex::class), 'test:repeating-background', null, false))->passthru(); + $event->expects('run') + ->resolves(function () use ($startedAt): void { Date::setTestNow($startedAt->addMinute()); }); $event->repeatSeconds = 1; @@ -1315,7 +1309,7 @@ public function testRepeatEventsUseTheBackgroundDispatchPath(): void public function testConcurrentFinishesUseRunLocalExitCodeForSuccessAndFailureCallbacks(): void { - $eventMutex = m::mock(EventMutex::class); + $eventMutex = Double::for(EventMutex::class); $event = new Event($eventMutex, 'test:overlap'); $channel = new Channel(2); @@ -1386,10 +1380,10 @@ public function testInFlightExecutionsFinishBeforeTheWorkerQuits(): void $finished = true; }); $event = (new Event($mutex, 'test:shutdown-drain'))->withoutOverlapping()->runInBackground(); - $schedule = m::mock(Schedule::class); - $schedule->expects('dueEventsAt')->andReturn(new Collection([$event])); - $cache = m::mock(Cache::class); - $cache->shouldNotReceive('get'); + $schedule = Double::for(Schedule::class); + $schedule->expects('dueEventsAt')->returns(new Collection([$event])); + $cache = Double::for(Cache::class); + $cache->expects('get')->never(); $command = $this->makeCommand($cache); $command->setInput(new ArrayInput([], $command->getDefinition())); $this->captureOutput($command); @@ -1425,7 +1419,7 @@ public function testNoNewExecutionsAreStartedAfterAStopSignal(string $phase): vo $command = $this->makeCommand(); (new ReflectionMethod($command, 'listenForSignals'))->invoke($command); $calls = []; - $event = new CallbackEvent(m::mock(EventMutex::class), function () use (&$calls, $phase, $signal): void { + $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls, $phase, $signal): void { $calls[] = 'first'; if ($phase === 'foreground task') { $signal(SIGTERM); @@ -1438,8 +1432,8 @@ public function testNoNewExecutionsAreStartedAfterAStopSignal(string $phase): vo return true; }); - $schedule = m::mock(Schedule::class); - $schedule->shouldReceive('serverShouldRun')->times($phase === 'filter' ? 0 : 1)->andReturnUsing(function () use ($phase, $signal): bool { + $schedule = Double::for(Schedule::class); + $schedule->expects('serverShouldRun')->times($phase === 'filter' ? 0 : 1)->resolves(function () use ($phase, $signal): bool { if ($phase === 'server claim') { $signal(SIGTERM); } @@ -1447,7 +1441,7 @@ public function testNoNewExecutionsAreStartedAfterAStopSignal(string $phase): vo return true; }); (new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule); - $next = new CallbackEvent(m::mock(EventMutex::class), function () use (&$calls): void { + $next = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls): void { $calls[] = 'second'; }); $next->when(function () use (&$calls): bool { @@ -1489,15 +1483,15 @@ public function testBackgroundTaskWaitingForCapacityDoesNotStartAfterShutdown(): throw new RuntimeException('The running task was not released.'); } }); - $first = (new Event(m::mock(EventMutex::class), 'test:occupy-slot'))->runInBackground(); - $second = (new Event(m::mock(EventMutex::class), 'test:must-not-run'))->runInBackground()->onOneServer(); + $first = (new Event(Double::for(EventMutex::class), 'test:occupy-slot'))->runInBackground(); + $second = (new Event(Double::for(EventMutex::class), 'test:must-not-run'))->runInBackground()->onOneServer(); $second->when(function () use ($waiting): bool { $waiting->push(true, 5.0); return true; }); - $schedule = m::mock(Schedule::class); - $schedule->shouldNotReceive('serverShouldRun'); + $schedule = Double::for(Schedule::class); + $schedule->expects('serverShouldRun')->never(); (new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule); try { @@ -1559,9 +1553,9 @@ protected function releaseRunningEventMutexes(): void public function testSignalCleanupReleasesMutexesForRunningOwnedEvents(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->once()->andReturnTrue(); - $eventMutex->shouldReceive('forget')->once(); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->expects('create')->returns(true); + $eventMutex->expects('forget'); $event = new Event($eventMutex, 'test:overlap'); $event->withoutOverlapping(); @@ -1579,8 +1573,8 @@ public function testSignalCleanupReleasesMutexesForRunningOwnedEvents(): void public function testSignalCleanupDoesNotReleaseMutexesForEventsWithoutOwnedMutexes(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldNotReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->expects('forget')->never(); $event = new Event($eventMutex, 'test:overlap'); $event->withoutOverlapping(); @@ -1596,9 +1590,9 @@ public function testSignalCleanupDoesNotReleaseMutexesForEventsWithoutOwnedMutex public function testSignalCleanupHonorsReleaseOnTerminationSignalsFlag(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->once()->andReturnTrue(); - $eventMutex->shouldNotReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->expects('create')->returns(true); + $eventMutex->expects('forget')->never(); $event = new Event($eventMutex, 'test:overlap'); $event->withoutOverlapping(releaseOnTerminationSignals: false); @@ -1616,9 +1610,9 @@ public function testSignalCleanupHonorsReleaseOnTerminationSignalsFlag(): void public function testRunningEventIsRetainedUntilEveryOverlappingInvocationFinishes(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->once()->andReturnTrue(); - $eventMutex->shouldReceive('forget')->once(); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->expects('create')->returns(true); + $eventMutex->expects('forget'); $event = new Event($eventMutex, 'test:overlap'); $event->withoutOverlapping(); @@ -1646,15 +1640,15 @@ public function testRunningEventIsRetainedUntilEveryOverlappingInvocationFinishe public function testRunningEventIsForgottenWhenEventThrows(): void { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); $exception = new RuntimeException('Task exploded'); - $event = m::mock(Event::class, [$eventMutex, 'test:failing', null, false])->makePartial(); - $event->shouldReceive('run')->once()->andThrow($exception); + $event = Double::for(new Event($eventMutex, 'test:failing', null, false))->passthru(); + $event->expects('run')->throws($exception); - $this->handler->shouldReceive('report')->once()->with($exception); + $this->handler->expects('report')->with($exception); $command = $this->makeCommand(); $this->invokeRunEvent($command, $event); @@ -1669,10 +1663,10 @@ public function testRunningEventIsForgottenWhenEventThrows(): void */ protected function captureTerminationSignal(?Closure &$callback): void { - $registry = m::mock(SignalRegistry::class); + $registry = Double::for(SignalRegistry::class); $registry->expects('register') - ->with(m::type(ScheduleRunCommand::class), [SIGTERM, SIGINT, SIGQUIT], m::capture($callback)); - $registry->shouldReceive('unregister'); + ->with(Argument::type(ScheduleRunCommand::class), [SIGTERM, SIGINT, SIGQUIT], Argument::capture($callback)); + $registry->allows('unregister'); $this->app->instance(SignalRegistry::class, $registry); } @@ -1686,14 +1680,15 @@ protected function makeCommand( $command ??= new ScheduleRunCommand; $command->setHypervel($this->app); - $cache ??= m::mock(Cache::class); - $cache->shouldReceive('get') - ->byDefault() - ->with('hypervel:schedule:paused', false) - ->andReturnFalse(); + if ($cache === null) { + $cache = Double::for(Cache::class)->strict(); + $cache->allows('get') + ->with('hypervel:schedule:paused', false) + ->returns(false); + } // Set dependencies that are normally injected via handle(). - (new ReflectionProperty($command, 'schedule'))->setValue($command, m::mock(Schedule::class)); + (new ReflectionProperty($command, 'schedule'))->setValue($command, Double::for(Schedule::class)); (new ReflectionProperty($command, 'dispatcher'))->setValue($command, $this->dispatcher); (new ReflectionProperty($command, 'cache'))->setValue($command, $cache); (new ReflectionProperty($command, 'handler'))->setValue($command, $this->handler); diff --git a/tests/Console/Scheduling/ScheduleRunContextPropagationTest.php b/tests/Console/Scheduling/ScheduleRunContextPropagationTest.php index 43ae8a1477..83800bbe05 100644 --- a/tests/Console/Scheduling/ScheduleRunContextPropagationTest.php +++ b/tests/Console/Scheduling/ScheduleRunContextPropagationTest.php @@ -21,13 +21,16 @@ use Hypervel\Support\Collection; use Hypervel\Support\Stringable; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionMethod; use ReflectionProperty; use Swoole\Coroutine; class ScheduleRunContextPropagationTest extends TestCase { + use VerifiesDoubles; + protected Dispatcher $dispatcher; protected ExceptionHandler $handler; @@ -38,11 +41,11 @@ protected function setUp(): void { parent::setUp(); - $this->dispatcher = m::mock(Dispatcher::class); - $this->dispatcher->shouldReceive('hasListeners')->andReturnTrue(); - $this->dispatcher->shouldReceive('dispatch'); + $this->dispatcher = Double::for(Dispatcher::class); + $this->dispatcher->allows('hasListeners')->returns(true); + $this->dispatcher->allows('dispatch'); - $this->handler = m::mock(ExceptionHandler::class); + $this->handler = Double::for(ExceptionHandler::class)->strict(); } /** @@ -132,9 +135,9 @@ public function testForegroundTaskReceivesIndependentCopyOfParentLogContext(): v ContextRepository::getInstance()->add('parent_key', 'original'); $childValues = []; - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); $event = new CallbackEvent($eventMutex, function () use (&$childValues) { $context = ContextRepository::getInstance(); @@ -166,7 +169,7 @@ public function testSystemTaskReceivesContextThroughItsEnvironment(): void ->addHidden('token', 'secret'); $context = null; - $event = new Event(m::mock(EventMutex::class), 'printf %s "$__HYPERVEL_CONTEXT"', isSystem: true); + $event = new Event(Double::for(EventMutex::class), 'printf %s "$__HYPERVEL_CONTEXT"', isSystem: true); $event->thenWithOutput(static function (Stringable $output) use (&$context): void { $context = (string) $output; }); @@ -186,12 +189,12 @@ public function testSystemTaskReceivesContextThroughItsEnvironment(): void */ protected function makeBackgroundEvent(callable $callback): Event { - $eventMutex = m::mock(EventMutex::class); - $eventMutex->shouldReceive('create')->andReturn(true); - $eventMutex->shouldReceive('forget'); + $eventMutex = Double::for(EventMutex::class); + $eventMutex->allows('create')->returns(true); + $eventMutex->allows('forget'); - $event = m::mock(Event::class, [$eventMutex, 'test:context', null, false])->makePartial(); - $event->shouldReceive('run')->once()->andReturnUsing(function () use ($callback) { + $event = Double::for(new Event($eventMutex, 'test:context', null, false))->passthru(); + $event->expects('run')->resolves(function () use ($callback) { $callback(); }); $event->runInBackground(); @@ -223,13 +226,12 @@ protected function makeCommand(): ScheduleRunCommand $command = new ScheduleRunCommand; $command->setHypervel($this->app); - (new ReflectionProperty($command, 'schedule'))->setValue($command, m::mock(Schedule::class)); + (new ReflectionProperty($command, 'schedule'))->setValue($command, Double::for(Schedule::class)); (new ReflectionProperty($command, 'dispatcher'))->setValue($command, $this->dispatcher); - $cache = m::mock(Cache::class); - $cache->shouldReceive('get') - ->byDefault() + $cache = Double::for(Cache::class); + $cache->allows('get') ->with('hypervel:schedule:paused', false) - ->andReturnFalse(); + ->returns(false); (new ReflectionProperty($command, 'cache'))->setValue($command, $cache); (new ReflectionProperty($command, 'handler'))->setValue($command, $this->handler); diff --git a/tests/Context/ContextCoroutineTest.php b/tests/Context/ContextCoroutineTest.php index f565130349..cb65aa4e80 100644 --- a/tests/Context/ContextCoroutineTest.php +++ b/tests/Context/ContextCoroutineTest.php @@ -14,7 +14,6 @@ use Hypervel\Http\Request; use Hypervel\Tests\Context\Fixtures\ThrowingReplicableContext; use Hypervel\Tests\TestCase; -use Mockery as m; use RuntimeException; use stdClass; @@ -183,7 +182,7 @@ function () { public function testRequestContextWithCoroutineId(): void { - $request = m::mock(Request::class); + $request = Request::create('/'); RequestContext::set($request); $id = Coroutine::id(); (new Waiter)->wait(function () use ($id, $request) { diff --git a/tests/Context/ContextTest.php b/tests/Context/ContextTest.php index 0eba2798d2..3b5d43182d 100644 --- a/tests/Context/ContextTest.php +++ b/tests/Context/ContextTest.php @@ -15,7 +15,6 @@ use Hypervel\Http\Request; use Hypervel\Tests\Context\Fixtures\ThrowingReplicableContext; use Hypervel\Tests\TestCase; -use Mockery as m; use RuntimeException; use stdClass; use Swoole\Event; @@ -418,11 +417,11 @@ public function testContextForget(): void public function testRequestContext(): void { - $request = m::mock(Request::class); + $request = Request::create('/'); RequestContext::set($request); $this->assertSame($request, RequestContext::get()); - CoroutineContext::set(Request::class, $req = m::mock(Request::class)); + CoroutineContext::set(Request::class, $req = Request::create('/')); $this->assertNotSame($request, RequestContext::get()); $this->assertSame($req, RequestContext::get()); $this->assertSame($req, CoroutineContext::get(Request::class)); diff --git a/tests/Cookie/CookieJarTest.php b/tests/Cookie/CookieJarTest.php index 54cf22ab14..e3a9c38409 100644 --- a/tests/Cookie/CookieJarTest.php +++ b/tests/Cookie/CookieJarTest.php @@ -10,7 +10,8 @@ use Hypervel\Http\Request; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use stdClass; use Symfony\Component\HttpFoundation\Cookie; @@ -35,6 +36,8 @@ enum CookieJarTestNameIntEnum: int class CookieJarTest extends TestCase { + use VerifiesDoubles; + // ========================================================================= // Laravel CookieTest (adapted for Context-based storage) // ========================================================================= @@ -374,9 +377,7 @@ public function testFlushQueuedCookies(): void public function testHas(): void { - $request = m::mock(Request::class); - $request->shouldReceive('cookie')->with('foo', null)->andReturn('bar'); - RequestContext::set($request); + RequestContext::set(Request::create('/', 'GET', [], ['foo' => 'bar'])); $manager = new CookieJar; @@ -385,9 +386,7 @@ public function testHas(): void public function testGet(): void { - $request = m::mock(Request::class); - $request->shouldReceive('cookie')->with('foo', null)->andReturn('bar'); - RequestContext::set($request); + RequestContext::set(Request::create('/', 'GET', [], ['foo' => 'bar'])); $manager = new CookieJar; @@ -424,9 +423,7 @@ public function testForeverUsesLaravelDuration(): void public function testHasAcceptsStringBackedEnum(): void { - $request = m::mock(Request::class); - $request->shouldReceive('cookie')->with('session_id', null)->andReturn('abc123'); - RequestContext::set($request); + RequestContext::set(Request::create('/', 'GET', [], ['session_id' => 'abc123'])); $manager = new CookieJar; @@ -435,9 +432,7 @@ public function testHasAcceptsStringBackedEnum(): void public function testHasAcceptsUnitEnum(): void { - $request = m::mock(Request::class); - $request->shouldReceive('cookie')->with('theme', null)->andReturn('dark'); - RequestContext::set($request); + RequestContext::set(Request::create('/', 'GET', [], ['theme' => 'dark'])); $manager = new CookieJar; @@ -446,9 +441,7 @@ public function testHasAcceptsUnitEnum(): void public function testGetAcceptsStringBackedEnum(): void { - $request = m::mock(Request::class); - $request->shouldReceive('cookie')->with('session_id', null)->andReturn('abc123'); - RequestContext::set($request); + RequestContext::set(Request::create('/', 'GET', [], ['session_id' => 'abc123'])); $manager = new CookieJar; @@ -457,9 +450,7 @@ public function testGetAcceptsStringBackedEnum(): void public function testGetAcceptsUnitEnum(): void { - $request = m::mock(Request::class); - $request->shouldReceive('cookie')->with('theme', null)->andReturn('dark'); - RequestContext::set($request); + RequestContext::set(Request::create('/', 'GET', [], ['theme' => 'dark'])); $manager = new CookieJar; @@ -528,9 +519,9 @@ public function testForgetAcceptsUnitEnum(): void public function testIntegerBackedEnumNamesAreNormalizedAcrossRequestCreationAndQueuePaths(): void { - $request = m::mock(Request::class); - $request->shouldReceive('cookie')->once()->with('0', null)->andReturn('request-value'); - RequestContext::set($request); + $request = Double::for(Request::class, override: true); + $request->expects('cookie')->with('0', null)->returns('request-value'); + RequestContext::set($request->instance()); $jar = new CookieJar; diff --git a/tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php b/tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php index 3b53d9e689..9c97a8b3a8 100644 --- a/tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php +++ b/tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php @@ -8,18 +8,21 @@ use Hypervel\Cookie\Middleware\AddQueuedCookiesToResponse; use Hypervel\Http\Request; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Response; class AddQueuedCookiesToResponseTest extends TestCase { + use VerifiesDoubles; + public function testHandle(): void { $queuedCookie = new Cookie('foo', 'bar'); - $cookieManager = m::mock(CookieJar::class); - $cookieManager->shouldReceive('getQueuedCookies')->once()->andReturn([$queuedCookie]); + $cookieManager = Double::for(CookieJar::class); + $cookieManager->expects('getQueuedCookies')->returns([$queuedCookie]); $request = Request::create('/test'); $response = new Response('OK'); diff --git a/tests/Coordinator/TimerTest.php b/tests/Coordinator/TimerTest.php index 08396c7f4e..560e2ab2f2 100644 --- a/tests/Coordinator/TimerTest.php +++ b/tests/Coordinator/TimerTest.php @@ -18,7 +18,8 @@ use Hypervel\Filesystem\Filesystem; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Psr\Log\LoggerInterface; use ReflectionProperty; @@ -27,6 +28,8 @@ class TimerTest extends TestCase { + use VerifiesDoubles; + public function testAfter(): void { $this->wait(function () { @@ -142,7 +145,7 @@ public function testClearAllFromCreationHookDoesNotLeaveTheTimerCoroutineRunning public function testCancellationDuringStartupReportingRollsBackThePublishedTimer(): void { - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); Container::getInstance()->instance(ExceptionHandlerContract::class, $handler); $timer = new Timer; $hookFailure = new RuntimeException('The startup hook failed.'); @@ -155,10 +158,9 @@ public function testCancellationDuringStartupReportingRollsBackThePublishedTimer $cancellationRequested = false; $callbackCalled = false; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ( + ->resolves(static function () use ( $timer, $reportStarted, $releaseReport, @@ -427,8 +429,8 @@ public function testTickWhenReturnStop(): void public function testTickStopsSilentlyWhenItsCallbackIsCancelled(): void { $logs = 0; - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('error')->zeroOrMoreTimes()->andReturnUsing( + $logger = Double::for(LoggerInterface::class); + $logger->allows('error')->resolves( static function () use (&$logs): void { ++$logs; }, @@ -472,8 +474,8 @@ public function testTickReportsThroughTheConfiguredLoggerAndContinues(): void { $this->wait(function (): void { $exception = new RuntimeException('recurring timer failed'); - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('error')->once()->with((string) $exception); + $logger = Double::for(LoggerInterface::class); + $logger->expects('error')->with((string) $exception); $timer = new Timer($logger); $calls = 0; $completed = new Channel(1); diff --git a/tests/Core/Bootstrap/LifecycleCallbackTest.php b/tests/Core/Bootstrap/LifecycleCallbackTest.php index 21c39d8ddb..7399fe68d7 100644 --- a/tests/Core/Bootstrap/LifecycleCallbackTest.php +++ b/tests/Core/Bootstrap/LifecycleCallbackTest.php @@ -30,12 +30,16 @@ use Hypervel\Core\Events\OnWorkerError; use Hypervel\Core\Events\OnWorkerStop; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use Swoole\Server; class LifecycleCallbackTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('callbacks')] public function testCallbackSkipsEventWithoutListeners( string $callbackClass, @@ -43,13 +47,13 @@ public function testCallbackSkipsEventWithoutListeners( string $eventClass, array $arguments, ): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with($eventClass)->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with($eventClass)->returns(false); + $dispatcher->expects('dispatch')->never(); $callback = new $callbackClass($dispatcher); - $this->assertNull($callback->{$method}(m::mock(Server::class), ...$arguments)); + $this->assertNull($callback->{$method}(Double::for(Server::class), ...$arguments)); } #[DataProvider('callbacks')] @@ -59,13 +63,13 @@ public function testCallbackDispatchesEventWhenListenedFor( string $eventClass, array $arguments, ): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with($eventClass)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type($eventClass)); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with($eventClass)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type($eventClass)); $callback = new $callbackClass($dispatcher); - $this->assertNull($callback->{$method}(m::mock(Server::class), ...$arguments)); + $this->assertNull($callback->{$method}(Double::for(Server::class), ...$arguments)); } /** diff --git a/tests/Core/Bootstrap/TaskCallbackNonCoroutineTest.php b/tests/Core/Bootstrap/TaskCallbackNonCoroutineTest.php index 8ef27bc919..243c072d8b 100644 --- a/tests/Core/Bootstrap/TaskCallbackNonCoroutineTest.php +++ b/tests/Core/Bootstrap/TaskCallbackNonCoroutineTest.php @@ -11,38 +11,40 @@ use Hypervel\Core\Events\OnTask; use Hypervel\Core\Events\TaskTerminated; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use RuntimeException; use Swoole\Constant; use Swoole\Server; class TaskCallbackNonCoroutineTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testEachTaskGetsAnEmptyContextUntilItHasTerminated(): void { CoroutineContext::set('worker', 'outer'); $seen = []; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->twice() - ->with(m::type(OnTask::class)) - ->andReturnUsing(function (OnTask $event) use (&$seen): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(true); + $dispatcher->expects('dispatch')->times(2) + ->with(Argument::type(OnTask::class)) + ->resolves(function (OnTask $event) use (&$seen): void { $seen[] = [CoroutineContext::get('worker'), CoroutineContext::get('task')]; CoroutineContext::set('task', $event->task->data); }); - $dispatcher->shouldReceive('dispatch') - ->twice() - ->with(m::type(TaskTerminated::class)) - ->andReturnUsing(function () use (&$seen): void { + $dispatcher->expects('dispatch')->times(2) + ->with(Argument::type(TaskTerminated::class)) + ->resolves(function () use (&$seen): void { $seen[] = CoroutineContext::get('task'); }); $callback = $this->makeCallback($dispatcher); - $callback->onTask(m::mock(Server::class), 1, 0, 'first'); - $callback->onTask(m::mock(Server::class), 2, 0, 'second'); + $callback->onTask(Double::for(Server::class), 1, 0, 'first'); + $callback->onTask(Double::for(Server::class), 2, 0, 'second'); $this->assertSame([[null, null], 'first', [null, null], 'second'], $seen); $this->assertSame('outer', CoroutineContext::get('worker')); @@ -54,25 +56,23 @@ public function testTheWorkerContextIsRestoredWhenATaskFails(): void CoroutineContext::set('worker', 'outer'); $exception = new RuntimeException('Task failed.'); $terminatedWith = null; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnTask::class)) - ->andReturnUsing(function () use ($exception): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->allows('hasListeners')->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->resolves(function () use ($exception): void { CoroutineContext::set('task', 'failed'); throw $exception; }); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(TaskTerminated::class)) - ->andReturnUsing(function () use (&$terminatedWith): void { + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)) + ->resolves(function () use (&$terminatedWith): void { $terminatedWith = CoroutineContext::get('task'); }); try { - $this->makeCallback($dispatcher)->onTask(m::mock(Server::class), 1, 0, 'payload'); + $this->makeCallback($dispatcher)->onTask(Double::for(Server::class), 1, 0, 'payload'); $this->fail('Expected the task failure to propagate.'); } catch (RuntimeException $throwable) { $this->assertSame($exception, $throwable); diff --git a/tests/Core/Bootstrap/TaskCallbackTest.php b/tests/Core/Bootstrap/TaskCallbackTest.php index 4e32e493aa..156d458e7a 100644 --- a/tests/Core/Bootstrap/TaskCallbackTest.php +++ b/tests/Core/Bootstrap/TaskCallbackTest.php @@ -10,7 +10,9 @@ use Hypervel\Core\Events\OnTask; use Hypervel\Core\Events\TaskTerminated; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Constant; @@ -19,47 +21,44 @@ class TaskCallbackTest extends TestCase { + use VerifiesDoubles; + public function testLegacySignatureBuildsTaskEvent(): void { - $server = m::mock(Server::class); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::on(function (OnTask $event) use ($server): bool { + $server = Double::for(Server::class); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->resolves(function (OnTask $event) use ($server): void { $this->assertSame($server, $event->server); $this->assertSame(12, $event->task->id); $this->assertSame(3, $event->task->worker_id); $this->assertSame(['payload' => true], $event->task->data); - - return true; - })); - $dispatcher->shouldReceive('hasListeners') - ->once() + }); + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnFalse(); + ->returns(false); $this->makeCallback($dispatcher)->onTask($server, 12, 3, ['payload' => true]); } public function testMissingTaskListenerSkipsFinishAndStillDispatchesTerminalEvent(): void { - $server = m::mock(Server::class); - $server->shouldNotReceive('finish'); - - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(TaskTerminated::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::on(function (TaskTerminated $event) use ($server): bool { + $server = Double::for(Server::class); + $server->expects('finish')->never(); + + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(false); + $dispatcher->expects('hasListeners')->with(TaskTerminated::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)) + ->resolves(function (TaskTerminated $event) use ($server): void { $this->assertSame($server, $event->server); $this->assertSame(12, $event->task->id); $this->assertSame(3, $event->task->worker_id); $this->assertSame(['payload' => true], $event->task->data); - - return true; - })); + }); $this->makeCallback($dispatcher)->onTask($server, 12, 3, ['payload' => true]); } @@ -67,34 +66,29 @@ public function testMissingTaskListenerSkipsFinishAndStillDispatchesTerminalEven #[DataProvider('objectModeSettings')] public function testDedicatedTaskSettingsUseNativeObjectSignature(array $settings): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class); $task = new Task; $task->id = 21; $task->worker_id = 4; $task->data = 'payload'; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::on(function (OnTask $event) use ($server, $task): bool { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->resolves(function (OnTask $event) use ($server, $task): void { $this->assertSame($server, $event->server); $this->assertSame($task, $event->task); - - return true; - })); - $dispatcher->shouldReceive('hasListeners') - ->once() + }); + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::on(function (TaskTerminated $event) use ($server, $task): bool { + ->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)) + ->resolves(function (TaskTerminated $event) use ($server, $task): void { $this->assertSame($server, $event->server); $this->assertSame($task, $event->task); - - return true; - })); + }); $this->makeCallback($dispatcher, $settings)->onTask($server, $task); } @@ -110,21 +104,18 @@ public static function objectModeSettings(): array public function testLegacyAliasPresenceTakesPrecedenceOverTaskObject(): void { - $server = m::mock(Server::class); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::on(function (OnTask $event): bool { + $server = Double::for(Server::class); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->resolves(function (OnTask $event): void { $this->assertSame(31, $event->task->id); $this->assertSame('legacy', $event->task->data); - - return true; - })); - $dispatcher->shouldReceive('hasListeners') - ->once() + }); + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnFalse(); + ->returns(false); $this->makeCallback($dispatcher, [ Constant::OPTION_TASK_USE_OBJECT => false, @@ -134,21 +125,19 @@ public function testLegacyAliasPresenceTakesPrecedenceOverTaskObject(): void public function testLegacyResultIsFinishedThroughServer(): void { - $server = m::mock(Server::class); - $server->shouldReceive('finish')->once()->with('completed'); - - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnTask::class)) - ->andReturnUsing(function (OnTask $event): void { + $server = Double::for(Server::class); + $server->expects('finish')->with('completed'); + + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->resolves(function (OnTask $event): void { $event->setResult('completed'); }); - $dispatcher->shouldReceive('hasListeners') - ->once() + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnFalse(); + ->returns(false); $this->makeCallback($dispatcher)->onTask($server, 41, 6, 'payload'); } @@ -156,40 +145,35 @@ public function testLegacyResultIsFinishedThroughServer(): void public function testLegacyResultIsFinishedBeforeTerminalDispatch(): void { $order = []; - $server = m::mock(Server::class); - $server->shouldReceive('finish') - ->once() + $server = Double::for(Server::class); + $server->expects('finish') ->with('completed') - ->andReturnUsing(function () use (&$order): bool { + ->resolves(function () use (&$order): bool { $order[] = 'finish'; return true; }); $task = null; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnTask::class)) - ->andReturnUsing(function (OnTask $event) use (&$order, &$task): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->resolves(function (OnTask $event) use (&$order, &$task): void { $task = $event->task; $event->setResult('completed'); $order[] = 'task'; }); - $dispatcher->shouldReceive('hasListeners') - ->once() + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::on(function (TaskTerminated $event) use ($server, &$order, &$task): bool { + ->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)) + ->resolves(function (TaskTerminated $event) use ($server, &$order, &$task): void { $this->assertSame($server, $event->server); $this->assertSame($task, $event->task); $order[] = 'terminated'; - - return true; - })); + }); $this->makeCallback($dispatcher)->onTask($server, 42, 7, 'payload'); @@ -199,22 +183,19 @@ public function testLegacyResultIsFinishedBeforeTerminalDispatch(): void public function testTaskFailureSkipsFinishButStillDispatchesTerminalEvent(): void { $exception = new RuntimeException('Task failed.'); - $server = m::mock(Server::class); - $server->shouldNotReceive('finish'); - - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnTask::class)) - ->andThrow($exception); - $dispatcher->shouldReceive('hasListeners') - ->once() + $server = Double::for(Server::class); + $server->expects('finish')->never(); + + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->throws($exception); + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(TaskTerminated::class)); + ->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)); try { $this->makeCallback($dispatcher)->onTask($server, 43, 8, 'payload'); @@ -227,24 +208,21 @@ public function testTaskFailureSkipsFinishButStillDispatchesTerminalEvent(): voi public function testFinishFailureStillDispatchesTerminalEvent(): void { $exception = new RuntimeException('Finish failed.'); - $server = m::mock(Server::class); - $server->shouldReceive('finish')->once()->andThrow($exception); - - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnTask::class)) - ->andReturnUsing(function (OnTask $event): void { + $server = Double::for(Server::class); + $server->expects('finish')->throws($exception); + + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->resolves(function (OnTask $event): void { $event->setResult('completed'); }); - $dispatcher->shouldReceive('hasListeners') - ->once() + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(TaskTerminated::class)); + ->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)); try { $this->makeCallback($dispatcher)->onTask($server, 44, 9, 'payload'); @@ -257,20 +235,17 @@ public function testFinishFailureStillDispatchesTerminalEvent(): void public function testTerminalFailurePropagatesAfterSuccessfulTask(): void { $exception = new RuntimeException('Terminal dispatch failed.'); - $server = m::mock(Server::class); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnTask::class)); - $dispatcher->shouldReceive('hasListeners') - ->once() + $server = Double::for(Server::class); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)); + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(TaskTerminated::class)) - ->andThrow($exception); + ->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)) + ->throws($exception); try { $this->makeCallback($dispatcher)->onTask($server, 45, 10, 'payload'); @@ -284,21 +259,18 @@ public function testTaskFailureRemainsPrimaryWhenTerminalDispatchAlsoFails(): vo { $taskException = new RuntimeException('Task failed.'); $terminalException = new RuntimeException('Terminal dispatch failed.'); - $server = m::mock(Server::class); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnTask::class)) - ->andThrow($taskException); - $dispatcher->shouldReceive('hasListeners') - ->once() + $server = Double::for(Server::class); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->throws($taskException); + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(TaskTerminated::class)) - ->andThrow($terminalException); + ->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)) + ->throws($terminalException); try { $this->makeCallback($dispatcher)->onTask($server, 46, 11, 'payload'); @@ -312,25 +284,22 @@ public function testFinishFailureRemainsPrimaryWhenTerminalDispatchAlsoFails(): { $finishException = new RuntimeException('Finish failed.'); $terminalException = new RuntimeException('Terminal dispatch failed.'); - $server = m::mock(Server::class); - $server->shouldReceive('finish')->once()->andThrow($finishException); - - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(OnTask::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnTask::class)) - ->andReturnUsing(function (OnTask $event): void { + $server = Double::for(Server::class); + $server->expects('finish')->throws($finishException); + + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnTask::class)) + ->resolves(function (OnTask $event): void { $event->setResult('completed'); }); - $dispatcher->shouldReceive('hasListeners') - ->once() + $dispatcher->expects('hasListeners') ->with(TaskTerminated::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(TaskTerminated::class)) - ->andThrow($terminalException); + ->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(TaskTerminated::class)) + ->throws($terminalException); try { $this->makeCallback($dispatcher)->onTask($server, 47, 12, 'payload'); diff --git a/tests/Core/Bootstrap/WorkerExitCallbackTest.php b/tests/Core/Bootstrap/WorkerExitCallbackTest.php index 46acb02d35..f74fe00fcf 100644 --- a/tests/Core/Bootstrap/WorkerExitCallbackTest.php +++ b/tests/Core/Bootstrap/WorkerExitCallbackTest.php @@ -10,7 +10,9 @@ use Hypervel\Core\Bootstrap\WorkerExitCallback; use Hypervel\Core\Events\OnWorkerExit; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use RuntimeException; use Swoole\Coroutine as SwooleCoroutine; @@ -18,6 +20,8 @@ class WorkerExitCallbackTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; #[RunInSeparateProcess] @@ -26,17 +30,15 @@ public function testWorkerExitDoesNotRequireAnotherCoroutineSlot(): void SwooleCoroutine::set(['max_coroutine' => 1]); SwooleCoroutine\run(function (): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners') - ->once() + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners') ->with(OnWorkerExit::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(OnWorkerExit::class)); + ->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(OnWorkerExit::class)); $coordinator = CoordinatorManager::until(Constants::WORKER_EXIT); $callback = new WorkerExitCallback($dispatcher); - $server = m::mock(Server::class); + $server = Double::for(Server::class); $callback->onWorkerExit($server, 3); $callback->onWorkerExit($server, 3); @@ -50,17 +52,16 @@ public function testWorkerExitDoesNotRequireAnotherCoroutineSlot(): void public function testWorkerExitResumesCoordinationWithoutListeners(): void { SwooleCoroutine\run(function (): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners') - ->once() + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners') ->with(OnWorkerExit::class) - ->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + ->returns(false); + $dispatcher->expects('dispatch')->never(); $coordinator = CoordinatorManager::until(Constants::WORKER_EXIT); $callback = new WorkerExitCallback($dispatcher); - $callback->onWorkerExit(m::mock(Server::class), 3); - $callback->onWorkerExit(m::mock(Server::class), 3); + $callback->onWorkerExit(Double::for(Server::class), 3); + $callback->onWorkerExit(Double::for(Server::class), 3); $this->assertTrue($coordinator->isClosing()); }); @@ -71,15 +72,14 @@ public function testWorkerExitResumesCoordinationWhenAListenerThrows(): void { SwooleCoroutine\run(function (): void { $failure = new RuntimeException('worker exit listener failed'); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners') - ->once() + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners') ->with(OnWorkerExit::class) - ->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andThrow($failure); + ->returns(true); + $dispatcher->expects('dispatch')->throws($failure); $coordinator = CoordinatorManager::until(Constants::WORKER_EXIT); $callback = new WorkerExitCallback($dispatcher); - $server = m::mock(Server::class); + $server = Double::for(Server::class); try { $callback->onWorkerExit($server, 3); diff --git a/tests/Core/Bootstrap/WorkerStartCallbackTest.php b/tests/Core/Bootstrap/WorkerStartCallbackTest.php index cf6ad39917..6c34137933 100644 --- a/tests/Core/Bootstrap/WorkerStartCallbackTest.php +++ b/tests/Core/Bootstrap/WorkerStartCallbackTest.php @@ -16,50 +16,50 @@ use Hypervel\Core\Events\OtherWorkerStart; use Hypervel\Core\Logger\StdoutLogger; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Psr\Log\LogLevel; use Swoole\Server; use Symfony\Component\Console\Output\BufferedOutput; class WorkerStartCallbackTest extends TestCase { + use VerifiesDoubles; + public function testLifecycleEventsAndStartupLoggingRemainOrdered(): void { $sequence = []; - $server = m::mock(Server::class); + $server = Double::for(Server::class); $server->taskworker = false; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MainWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(AfterWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(BeforeWorkerStart::class)->returns(true); + $dispatcher->expects('hasListeners')->with(MainWorkerStart::class)->returns(true); + $dispatcher->expects('hasListeners')->with(AfterWorkerStart::class)->returns(true); + $dispatcher->expects('dispatch') ->ordered() - ->with(m::type(BeforeWorkerStart::class)) - ->andReturnUsing(function () use (&$sequence): void { + ->with(Argument::type(BeforeWorkerStart::class)) + ->resolves(function () use (&$sequence): void { $sequence[] = 'before'; }); - $dispatcher->shouldReceive('dispatch') - ->once() + $dispatcher->expects('dispatch') ->ordered() - ->with(m::type(MainWorkerStart::class)) - ->andReturnUsing(function () use (&$sequence): void { + ->with(Argument::type(MainWorkerStart::class)) + ->resolves(function () use (&$sequence): void { $sequence[] = 'main'; }); - $dispatcher->shouldReceive('dispatch') - ->once() + $dispatcher->expects('dispatch') ->ordered() - ->with(m::type(AfterWorkerStart::class)) - ->andReturnUsing(function () use (&$sequence): void { + ->with(Argument::type(AfterWorkerStart::class)) + ->resolves(function () use (&$sequence): void { $sequence[] = 'after'; }); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('info') - ->once() + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('info') ->with('Worker#0 started.') - ->andReturnUsing(function () use (&$sequence): void { + ->resolves(function () use (&$sequence): void { $sequence[] = 'started'; }); @@ -73,17 +73,17 @@ public function testLifecycleEventsAndStartupLoggingRemainOrdered(): void public function testWorkerStartsAndResumesCoordinationWithoutLifecycleListeners(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class); $server->taskworker = false; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeWorkerStart::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MainWorkerStart::class)->andReturnFalse(); - $dispatcher->shouldReceive('hasListeners')->once()->with(AfterWorkerStart::class)->andReturnFalse(); - $dispatcher->shouldNotReceive('dispatch'); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(BeforeWorkerStart::class)->returns(false); + $dispatcher->expects('hasListeners')->with(MainWorkerStart::class)->returns(false); + $dispatcher->expects('hasListeners')->with(AfterWorkerStart::class)->returns(false); + $dispatcher->expects('dispatch')->never(); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('info')->once()->with('Worker#0 started.'); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('info')->with('Worker#0 started.'); $coordinator = CoordinatorManager::until(Constants::WORKER_START); (new WorkerStartCallback($dispatcher, $logger))->onWorkerStart($server, 0); @@ -98,22 +98,21 @@ public function testStartupLoggingUsesConfigurationRefreshedDuringBeforeWorkerSt ]); $output = new BufferedOutput; $logger = new StdoutLogger($config, $output); - $server = m::mock(Server::class); + $server = Double::for(Server::class); $server->taskworker = false; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(MainWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(AfterWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with(m::type(BeforeWorkerStart::class)) - ->andReturnUsing(function () use ($config): void { + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(BeforeWorkerStart::class)->returns(true); + $dispatcher->expects('hasListeners')->with(MainWorkerStart::class)->returns(true); + $dispatcher->expects('hasListeners')->with(AfterWorkerStart::class)->returns(true); + $dispatcher->expects('dispatch') + ->with(Argument::type(BeforeWorkerStart::class)) + ->resolves(function () use ($config): void { $config->set('app.stdout_log.level', [LogLevel::INFO]); $config->set('app.stdout_log.format', 'json'); }); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(MainWorkerStart::class)); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(AfterWorkerStart::class)); + $dispatcher->expects('dispatch')->with(Argument::type(MainWorkerStart::class)); + $dispatcher->expects('dispatch')->with(Argument::type(AfterWorkerStart::class)); (new WorkerStartCallback($dispatcher, $logger))->onWorkerStart($server, 0); @@ -124,19 +123,19 @@ public function testStartupLoggingUsesConfigurationRefreshedDuringBeforeWorkerSt public function testCustomLoggerOwnsItsConfiguration(): void { - $server = m::mock(Server::class); + $server = Double::for(Server::class); $server->taskworker = true; - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('hasListeners')->once()->with(BeforeWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(OtherWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('hasListeners')->once()->with(AfterWorkerStart::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(BeforeWorkerStart::class)); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(OtherWorkerStart::class)); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(AfterWorkerStart::class)); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('hasListeners')->with(BeforeWorkerStart::class)->returns(true); + $dispatcher->expects('hasListeners')->with(OtherWorkerStart::class)->returns(true); + $dispatcher->expects('hasListeners')->with(AfterWorkerStart::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(BeforeWorkerStart::class)); + $dispatcher->expects('dispatch')->with(Argument::type(OtherWorkerStart::class)); + $dispatcher->expects('dispatch')->with(Argument::type(AfterWorkerStart::class)); - $logger = m::mock(StdoutLoggerInterface::class); - $logger->shouldReceive('info')->once()->with('TaskWorker#2 started.'); + $logger = Double::for(StdoutLoggerInterface::class); + $logger->expects('info')->with('TaskWorker#2 started.'); (new WorkerStartCallback($dispatcher, $logger))->onWorkerStart($server, 2); } diff --git a/tests/Core/StdoutLoggerTest.php b/tests/Core/StdoutLoggerTest.php index ab79cca2f2..aa1787f0f9 100644 --- a/tests/Core/StdoutLoggerTest.php +++ b/tests/Core/StdoutLoggerTest.php @@ -11,8 +11,10 @@ use Hypervel\Tests\Core\Fixtures\TestObject; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use JsonSerializable; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use Psr\Log\InvalidArgumentException as PsrInvalidArgumentException; use Psr\Log\LogLevel; @@ -20,12 +22,13 @@ use Stringable; use Swoole\Coroutine\CanceledException; use Symfony\Component\Console\Output\BufferedOutput; -use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\OutputInterface; use Throwable; class StdoutLoggerTest extends TestCase { + use VerifiesDoubles; + public function testLog(): void { $logger = $this->getLineLogger('/^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] \[INFO\]<\/> Hello Hypervel\.$/'); @@ -55,8 +58,8 @@ public function testLogComplexityContext(): void public function testLogThrowable(): void { - $output = m::mock(ConsoleOutput::class); - $output->shouldReceive('writeln')->with(m::any())->once()->andReturnUsing(function ($message) { + $output = Double::for(OutputInterface::class); + $output->expects('writeln')->with(Argument::any())->resolves(function ($message) { $this->assertMatchesRegularExpression('/^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\].*RuntimeException: Invalid Arguments\./', $message); }); $logger = new StdoutLogger(new Repository([ @@ -68,8 +71,8 @@ public function testLogThrowable(): void public function testLevelFiltering(): void { - $output = m::mock(ConsoleOutput::class); - $output->shouldNotReceive('writeln'); + $output = Double::for(OutputInterface::class); + $output->expects('writeln')->never(); $logger = new StdoutLogger(new Repository([ 'app' => ['stdout_log' => ['level' => [LogLevel::ERROR], 'format' => 'line']], ]), $output); @@ -83,8 +86,8 @@ public function testLevelFilteringUsesConstructionTimeConfig(): void 'app' => ['stdout_log' => ['level' => [LogLevel::ERROR], 'format' => 'line']], ]); - $output = m::mock(ConsoleOutput::class); - $output->shouldReceive('writeln')->with(m::any())->once(); + $output = Double::for(OutputInterface::class); + $output->expects('writeln')->with(Argument::any()); $logger = new StdoutLogger($config, $output); @@ -95,8 +98,8 @@ public function testLevelFilteringUsesConstructionTimeConfig(): void public function testLineFormat(): void { - $output = m::mock(ConsoleOutput::class); - $output->shouldReceive('writeln')->with(m::any())->once()->andReturnUsing(function ($message) { + $output = Double::for(OutputInterface::class); + $output->expects('writeln')->with(Argument::any())->resolves(function ($message) { // Line format has colored tags, not JSON $this->assertMatchesRegularExpression('/^\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] \[INFO\]<\/>/', $message); }); @@ -163,8 +166,8 @@ public function testJsonFormatWithThrowable(): void public function testJsonFormatLevelFiltering(): void { - $output = m::mock(ConsoleOutput::class); - $output->shouldNotReceive('writeln'); + $output = Double::for(OutputInterface::class); + $output->expects('writeln')->never(); $logger = new StdoutLogger(new Repository([ 'app' => ['stdout_log' => ['level' => [LogLevel::ERROR], 'format' => 'json']], ]), $output); @@ -245,8 +248,8 @@ public function __toString(): string throw $this->cancellation; } }; - $output = m::mock(ConsoleOutput::class); - $output->shouldNotReceive('writeln'); + $output = Double::for(OutputInterface::class); + $output->expects('writeln')->never(); $logger = new StdoutLogger(new Repository([ 'app' => ['stdout_log' => ['level' => [LogLevel::INFO], 'format' => 'line']], ]), $output); @@ -422,8 +425,8 @@ public function jsonSerialize(): never throw $this->cancellation; } }; - $output = m::mock(ConsoleOutput::class); - $output->shouldNotReceive('writeln'); + $output = Double::for(OutputInterface::class); + $output->expects('writeln')->never(); $logger = new StdoutLogger(new Repository([ 'app' => ['stdout_log' => ['level' => [LogLevel::INFO], 'format' => 'json']], ]), $output); @@ -442,8 +445,8 @@ public function jsonSerialize(): never */ protected function getLineLogger(string $expectedPattern): StdoutLogger { - $output = m::mock(ConsoleOutput::class); - $output->shouldReceive('writeln')->with(m::any())->once()->andReturnUsing(function ($message) use ($expectedPattern) { + $output = Double::for(OutputInterface::class); + $output->expects('writeln')->with(Argument::any())->resolves(function ($message) use ($expectedPattern) { $this->assertMatchesRegularExpression($expectedPattern, $message); }); return new StdoutLogger(new Repository([ @@ -457,13 +460,9 @@ protected function getLineLogger(string $expectedPattern): StdoutLogger protected function logJson(string $level, string|Stringable $message, array $context = []): array { $captured = null; - $output = m::mock(ConsoleOutput::class); - $output->shouldReceive('writeln') - ->with(m::any(), OutputInterface::OUTPUT_RAW) - ->once() - ->andReturnUsing(function ($message) use (&$captured) { - $captured = $message; - }); + $output = Double::for(OutputInterface::class); + $output->expects('writeln') + ->with(Argument::capture($captured), OutputInterface::OUTPUT_RAW); $logger = new StdoutLogger(new Repository([ 'app' => ['stdout_log' => ['level' => [LogLevel::INFO, LogLevel::ERROR], 'format' => 'json']], diff --git a/tests/Coroutine/ConcurrentTest.php b/tests/Coroutine/ConcurrentTest.php index d9a553a4da..3c70422dc8 100644 --- a/tests/Coroutine/ConcurrentTest.php +++ b/tests/Coroutine/ConcurrentTest.php @@ -13,7 +13,8 @@ use Hypervel\Engine\Channel; use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine; @@ -21,6 +22,8 @@ class ConcurrentTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -137,7 +140,7 @@ public function testWaitForAvailableSlotConvertsNonThrowingCancellation(): void #[DataProvider('creationMethods')] public function testCreationCancellationWhileStartupReportingYieldsReleasesItsSlotOnce(string $method): void { - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); Container::getInstance()->instance(ExceptionHandlerContract::class, $handler); $concurrent = new ConcurrentTestConcurrent(1); $hookFailure = new RuntimeException('The startup hook failed.'); @@ -148,10 +151,9 @@ public function testCreationCancellationWhileStartupReportingYieldsReleasesItsSl $childCoroutineId = null; $childBodyRan = false; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); $releaseReport->pop(); diff --git a/tests/Coroutine/CoroutineTest.php b/tests/Coroutine/CoroutineTest.php index ae6e9725db..d9768c7a95 100644 --- a/tests/Coroutine/CoroutineTest.php +++ b/tests/Coroutine/CoroutineTest.php @@ -20,7 +20,8 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Context\Fixtures\ThrowingReplicableContext; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use PHPUnit\Framework\Attributes\TestWith; @@ -32,6 +33,8 @@ class CoroutineTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('cancellationExceptions')] public function testCancellationClassificationRespectsCoroutineBoundaries(Throwable $exception, bool $expected): void { @@ -159,34 +162,25 @@ public function testCoroutineParentIdHasBeenDestroyed(): void public function testCoroutineAndDeferWithException(): void { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); $container->instance(ExceptionHandlerContract::class, $handler); Container::setInstance($container); $exception = new Exception; - $handler->shouldReceive('report')->with($exception)->twice(); + $handler->expects('report')->with($exception)->times(2); - $chan = new Channel(1); - go(static function () use ($chan, $exception) { - Coroutine::defer(static function () use ($chan, $exception) { - try { - throw $exception; - } finally { - $chan->push(1); - } - }); + go(static function () use ($exception): never { + Coroutine::defer(static fn () => throw $exception); throw $exception; }); - - $this->assertTrue(true); } public function testTerminalCancellationIsNotReported(): void { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report')->never(); $container->instance(ExceptionHandlerContract::class, $handler); Container::setInstance($container); $blocker = new Channel(1); @@ -202,9 +196,9 @@ public function testTerminalCancellationIsNotReported(): void public function testTerminalBoundaryReportsCleanupFailureDuringCancellationOnce(): void { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); $failure = new RuntimeException('Coroutine cleanup failed.'); - $handler->shouldReceive('report')->once()->with($failure); + $handler->expects('report')->with($failure); $container->instance(ExceptionHandlerContract::class, $handler); Container::setInstance($container); $blocker = new Channel(1); @@ -232,14 +226,14 @@ public function testTerminalBoundaryReportsCleanupFailureDuringCancellationOnce( public function testTerminalBoundaryContainsCancellationDuringReporting(bool $cleanupFails): void { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); $container->instance(ExceptionHandlerContract::class, $handler); Container::setInstance($container); $failure = new RuntimeException('The coroutine failed.'); $cleanupFailure = new RuntimeException('The reporter cleanup failed.'); $blocker = new Channel(1); - $handler->shouldReceive('report')->once()->with($failure) - ->andReturnUsing(static function () use ($blocker, $cleanupFails, $cleanupFailure): void { + $handler->expects('report')->with($failure) + ->resolves(static function () use ($blocker, $cleanupFails, $cleanupFailure): void { try { $blocker->pop(); } finally { @@ -414,11 +408,11 @@ public function testExceptionReportingCanBeRestored(bool $flushState): void { try { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); $container->instance(ExceptionHandlerContract::class, $handler); Container::setInstance($container); - $handler->shouldReceive('report')->once(); + $handler->expects('report'); Coroutine::reportExceptions(false); Coroutine::create(function () { @@ -442,10 +436,10 @@ public function testExceptionReportingCanBeRestored(bool $flushState): void public function testAfterCreatedCallbackExceptionDoesNotStopOthers(): void { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); $container->instance(ExceptionHandlerContract::class, $handler); Container::setInstance($container); - $handler->shouldReceive('report')->once(); + $handler->expects('report'); $secondCallbackRan = false; $mainCallableRan = false; @@ -471,7 +465,7 @@ public function testAfterCreatedCallbackExceptionDoesNotStopOthers(): void public function testOwnedCoroutineTransfersOwnershipBeforeStartupFailureReportingCanSuspend(bool $cleanupFails): void { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); $container->instance(ExceptionHandlerContract::class, $handler); Container::setInstance($container); CoroutineContext::set('request-id', 'child-request'); @@ -485,10 +479,9 @@ public function testOwnedCoroutineTransfersOwnershipBeforeStartupFailureReportin $secondCallbackRan = false; $mainCallableRan = false; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($exception) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$reportedContext, $cleanupFails, $cleanupFailure): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$reportedContext, $cleanupFails, $cleanupFailure): void { $reportedContext = CoroutineContext::get('request-id'); $reportStarted->push(true); try { @@ -501,7 +494,7 @@ public function testOwnedCoroutineTransfersOwnershipBeforeStartupFailureReportin }); if ($cleanupFails) { - $handler->shouldReceive('report')->once()->with($cleanupFailure); + $handler->expects('report')->with($cleanupFailure); } Coroutine::afterCreated(static function () use ($exception): void { @@ -564,10 +557,9 @@ public function testExceptionHandlerFailureFallsBackToThePhpErrorLog(): void try { $container = new Container; - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report') - ->once() - ->andThrow(new RuntimeException('The exception reporter failed.')); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report') + ->throws(new RuntimeException('The exception reporter failed.')); $container->instance(ExceptionHandlerContract::class, $handler); Container::setInstance($container); diff --git a/tests/Coroutine/ParallelTest.php b/tests/Coroutine/ParallelTest.php index 60a8228a5f..a8a39d273b 100644 --- a/tests/Coroutine/ParallelTest.php +++ b/tests/Coroutine/ParallelTest.php @@ -19,7 +19,8 @@ use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Tests\Context\Fixtures\ThrowingReplicableContext; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine as SwooleCoroutine; @@ -30,6 +31,8 @@ class ParallelTest extends TestCase { + use VerifiesDoubles; + public function testParallel(): void { // Closure @@ -564,7 +567,7 @@ public function testNonThrowingCancellationWhileWaitingForCapacityDoesNotStartAn public function testCreationCancellationWhileStartupReportingYieldsReleasesOwnership(): void { - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); Container::getInstance()->instance(ExceptionHandlerContract::class, $handler); $parallel = new Parallel(1); $hookFailure = new RuntimeException('The startup hook failed.'); @@ -578,10 +581,9 @@ public function testCreationCancellationWhileStartupReportingYieldsReleasesOwner $childBodyRan = false; $failStartup = true; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); $releaseReport->pop(); diff --git a/tests/Coroutine/SignalRegistryRollbackTest.php b/tests/Coroutine/SignalRegistryRollbackTest.php index dfc7ffeabe..73bcf6fe31 100644 --- a/tests/Coroutine/SignalRegistryRollbackTest.php +++ b/tests/Coroutine/SignalRegistryRollbackTest.php @@ -13,7 +13,8 @@ use Hypervel\Engine\Exceptions\CoroutineCreateException; use Hypervel\Support\ClassInvoker; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use RuntimeException; use Swoole\Coroutine as SwooleCoroutine; @@ -21,6 +22,8 @@ class SignalRegistryRollbackTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; #[RunInSeparateProcess] @@ -52,8 +55,8 @@ public function testPartialArrayRegistrationRollsBackHandlersAndWaiters(): void public function testUnregisterTerminallyCancelsItsWaiterWithoutReporting(): void { SwooleCoroutine\run(function (): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldNotReceive('report'); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report')->never(); Container::getInstance()->instance(ExceptionHandlerContract::class, $handler); $registry = new SignalRegistry; @@ -131,11 +134,11 @@ protected function cancelOwnerDuringCreation(int $creation): Channel $releaseReport = new Channel(1); $parentCoroutineId = EngineCoroutine::id(); $reports = 0; - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report') + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report') ->times($creation) ->with($hookFailure) - ->andReturnUsing(static function () use ($creation, $reportStarted, $releaseReport, &$reports): void { + ->resolves(static function () use ($creation, $reportStarted, $releaseReport, &$reports): void { if (++$reports !== $creation) { return; } diff --git a/tests/Coroutine/SignalRegistryTest.php b/tests/Coroutine/SignalRegistryTest.php index 690adcaa17..f50abfa94e 100644 --- a/tests/Coroutine/SignalRegistryTest.php +++ b/tests/Coroutine/SignalRegistryTest.php @@ -12,13 +12,16 @@ use Hypervel\Engine\Channel; use Hypervel\Support\ClassInvoker; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use RuntimeException; use stdClass; class SignalRegistryTest extends TestCase { + use VerifiesDoubles; + #[RunInSeparateProcess] public function testRegister(): void { @@ -134,8 +137,8 @@ public function testInterleavedOwnersRetainOrderAndIsolateCallbackFailuresAndCon $handled = new Channel(1); $trace = []; $exception = new RuntimeException('Signal callback failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->twice()->with($exception); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->times(2)->with($exception); Container::getInstance()->instance(ExceptionHandler::class, $handler); try { @@ -171,9 +174,8 @@ public function testInterleavedOwnersRetainOrderAndIsolateCallbackFailuresAndCon public function testRegisterSingleSignalPushesHandler(): void { - $registry = m::mock(SignalRegistry::class)->makePartial(); - $registry->shouldAllowMockingProtectedMethods(); - $registry->shouldReceive('waitSignal')->with(SIGTERM)->once(); + $registry = Double::for(new SignalRegistry)->passthru(); + $registry->expects('waitSignal')->with(SIGTERM); $callback = fn (int $signo) => null; $registry->register($this, SIGTERM, $callback); @@ -186,10 +188,9 @@ public function testRegisterSingleSignalPushesHandler(): void public function testRegisterMultipleSignalsRegistersEach(): void { - $registry = m::mock(SignalRegistry::class)->makePartial(); - $registry->shouldAllowMockingProtectedMethods(); - $registry->shouldReceive('waitSignal')->with(SIGTERM)->once(); - $registry->shouldReceive('waitSignal')->with(SIGINT)->once(); + $registry = Double::for(new SignalRegistry)->passthru(); + $registry->expects('waitSignal')->with(SIGTERM); + $registry->expects('waitSignal')->with(SIGINT); $callback = fn (int $signo) => null; $registry->register($this, [SIGTERM, SIGINT], $callback); @@ -203,9 +204,8 @@ public function testRegisterMultipleSignalsRegistersEach(): void public function testRegisterMultipleHandlersForSameSignal(): void { - $registry = m::mock(SignalRegistry::class)->makePartial(); - $registry->shouldAllowMockingProtectedMethods(); - $registry->shouldReceive('waitSignal')->with(SIGTERM)->twice(); + $registry = Double::for(new SignalRegistry)->passthru(); + $registry->expects('waitSignal')->with(SIGTERM)->times(2); $callbackA = fn (int $signo) => null; $callbackB = fn (int $signo) => null; @@ -221,9 +221,8 @@ public function testRegisterMultipleHandlersForSameSignal(): void public function testUnregisterSingleSignal(): void { - $registry = m::mock(SignalRegistry::class)->makePartial(); - $registry->shouldAllowMockingProtectedMethods(); - $registry->shouldReceive('waitSignal'); + $registry = Double::for(new SignalRegistry)->passthru(); + $registry->allows('waitSignal'); $registry->register($this, SIGTERM, fn (int $signo) => null); $registry->register($this, SIGINT, fn (int $signo) => null); @@ -237,9 +236,8 @@ public function testUnregisterSingleSignal(): void public function testUnregisterMultipleSignals(): void { - $registry = m::mock(SignalRegistry::class)->makePartial(); - $registry->shouldAllowMockingProtectedMethods(); - $registry->shouldReceive('waitSignal'); + $registry = Double::for(new SignalRegistry)->passthru(); + $registry->allows('waitSignal'); $registry->register($this, SIGTERM, fn (int $signo) => null); $registry->register($this, SIGINT, fn (int $signo) => null); @@ -252,9 +250,8 @@ public function testUnregisterMultipleSignals(): void public function testUnregisterAllSignals(): void { - $registry = m::mock(SignalRegistry::class)->makePartial(); - $registry->shouldAllowMockingProtectedMethods(); - $registry->shouldReceive('waitSignal'); + $registry = Double::for(new SignalRegistry)->passthru(); + $registry->allows('waitSignal'); $registry->register($this, SIGTERM, fn (int $signo) => null); $registry->register($this, SIGINT, fn (int $signo) => null); diff --git a/tests/Coroutine/WaitConcurrentTest.php b/tests/Coroutine/WaitConcurrentTest.php index 6139b50087..cb96137da7 100644 --- a/tests/Coroutine/WaitConcurrentTest.php +++ b/tests/Coroutine/WaitConcurrentTest.php @@ -13,13 +13,16 @@ use Hypervel\Engine\Coroutine as EngineCoroutine; use Hypervel\Tests\Context\Fixtures\ThrowingReplicableContext; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; class WaitConcurrentTest extends TestCase { + use VerifiesDoubles; + public function testForkParticipatesInWaitTracking(): void { $release = new Channel(1); @@ -58,7 +61,7 @@ public function testForkBalancesWaitTrackingWhenContextReplicationFails(): void #[DataProvider('creationMethods')] public function testCreationCancellationWhileStartupReportingYieldsReleasesOwnershipOnce(string $method): void { - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); Container::getInstance()->instance(ExceptionHandlerContract::class, $handler); $concurrent = new WaitConcurrent(1); $hookFailure = new RuntimeException('The startup hook failed.'); @@ -69,10 +72,9 @@ public function testCreationCancellationWhileStartupReportingYieldsReleasesOwner $childCoroutineId = null; $childBodyRan = false; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); $releaseReport->pop(); diff --git a/tests/Coroutine/WaiterTest.php b/tests/Coroutine/WaiterTest.php index b17afdfc10..c43e1f243d 100644 --- a/tests/Coroutine/WaiterTest.php +++ b/tests/Coroutine/WaiterTest.php @@ -18,7 +18,8 @@ use Hypervel\Support\Sleep; use Hypervel\Tests\Context\Fixtures\ThrowingReplicableContext; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use ReflectionProperty; @@ -30,6 +31,8 @@ class WaiterTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -168,7 +171,7 @@ public function testWaitException(): void #[DataProvider('copyContexts')] public function testParentCancellationDuringStartupReportingCancelsThePublishedChild(bool $copyContext): void { - $handler = m::mock(ExceptionHandlerContract::class); + $handler = Double::for(ExceptionHandlerContract::class); Container::getInstance()->instance(ExceptionHandlerContract::class, $handler); $waiter = new Waiter; $hookFailure = new RuntimeException('The startup hook failed.'); @@ -179,10 +182,9 @@ public function testParentCancellationDuringStartupReportingCancelsThePublishedC $childCoroutineId = null; $childBodyRan = false; - $handler->shouldReceive('report') - ->once() + $handler->expects('report') ->with($hookFailure) - ->andReturnUsing(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { + ->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void { $childCoroutineId = EngineCoroutine::id(); $reportStarted->push(true); $releaseReport->pop(); diff --git a/tests/Data/DataServiceProviderTest.php b/tests/Data/DataServiceProviderTest.php index a097a63659..c7b5f87579 100644 --- a/tests/Data/DataServiceProviderTest.php +++ b/tests/Data/DataServiceProviderTest.php @@ -13,10 +13,13 @@ use Hypervel\Data\Support\Transformation\DataTransformer; use Hypervel\Foundation\Application as FoundationApplication; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DataServiceProviderTest extends TestCase { + use VerifiesDoubles; + // REMOVED: Structure-cache tests (the cache command and CachedDataConfig); worker memory is the metadata cache boundary. // REMOVED: Livewire/Wireable and TypeScript integration tests; Hypervel has no matching Data integration. @@ -54,8 +57,8 @@ public function testProviderWarmsFixedServicesAfterNonTestingApplicationBoot(): $application->instance('config', new Repository); $application->setRunningInConsole(false); - $creator = m::mock(DataCreator::class); - $transformer = m::mock(DataTransformer::class); + $creator = Double::for(DataCreator::class); + $transformer = Double::for(DataTransformer::class); $application->singleton(DataCreator::class, static fn (): DataCreator => $creator); $application->singleton(DataTransformer::class, static fn (): DataTransformer => $transformer); diff --git a/tests/Data/Support/Creation/DataCollectTest.php b/tests/Data/Support/Creation/DataCollectTest.php index 41b1a5dbfb..9703673576 100644 --- a/tests/Data/Support/Creation/DataCollectTest.php +++ b/tests/Data/Support/Creation/DataCollectTest.php @@ -22,11 +22,14 @@ use Hypervel\Support\Collection; use Hypervel\Support\LazyCollection; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use stdClass; class DataCollectTest extends TestCase { + use VerifiesDoubles; + /** * Get package providers for the test application. */ @@ -218,8 +221,8 @@ public function testCollectBuildsExplicitPaginatorWrappersWithoutMutatingTheSour public function testContractOnlyPaginatorCanTargetANonPaginatorWithoutCollectMethodDispatch(): void { - $paginator = m::mock(PaginatorContract::class); - $paginator->shouldReceive('items')->once()->andReturn([ + $paginator = Double::for(PaginatorContract::class); + $paginator->expects('items')->returns([ ['id' => '1'], ]); diff --git a/tests/Data/Support/DataTypeFactoryTest.php b/tests/Data/Support/DataTypeFactoryTest.php index 53b5ced0ef..4ff4b68a67 100644 --- a/tests/Data/Support/DataTypeFactoryTest.php +++ b/tests/Data/Support/DataTypeFactoryTest.php @@ -6,6 +6,7 @@ use Hypervel\Data\Attributes\DataCollectionOf; use Hypervel\Data\Contracts\BaseData; +use Hypervel\Data\Data; use Hypervel\Data\DataCollection; use Hypervel\Data\Enums\DataTypeKind; use Hypervel\Data\Optional; @@ -24,7 +25,6 @@ use Hypervel\Tests\Data\Fixtures\SimpleData; use Hypervel\Tests\Data\Fixtures\Types\ImportedData as GroupedImportedData; use Hypervel\Tests\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionClass; use ReflectionMethod; @@ -147,7 +147,7 @@ public function testIterableItemTypesAreCompiledFromPhpDocAndAttributes(): void $this->assertInstanceOf(UnionType::class, $itemType); $this->assertTrue($itemType->acceptsValue('value')); - $this->assertTrue($itemType->acceptsValue(m::mock(DataTypeFactoryItemData::class))); + $this->assertTrue($itemType->acceptsValue(new DataTypeFactoryItemData)); $this->assertSame(DataTypeFactoryItemData::class, $unionItems->getNamedTypes()[0]->dataClass); $this->assertSame($strings->getIterableTypes()[0], $strings->getNonDataIterableType()); $this->assertCount(2, $ambiguousIterables->getIterableTypes()); @@ -275,7 +275,7 @@ public function testNamedTypesUseNativePhpAcceptanceRules(): void $this->assertSame($data->getNamedTypes()[0], $data->getDataObjectType()); $this->assertSame(DataTypeFactoryItemData::class, $data->getDataObjectClass()); $this->assertNull($data->getDataCollectableType()); - $this->assertTrue($data->acceptsValue(m::mock(DataTypeFactoryItemData::class))); + $this->assertTrue($data->acceptsValue(new DataTypeFactoryItemData)); $this->assertSame( $dataCollection->getNamedTypes()[0], $dataCollection->getDataCollectableType(), @@ -492,7 +492,7 @@ class DataTypeFactoryBothTypes implements DataTypeFactoryFirstType, DataTypeFact { } -abstract class DataTypeFactoryItemData implements BaseData +class DataTypeFactoryItemData extends Data { } diff --git a/tests/Data/Transformers/ArrayableTransformerTest.php b/tests/Data/Transformers/ArrayableTransformerTest.php index 4db432bfe8..0141986e2e 100644 --- a/tests/Data/Transformers/ArrayableTransformerTest.php +++ b/tests/Data/Transformers/ArrayableTransformerTest.php @@ -9,16 +9,19 @@ use Hypervel\Data\Transformers\ArrayableTransformer; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ArrayableTransformerTest extends TestCase { + use VerifiesDoubles; + public function testCanTransformAnArrayable(): void { $value = new Collection(['A', 'B']); $result = (new ArrayableTransformer)->transform( - m::mock(DataProperty::class), + Double::for(DataProperty::class), $value, new TransformationContext, ); diff --git a/tests/Data/Transformers/DateTimeInterfaceTransformerTest.php b/tests/Data/Transformers/DateTimeInterfaceTransformerTest.php index 85c9569403..7cca9c9881 100644 --- a/tests/Data/Transformers/DateTimeInterfaceTransformerTest.php +++ b/tests/Data/Transformers/DateTimeInterfaceTransformerTest.php @@ -19,10 +19,13 @@ use Hypervel\Support\CarbonImmutable as HypervelCarbonImmutable; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DateTimeInterfaceTransformerTest extends TestCase { + use VerifiesDoubles; + protected function getPackageProviders(Application $app): array { return [DataServiceProvider::class]; @@ -74,7 +77,7 @@ protected function transform( DateTimeInterface $date, ): string { return $transformer->transform( - m::mock(DataProperty::class), + Double::for(DataProperty::class), $date, new TransformationContext, ); diff --git a/tests/Data/Transformers/EnumTransformerTest.php b/tests/Data/Transformers/EnumTransformerTest.php index 929d66d40a..3735e4ec63 100644 --- a/tests/Data/Transformers/EnumTransformerTest.php +++ b/tests/Data/Transformers/EnumTransformerTest.php @@ -8,14 +8,17 @@ use Hypervel\Data\Support\Transformation\TransformationContext; use Hypervel\Data\Transformers\EnumTransformer; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class EnumTransformerTest extends TestCase { + use VerifiesDoubles; + public function testCanTransformEnums(): void { $transformer = new EnumTransformer; - $property = m::mock(DataProperty::class); + $property = Double::for(DataProperty::class); $context = new TransformationContext; $this->assertSame('ready', $transformer->transform($property, StringStatus::Ready, $context)); diff --git a/tests/Data/Transformers/SerializeTransformerTest.php b/tests/Data/Transformers/SerializeTransformerTest.php index 77a96f7eed..8cc48ed8bc 100644 --- a/tests/Data/Transformers/SerializeTransformerTest.php +++ b/tests/Data/Transformers/SerializeTransformerTest.php @@ -9,17 +9,20 @@ use Hypervel\Data\Transformers\SerializeTransformer; use Hypervel\Tests\Data\Fixtures\Enums\DummyBackedEnum; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class SerializeTransformerTest extends TestCase { + use VerifiesDoubles; + public function testCanTransformUsingASerializer(): void { $transformer = new SerializeTransformer; $this->assertSame( serialize(DummyBackedEnum::FOO), - $transformer->transform(m::mock(DataProperty::class), DummyBackedEnum::FOO, new TransformationContext) + $transformer->transform(Double::for(DataProperty::class), DummyBackedEnum::FOO, new TransformationContext) ); } } diff --git a/tests/Database/ConnectionResolverTest.php b/tests/Database/ConnectionResolverTest.php index ae0f07f6a8..377eb2666c 100644 --- a/tests/Database/ConnectionResolverTest.php +++ b/tests/Database/ConnectionResolverTest.php @@ -16,7 +16,8 @@ use Hypervel\Database\Query\Grammars\SQLiteGrammar; use Hypervel\Engine\Coroutine; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -32,6 +33,8 @@ */ class ConnectionResolverTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; protected function tearDown(): void @@ -131,20 +134,24 @@ public function testNestedOverrideRestoresExactPriorValue(): void public function testNonCoroutineConnectionIsRetainedUntilTerminalRelease(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $firstWrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - $secondWrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - $firstConnection = m::mock(Connection::class); - $secondConnection = m::mock(Connection::class); - - $poolManager->expects('pool')->twice()->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->twice()->andReturn($firstWrapper, $secondWrapper); - $firstWrapper->expects('getConnection')->andReturn($firstConnection); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $firstWrapper = Double::for(PooledConnection::class); + $firstWrapper->allows('recordDateFormat'); + $firstWrapper->allows('usesSessionLeases')->returns(false); + $secondWrapper = Double::for(PooledConnection::class); + $secondWrapper->allows('recordDateFormat'); + $secondWrapper->allows('usesSessionLeases')->returns(false); + $firstConnection = Double::for(Connection::class); + $secondConnection = Double::for(Connection::class); + + $poolManager->expects('pool')->times(2)->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->times(2)->returns($firstWrapper, $secondWrapper); + $firstWrapper->expects('getConnection')->returns($firstConnection); $firstWrapper->expects('dispatchConnectionEstablishedEvent'); $firstWrapper->expects('release'); - $secondWrapper->expects('getConnection')->andReturn($secondConnection); + $secondWrapper->expects('getConnection')->returns($secondConnection); $secondWrapper->expects('dispatchConnectionEstablishedEvent'); $secondWrapper->expects('release'); @@ -162,18 +169,20 @@ public function testNonCoroutineConnectionIsRetainedUntilTerminalRelease(): void public function testTerminalReleaseOwnsEveryRequestedConnectionRole(): void { - $poolManager = m::mock(PoolManager::class); + $poolManager = Double::for(PoolManager::class); $resolver = $this->makeResolver('mysql', $poolManager); foreach (['mysql' => null, 'mysql::read' => 'read', 'mysql::write' => 'write'] as $name => $role) { - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - $connection = m::mock(Connection::class); - - $poolManager->expects('pool')->once()->with($name)->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn($connection); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('recordDateFormat'); + $wrapper->allows('usesSessionLeases')->returns(false); + $connection = Double::for(Connection::class); + + $poolManager->expects('pool')->with($name)->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns($connection); $wrapper->expects('dispatchConnectionEstablishedEvent'); $wrapper->expects('release'); @@ -193,17 +202,23 @@ public function testTerminalReleaseOwnsEveryRequestedConnectionRole(): void public function testBorrowedConnectionRetainsItsRequestedRole(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); $resolver = $this->makeResolver('sqlite', $poolManager); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + + $wrappers = [ + 'sqlite::write' => Double::for(PooledConnection::class), + 'sqlite' => Double::for(PooledConnection::class), + ]; + $pool->expects('borrow')->times(2)->returns(...array_values($wrappers)); - foreach (['sqlite::write', 'sqlite'] as $name) { + foreach ($wrappers as $name => $wrapper) { $connection = new PdoConnection(new PDO('sqlite::memory:'), config: ['name' => 'sqlite']); - $wrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - $poolManager->expects('pool')->with($name)->andReturn($pool); - $pool->expects('borrow')->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn($connection); + $wrapper->allows('recordDateFormat'); + $wrapper->allows('usesSessionLeases')->returns(false); + $poolManager->expects('pool')->with($name)->returns($pool); + $wrapper->expects('getConnection')->returns($connection); $wrapper->expects('dispatchConnectionEstablishedEvent'); $wrapper->expects('release'); @@ -216,20 +231,22 @@ public function testBorrowedConnectionRetainsItsRequestedRole(): void public function testSharedInMemorySqliteAliasesReuseOneConnectionOwner(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - $connection = m::mock(Connection::class); - - $poolManager->expects('pool')->once()->with('sqlite::read')->andReturn($pool); - $poolManager->expects('pool')->once()->with('sqlite::write')->andReturn($pool); - $pool->expects('getSharedInMemorySqlitePdo')->times(2)->andReturn(m::mock(PDO::class)); - $pool->expects('getName')->times(2)->andReturn('sqlite'); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->once()->andReturn($connection); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('recordDateFormat'); + $wrapper->allows('usesSessionLeases')->returns(false); + $connection = Double::for(Connection::class); + + $poolManager->expects('pool')->with('sqlite::read')->returns($pool); + $poolManager->expects('pool')->with('sqlite::write')->returns($pool); + $pool->expects('getSharedInMemorySqlitePdo')->times(2)->returns(Double::for(PDO::class)); + $pool->expects('getName')->times(2)->returns('sqlite'); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns($connection); $wrapper->expects('dispatchConnectionEstablishedEvent'); - $connection->expects('useWriteConnectionWhenReading')->once(); - $wrapper->expects('release')->once(); + $connection->expects('useWriteConnectionWhenReading'); + $wrapper->expects('release'); $resolver = $this->makeResolver('sqlite', $poolManager); @@ -242,26 +259,30 @@ public function testSharedInMemorySqliteAliasesReuseOneConnectionOwner(): void public function testTerminalStateRemainsAvailableUntilItsOwnerIsReleased(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $firstWrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - $secondWrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - $firstConnection = m::mock(Connection::class); - $secondConnection = m::mock(Connection::class); - - $poolManager->expects('pool')->twice()->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->twice()->andReturn($firstWrapper, $secondWrapper); - $firstWrapper->expects('getConnection')->andReturn($firstConnection); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $firstWrapper = Double::for(PooledConnection::class); + $firstWrapper->allows('recordDateFormat'); + $firstWrapper->allows('usesSessionLeases')->returns(false); + $secondWrapper = Double::for(PooledConnection::class); + $secondWrapper->allows('recordDateFormat'); + $secondWrapper->allows('usesSessionLeases')->returns(false); + $firstConnection = Double::for(Connection::class); + $secondConnection = Double::for(Connection::class); + + $poolManager->expects('pool')->times(2)->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->times(2)->returns($firstWrapper, $secondWrapper); + $firstWrapper->expects('getConnection')->returns($firstConnection); $firstWrapper->expects('dispatchConnectionEstablishedEvent'); - $secondWrapper->expects('getConnection')->andReturn($secondConnection); + $secondWrapper->expects('getConnection')->returns($secondConnection); $secondWrapper->expects('dispatchConnectionEstablishedEvent'); $secondWrapper->expects('release'); $resolver = $this->makeResolver('mysql', $poolManager); $resolver->setDefaultConnection('reporting'); - $firstWrapper->expects('release')->andReturnUsing(function () use ($resolver, $firstConnection): void { + $firstWrapper->expects('release')->resolves(function () use ($resolver, $firstConnection): void { $this->assertSame('reporting', $resolver->getDefaultConnection()); $this->assertSame($firstConnection, $resolver->connection('mysql')); }); @@ -278,22 +299,24 @@ public function testTerminalReleaseExhaustsConnectionsAndPreservesTheFirstFailur { $firstException = new RuntimeException('First release failed.'); $secondException = new RuntimeException('Second release failed.'); - $poolManager = m::mock(PoolManager::class); + $poolManager = Double::for(PoolManager::class); $resolver = $this->makeResolver('first', $poolManager); foreach ([ ['first', $firstException], ['second', $secondException], ] as [$name, $exception]) { - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - - $poolManager->expects('pool')->once()->with($name)->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn(m::mock(Connection::class)); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('recordDateFormat'); + $wrapper->allows('usesSessionLeases')->returns(false); + + $poolManager->expects('pool')->with($name)->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns(Double::for(Connection::class)); $wrapper->expects('dispatchConnectionEstablishedEvent'); - $wrapper->expects('release')->andThrow($exception); + $wrapper->expects('release')->throws($exception); $resolver->connection($name); } @@ -318,7 +341,7 @@ public function testTerminalReleasePrioritizesTheFirstCancellationAndStillExhaus $firstCancellation = new RuntimeException('Release cleanup failed.', previous: $firstCancellation); } $secondCancellation = new CanceledException('Third release was canceled.'); - $poolManager = m::mock(PoolManager::class); + $poolManager = Double::for(PoolManager::class); $resolver = $this->makeResolver('first', $poolManager); foreach ([ @@ -326,15 +349,17 @@ public function testTerminalReleasePrioritizesTheFirstCancellationAndStillExhaus ['second', $firstCancellation], ['third', $secondCancellation], ] as [$name, $failure]) { - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - - $poolManager->expects('pool')->once()->with($name)->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn(m::mock(Connection::class)); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('recordDateFormat'); + $wrapper->allows('usesSessionLeases')->returns(false); + + $poolManager->expects('pool')->with($name)->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns(Double::for(Connection::class)); $wrapper->expects('dispatchConnectionEstablishedEvent'); - $wrapper->expects('release')->andThrow($failure); + $wrapper->expects('release')->throws($failure); $resolver->connection($name); } @@ -351,17 +376,19 @@ public function testTerminalReleasePrioritizesTheFirstCancellationAndStillExhaus public function testTerminalDiscardExhaustsExactConnections(): void { - $poolManager = m::mock(PoolManager::class); + $poolManager = Double::for(PoolManager::class); $resolver = $this->makeResolver('first', $poolManager); foreach (['first', 'second'] as $name) { - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - - $poolManager->expects('pool')->once()->with($name)->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn(m::mock(Connection::class)); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('recordDateFormat'); + $wrapper->allows('usesSessionLeases')->returns(false); + + $poolManager->expects('pool')->with($name)->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns(Double::for(Connection::class)); $wrapper->expects('dispatchConnectionEstablishedEvent'); $wrapper->expects('discard'); @@ -375,14 +402,15 @@ public function testTerminalDiscardExhaustsExactConnections(): void public function testConnectionRetrievalFailureDiscardsTheExactWrapper(): void { $exception = new RuntimeException('Connection retrieval failed.'); - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); - - $poolManager->expects('pool')->once()->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andThrow($exception); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); + + $poolManager->expects('pool')->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->throws($exception); $wrapper->expects('discard'); $resolver = $this->makeResolver('mysql', $poolManager); @@ -398,17 +426,18 @@ public function testConnectionRetrievalFailureDiscardsTheExactWrapper(): void public function testListenerFailureDiscardsTheExactWrapperWithoutDeferringRelease(): void { $exception = new RuntimeException('Connection listener failed.'); - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); - - $poolManager->expects('pool')->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn(m::mock(Connection::class)); - $wrapper->expects('dispatchConnectionEstablishedEvent')->andThrow($exception); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); + + $poolManager->expects('pool')->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns(Double::for(Connection::class)); + $wrapper->expects('dispatchConnectionEstablishedEvent')->throws($exception); $wrapper->expects('discard'); - $wrapper->shouldNotReceive('release'); + $wrapper->expects('release')->never(); $resolver = $this->makeResolver('mysql', $poolManager); $caught = null; @@ -427,17 +456,18 @@ public function testListenerFailureDiscardsTheExactWrapperWithoutDeferringReleas public function testWriteRoleConfigurationFailureDiscardsTheExactWrapper(): void { $exception = new RuntimeException('Write role configuration failed.'); - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); - $connection = m::mock(Connection::class); - - $poolManager->expects('pool')->once()->with('mysql::write')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn($connection); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); + $connection = Double::for(Connection::class); + + $poolManager->expects('pool')->with('mysql::write')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns($connection); $connection->expects('setReadWriteType')->with('write'); - $connection->expects('useWriteConnectionWhenReading')->andThrow($exception); + $connection->expects('useWriteConnectionWhenReading')->throws($exception); $wrapper->expects('discard'); $resolver = $this->makeResolver('mysql', $poolManager); @@ -454,15 +484,16 @@ public function testDiscardFailureDoesNotReplaceTheSetupFailure(): void { $setupException = new RuntimeException('Connection retrieval failed.'); $discardException = new RuntimeException('Discard failed.'); - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); - $poolManager->expects('pool')->once()->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andThrow($setupException); - $wrapper->expects('discard')->andThrow($discardException); + $poolManager->expects('pool')->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->throws($setupException); + $wrapper->expects('discard')->throws($discardException); $resolver = $this->makeResolver('mysql', $poolManager); @@ -481,15 +512,16 @@ public function testDiscardCancellationReplacesAnOrdinarySetupFailure(bool $chai $setupException = new RuntimeException('Connection retrieval failed.'); $discardCancellation = new CanceledException('Discard was canceled.'); $discardCancellation = $chained ? new RuntimeException('Discard cleanup failed.', previous: $discardCancellation) : $discardCancellation; - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); - $poolManager->expects('pool')->once()->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andThrow($setupException); - $wrapper->expects('discard')->andThrow($discardCancellation); + $poolManager->expects('pool')->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->throws($setupException); + $wrapper->expects('discard')->throws($discardCancellation); $resolver = $this->makeResolver('mysql', $poolManager); @@ -505,15 +537,16 @@ public function testSetupCancellationRemainsPrimaryOverAnOrdinaryDiscardFailure( { $setupCancellation = new CanceledException('Connection setup was canceled.'); $discardException = new RuntimeException('Discard failed.'); - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); - $poolManager->expects('pool')->once()->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andThrow($setupCancellation); - $wrapper->expects('discard')->andThrow($discardException); + $poolManager->expects('pool')->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->throws($setupCancellation); + $wrapper->expects('discard')->throws($discardException); $resolver = $this->makeResolver('mysql', $poolManager); @@ -532,15 +565,16 @@ public function testSetupCancellationRemainsPrimaryOverDiscardCancellation(bool $setupCancellation = new CanceledException('Connection setup was canceled.'); $setupCancellation = $chained ? new RuntimeException('Connection setup cleanup failed.', previous: $setupCancellation) : $setupCancellation; $discardCancellation = new CanceledException('Discard was canceled.'); - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); - $poolManager->expects('pool')->once()->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andThrow($setupCancellation); - $wrapper->expects('discard')->andThrow($discardCancellation); + $poolManager->expects('pool')->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->throws($setupCancellation); + $wrapper->expects('discard')->throws($discardCancellation); $resolver = $this->makeResolver('mysql', $poolManager); @@ -554,15 +588,17 @@ public function testSetupCancellationRemainsPrimaryOverDiscardCancellation(bool public function testCoroutineConnectionRemainsDeferOwned(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['recordDateFormat' => null, 'usesSessionLeases' => false]); - $connection = m::mock(Connection::class); - - $poolManager->expects('pool')->once()->with('mysql')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn($connection); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('recordDateFormat'); + $wrapper->allows('usesSessionLeases')->returns(false); + $connection = Double::for(Connection::class); + + $poolManager->expects('pool')->with('mysql')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns($connection); $wrapper->expects('dispatchConnectionEstablishedEvent'); $wrapper->expects('release'); @@ -578,14 +614,14 @@ public function testCoroutineConnectionRemainsDeferOwned(): void public function testConnectionDateFormatReadsThePoolsRecordWithoutBorrowing(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $poolManager->expects('existing')->with('pgsql')->andReturn($pool); - $poolManager->expects('existing')->with('pgsql::write')->andReturn($pool); - $poolManager->shouldNotReceive('pool'); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->allows('recordedDateFormat')->andReturn('Y-m-d H:i:s.u'); - $pool->shouldNotReceive('borrow'); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $poolManager->expects('existing')->with('pgsql')->returns($pool); + $poolManager->expects('existing')->with('pgsql::write')->returns($pool); + $poolManager->expects('pool')->never(); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->allows('recordedDateFormat')->returns('Y-m-d H:i:s.u'); + $pool->expects('borrow')->never(); $resolver = $this->makeResolver('pgsql', $poolManager); run(function () use ($resolver): void { @@ -597,16 +633,17 @@ public function testConnectionDateFormatReadsThePoolsRecordWithoutBorrowing(): v public function testConnectionDateFormatPrefersTheGrammarOfAHeldConnection(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); $connection = new PdoConnection(new PDO('sqlite::memory:'), config: ['name' => 'sqlite']); - $poolManager->expects('pool')->with('sqlite')->andReturn($pool); - $poolManager->shouldNotReceive('existing'); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->andReturn($wrapper); + $poolManager->expects('pool')->with('sqlite')->returns($pool); + $poolManager->expects('existing')->never(); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); $wrapper->expects('recordDateFormat'); - $wrapper->expects('getConnection')->andReturn($connection); + $wrapper->expects('getConnection')->returns($connection); $wrapper->expects('dispatchConnectionEstablishedEvent'); $wrapper->expects('release'); $resolver = $this->makeResolver('sqlite', $poolManager); @@ -624,19 +661,20 @@ public function testConnectionDateFormatPrefersTheGrammarOfAHeldConnection(): vo public function testSharedInMemorySqliteAliasesReadTheFormatOfTheirHeldOwner(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); $connection = new PdoConnection(new PDO('sqlite::memory:'), config: ['name' => 'sqlite']); $connection->setQueryGrammar(new ConnectionResolverTestTimestampGrammar($connection)); - $poolManager->expects('pool')->with('sqlite::write')->andReturn($pool); - $poolManager->expects('existing')->with('sqlite::read')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturn(m::mock(PDO::class)); - $pool->allows('getName')->andReturn('sqlite'); + $poolManager->expects('pool')->with('sqlite::write')->returns($pool); + $poolManager->expects('existing')->with('sqlite::read')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(Double::for(PDO::class)); + $pool->allows('getName')->returns('sqlite'); $wrapper->expects('recordDateFormat'); - $pool->shouldNotReceive('recordedDateFormat'); - $pool->expects('borrow')->andReturn($wrapper); - $wrapper->expects('getConnection')->andReturn($connection); + $pool->expects('recordedDateFormat')->never(); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('getConnection')->returns($connection); $wrapper->expects('dispatchConnectionEstablishedEvent'); $wrapper->expects('release'); $resolver = $this->makeResolver('sqlite', $poolManager); @@ -650,17 +688,18 @@ public function testSharedInMemorySqliteAliasesReadTheFormatOfTheirHeldOwner(): public function testConnectionDateFormatResolvesTheConnectionWhileNoOpenPoolHasRecordedOne(): void { - $poolManager = m::mock(PoolManager::class); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class, ['usesSessionLeases' => false]); + $poolManager = Double::for(PoolManager::class); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $wrapper->allows('usesSessionLeases')->returns(false); $connection = new PdoConnection(new PDO('sqlite::memory:'), config: ['name' => 'sqlite']); // A purged pool is no longer found, so its old record cannot answer. - $poolManager->expects('existing')->twice()->with('sqlite')->andReturn(null, $pool); - $poolManager->expects('pool')->with('sqlite')->andReturn($pool); - $pool->allows('getSharedInMemorySqlitePdo')->andReturnNull(); - $pool->expects('borrow')->andReturn($wrapper); + $poolManager->expects('existing')->times(2)->with('sqlite')->returns(null, $pool); + $poolManager->expects('pool')->with('sqlite')->returns($pool); + $pool->allows('getSharedInMemorySqlitePdo')->returns(null); + $pool->expects('borrow')->returns($wrapper); $wrapper->expects('recordDateFormat'); - $wrapper->expects('getConnection')->andReturn($connection); + $wrapper->expects('getConnection')->returns($connection); $wrapper->expects('dispatchConnectionEstablishedEvent'); $wrapper->expects('release'); $resolver = $this->makeResolver('sqlite', $poolManager); @@ -679,7 +718,7 @@ protected function makeResolver( $app->instance('config', new Repository([ 'database' => ['default' => $configuredDefault], ])); - $app->instance(PoolManager::class, $poolManager ?? m::mock(PoolManager::class)); + $app->instance(PoolManager::class, $poolManager ?? Double::for(PoolManager::class)); return new ConnectionResolver($app); } diff --git a/tests/Database/ConnectionTest.php b/tests/Database/ConnectionTest.php index f247185555..07e214169e 100644 --- a/tests/Database/ConnectionTest.php +++ b/tests/Database/ConnectionTest.php @@ -11,7 +11,8 @@ use Hypervel\Support\Facades\DB; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -23,6 +24,8 @@ #[WithConfig('database.default', 'testing')] class ConnectionTest extends TestCase { + use VerifiesDoubles; + /** * Test that disconnect() rolls back any open transaction. * @@ -107,8 +110,8 @@ public function testDisconnectCancellationFromTransactionResetSupersedesAnOrdina $resetCancellation = new CanceledException('Transaction reset was canceled.'); $connection = new DisconnectFailureConnection(new PDO('sqlite::memory:')); $connection->disconnectFailure = $driverFailure; - $manager = m::mock(DatabaseTransactionsManager::class); - $manager->expects('rollback')->once()->with('', 0)->andThrow($resetCancellation); + $manager = Double::for(DatabaseTransactionsManager::class); + $manager->expects('rollback')->with('', 0)->throws($resetCancellation); $connection->setTransactionManager($manager); try { @@ -127,8 +130,8 @@ public function testDisconnectPreservesDriverCancellationOverAnOrdinaryTransacti $resetFailure = new RuntimeException('Transaction reset failed.'); $connection = new DisconnectFailureConnection(new PDO('sqlite::memory:')); $connection->disconnectFailure = $driverCancellation; - $manager = m::mock(DatabaseTransactionsManager::class); - $manager->expects('rollback')->once()->with('', 0)->andThrow($resetFailure); + $manager = Double::for(DatabaseTransactionsManager::class); + $manager->expects('rollback')->with('', 0)->throws($resetFailure); $connection->setTransactionManager($manager); try { @@ -147,8 +150,8 @@ public function testDisconnectPreservesTheFirstCancellationWhenTransactionResetI $resetCancellation = new CanceledException('Transaction reset was canceled.'); $connection = new DisconnectFailureConnection(new PDO('sqlite::memory:')); $connection->disconnectFailure = $driverCancellation; - $manager = m::mock(DatabaseTransactionsManager::class); - $manager->expects('rollback')->once()->with('', 0)->andThrow($resetCancellation); + $manager = Double::for(DatabaseTransactionsManager::class); + $manager->expects('rollback')->with('', 0)->throws($resetCancellation); $connection->setTransactionManager($manager); try { @@ -167,8 +170,8 @@ public function testDisconnectPreservesTheFirstOrdinaryFailureAfterTransactionRe $resetFailure = new RuntimeException('Transaction reset failed.'); $connection = new DisconnectFailureConnection(new PDO('sqlite::memory:')); $connection->disconnectFailure = $driverFailure; - $manager = m::mock(DatabaseTransactionsManager::class); - $manager->expects('rollback')->once()->with('', 0)->andThrow($resetFailure); + $manager = Double::for(DatabaseTransactionsManager::class); + $manager->expects('rollback')->with('', 0)->throws($resetFailure); $connection->setTransactionManager($manager); try { diff --git a/tests/Database/DatabaseAbstractSchemaGrammarTest.php b/tests/Database/DatabaseAbstractSchemaGrammarTest.php index 7810e425ed..4c35058ad3 100755 --- a/tests/Database/DatabaseAbstractSchemaGrammarTest.php +++ b/tests/Database/DatabaseAbstractSchemaGrammarTest.php @@ -8,13 +8,16 @@ use Hypervel\Database\PdoConnection; use Hypervel\Database\Schema\Grammars\Grammar; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; class DatabaseAbstractSchemaGrammarTest extends TestCase { + use VerifiesDoubles; + public function testCreateDatabase(): void { $connection = new PdoConnection(new PDO('sqlite::memory:')); @@ -38,7 +41,7 @@ public function testDropDatabaseIfExists(): void #[TestWith(['compileCreateRangePartition', ['users', 'users_1', [1], [2]]])] public function testPartitioningIsUnsupportedByDefault(string $method, array $arguments): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new class($connection) extends Grammar { }; diff --git a/tests/Database/DatabaseApplicableTransactionTest.php b/tests/Database/DatabaseApplicableTransactionTest.php index 98c7a44d3a..11ba24c867 100644 --- a/tests/Database/DatabaseApplicableTransactionTest.php +++ b/tests/Database/DatabaseApplicableTransactionTest.php @@ -11,13 +11,16 @@ use Hypervel\Engine\Channel; use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use UnitEnum; use function Hypervel\Coroutine\parallel; class DatabaseApplicableTransactionTest extends TestCase { + use VerifiesDoubles; + /** * Configure two isolated databases with one slot each. */ @@ -99,8 +102,8 @@ public function testCurrentDefaultAndSharedSqliteRoleAliasesUseTheirHeldConnecti public function testCustomManagerResolversProvideTransactionStateAndDateFormat(): void { $connection = DB::connection('first'); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with('first')->times(3)->andReturn($connection); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with('first')->times(3)->returns($connection); $this->app->instance('db.resolver', $resolver); $this->assertFalse(DB::hasApplicableTransaction()); @@ -132,8 +135,8 @@ public function testCustomModelResolversUseTheirActualConnection(): void { $connection = DB::connection('second'); $connection->beginTransaction(); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->with(null)->once()->andReturn($connection); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with(null)->returns($connection); Model::setConnectionResolver($resolver); try { diff --git a/tests/Database/DatabaseConnectionLeaseTest.php b/tests/Database/DatabaseConnectionLeaseTest.php index 5c3b18a9a4..b3d44188ae 100644 --- a/tests/Database/DatabaseConnectionLeaseTest.php +++ b/tests/Database/DatabaseConnectionLeaseTest.php @@ -57,8 +57,9 @@ use Hypervel\Tests\Grpc\Fixtures\ClientCallClient; use Hypervel\Tests\Grpc\Fixtures\ClientCallClientFactory; use Hypervel\Tests\Socialite\Fixtures\GenericTestProviderStub; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; @@ -74,6 +75,8 @@ class DatabaseConnectionLeaseTest extends TestCase { + use VerifiesDoubles; + /** * Configure a single physical slot shared by independently owned connections. */ @@ -1022,13 +1025,13 @@ public function testAcquisitionCleanupPropagatesWrappedCancellation(): void 'database' => ':memory:', 'prefix' => '', ]); - $pool = m::mock(DatabasePool::class); - $wrapper = m::mock(PooledConnection::class); - $pool->expects('borrow')->once()->andReturn($wrapper); - $wrapper->expects('attachLease')->twice(); - $wrapper->expects('getDriverConnection')->once()->andReturn($physical); - $wrapper->expects('dispatchConnectionEstablishedEvent')->once()->andThrow($setupFailure); - $wrapper->expects('discard')->once()->andThrow($cleanupFailure); + $pool = Double::for(DatabasePool::class); + $wrapper = Double::for(PooledConnection::class); + $pool->expects('borrow')->returns($wrapper); + $wrapper->expects('attachLease')->times(2); + $wrapper->expects('getDriverConnection')->returns($physical); + $wrapper->expects('dispatchConnectionEstablishedEvent')->throws($setupFailure); + $wrapper->expects('discard')->throws($cleanupFailure); $lease = new ConnectionLease($pool, $wrapper, $this->app->make('db.factory'), $physical); $lease->detach(); diff --git a/tests/Database/DatabaseConnectionLifecycleListenerTest.php b/tests/Database/DatabaseConnectionLifecycleListenerTest.php index 7825ac8a55..b3ecc74c3d 100644 --- a/tests/Database/DatabaseConnectionLifecycleListenerTest.php +++ b/tests/Database/DatabaseConnectionLifecycleListenerTest.php @@ -10,83 +10,86 @@ use Hypervel\Database\Pool\PoolManager; use Hypervel\Database\SimpleConnectionResolver; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Swoole\Coroutine\CanceledException; class DatabaseConnectionLifecycleListenerTest extends TestCase { + use VerifiesDoubles; + public function testTaskCleanupDoesNotResolveAnUnusedResolver(): void { - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnFalse(); - $container->shouldNotReceive('make'); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(false); + $container->expects('make')->never(); - (new DatabaseConnectionLifecycleListener($container))->releaseTaskConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->releaseTaskConnections(); } public function testTaskCleanupReleasesTheConcretePooledResolver(): void { - $resolver = m::mock(ConnectionResolver::class); + $resolver = Double::for(ConnectionResolver::class); $resolver->expects('releaseConnections'); - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnTrue(); - $container->expects('make')->with('db.resolver')->andReturn($resolver); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(true); + $container->expects('make')->with('db.resolver')->returns($resolver); - (new DatabaseConnectionLifecycleListener($container))->releaseTaskConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->releaseTaskConnections(); } public function testTaskCleanupLeavesCustomResolversAlone(): void { - $resolver = m::mock(SimpleConnectionResolver::class); - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnTrue(); - $container->expects('make')->with('db.resolver')->andReturn($resolver); + $resolver = Double::for(SimpleConnectionResolver::class)->strict(); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(true); + $container->expects('make')->with('db.resolver')->returns($resolver); - (new DatabaseConnectionLifecycleListener($container))->releaseTaskConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->releaseTaskConnections(); } public function testProcessCleanupDoesNotResolveUnusedOwners(): void { - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnFalse(); - $container->expects('resolved')->with(PoolManager::class)->andReturnFalse(); - $container->shouldNotReceive('make'); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(false); + $container->expects('resolved')->with(PoolManager::class)->returns(false); + $container->expects('make')->never(); - (new DatabaseConnectionLifecycleListener($container))->discardProcessConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->discardProcessConnections(); } public function testProcessCleanupDiscardsResolverAndPurgesPools(): void { - $resolver = m::mock(ConnectionResolver::class); + $resolver = Double::for(ConnectionResolver::class); $resolver->expects('discardConnections'); - $poolManager = m::mock(PoolManager::class); + $poolManager = Double::for(PoolManager::class); $poolManager->expects('purgeAll'); - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnTrue(); - $container->expects('make')->with('db.resolver')->andReturn($resolver); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(true); + $container->expects('make')->with('db.resolver')->returns($resolver); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); - (new DatabaseConnectionLifecycleListener($container))->discardProcessConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->discardProcessConnections(); } public function testResolverFailureDoesNotSkipPoolPurgeAndRemainsPrimary(): void { $resolverException = new RuntimeException('Resolver discard failed.'); $purgeException = new RuntimeException('Pool purge failed.'); - $resolver = m::mock(ConnectionResolver::class); - $resolver->expects('discardConnections')->andThrow($resolverException); - $poolManager = m::mock(PoolManager::class); - $poolManager->expects('purgeAll')->andThrow($purgeException); - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnTrue(); - $container->expects('make')->with('db.resolver')->andReturn($resolver); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $resolver = Double::for(ConnectionResolver::class); + $resolver->expects('discardConnections')->throws($resolverException); + $poolManager = Double::for(PoolManager::class); + $poolManager->expects('purgeAll')->throws($purgeException); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(true); + $container->expects('make')->with('db.resolver')->returns($resolver); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); try { - (new DatabaseConnectionLifecycleListener($container))->discardProcessConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->discardProcessConnections(); $this->fail('Expected the resolver failure to propagate.'); } catch (RuntimeException $throwable) { $this->assertSame($resolverException, $throwable); @@ -96,18 +99,18 @@ public function testResolverFailureDoesNotSkipPoolPurgeAndRemainsPrimary(): void public function testPoolPurgeFailurePropagatesAfterResolverCleanup(): void { $exception = new RuntimeException('Pool purge failed.'); - $resolver = m::mock(ConnectionResolver::class); + $resolver = Double::for(ConnectionResolver::class); $resolver->expects('discardConnections'); - $poolManager = m::mock(PoolManager::class); - $poolManager->expects('purgeAll')->andThrow($exception); - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnTrue(); - $container->expects('make')->with('db.resolver')->andReturn($resolver); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $poolManager = Double::for(PoolManager::class); + $poolManager->expects('purgeAll')->throws($exception); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(true); + $container->expects('make')->with('db.resolver')->returns($resolver); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); try { - (new DatabaseConnectionLifecycleListener($container))->discardProcessConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->discardProcessConnections(); $this->fail('Expected the pool purge failure to propagate.'); } catch (RuntimeException $throwable) { $this->assertSame($exception, $throwable); @@ -118,18 +121,18 @@ public function testPoolPurgeCancellationSupersedesAnOrdinaryResolverFailure(): { $resolverException = new RuntimeException('Resolver discard failed.'); $purgeCancellation = new CanceledException('Pool purge was canceled.'); - $resolver = m::mock(ConnectionResolver::class); - $resolver->expects('discardConnections')->andThrow($resolverException); - $poolManager = m::mock(PoolManager::class); - $poolManager->expects('purgeAll')->andThrow($purgeCancellation); - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnTrue(); - $container->expects('make')->with('db.resolver')->andReturn($resolver); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $resolver = Double::for(ConnectionResolver::class); + $resolver->expects('discardConnections')->throws($resolverException); + $poolManager = Double::for(PoolManager::class); + $poolManager->expects('purgeAll')->throws($purgeCancellation); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(true); + $container->expects('make')->with('db.resolver')->returns($resolver); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); try { - (new DatabaseConnectionLifecycleListener($container))->discardProcessConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->discardProcessConnections(); $this->fail('Expected pool purge cancellation to propagate.'); } catch (CanceledException $throwable) { $this->assertSame($purgeCancellation, $throwable); @@ -140,18 +143,18 @@ public function testResolverCancellationRemainsPrimaryOverAnOrdinaryPoolPurgeFai { $resolverCancellation = new CanceledException('Resolver discard was canceled.'); $purgeException = new RuntimeException('Pool purge failed.'); - $resolver = m::mock(ConnectionResolver::class); - $resolver->expects('discardConnections')->andThrow($resolverCancellation); - $poolManager = m::mock(PoolManager::class); - $poolManager->expects('purgeAll')->andThrow($purgeException); - $container = m::mock(Container::class); - $container->expects('resolved')->with('db.resolver')->andReturnTrue(); - $container->expects('make')->with('db.resolver')->andReturn($resolver); - $container->expects('resolved')->with(PoolManager::class)->andReturnTrue(); - $container->expects('make')->with(PoolManager::class)->andReturn($poolManager); + $resolver = Double::for(ConnectionResolver::class); + $resolver->expects('discardConnections')->throws($resolverCancellation); + $poolManager = Double::for(PoolManager::class); + $poolManager->expects('purgeAll')->throws($purgeException); + $container = Double::for(Container::class, override: true); + $container->expects('resolved')->with('db.resolver')->returns(true); + $container->expects('make')->with('db.resolver')->returns($resolver); + $container->expects('resolved')->with(PoolManager::class)->returns(true); + $container->expects('make')->with(PoolManager::class)->returns($poolManager); try { - (new DatabaseConnectionLifecycleListener($container))->discardProcessConnections(); + (new DatabaseConnectionLifecycleListener($container->instance()))->discardProcessConnections(); $this->fail('Expected resolver cancellation to propagate.'); } catch (CanceledException $throwable) { $this->assertSame($resolverCancellation, $throwable); diff --git a/tests/Database/DatabaseDbCommandLaunchTest.php b/tests/Database/DatabaseDbCommandLaunchTest.php index c62b5ccdb3..c7e38a7d49 100644 --- a/tests/Database/DatabaseDbCommandLaunchTest.php +++ b/tests/Database/DatabaseDbCommandLaunchTest.php @@ -12,18 +12,20 @@ use Hypervel\Database\DatabaseCliConfiguration; use Hypervel\Database\DatabaseCliManager; use Hypervel\Tests\TestCase; -use Mockery as m; -use PHPUnit\Framework\Attributes\PreserveGlobalState; -use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; use Symfony\Component\Process\Process; -// Process overloads must never enter the shared PHPUnit worker. -#[RunTestsInSeparateProcesses] -#[PreserveGlobalState(false)] class DatabaseDbCommandLaunchTest extends TestCase { + use VerifiesDoubles; + + private DoubleInterface $application; + public function testBuiltInLaunchUsesThePublicAndProtectedOverrides(): void { $command = new class extends DbCommand { @@ -108,16 +110,16 @@ public function testHostlessExtensionResolvesOnceForTheLaunch(): void */ private function prepareCommand(DbCommand $command, DatabaseCliManager $manager, array $connection): BufferedOutput { - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with(DatabaseCliManager::class)->andReturn($manager); - $application->shouldReceive('make')->once()->with('config')->andReturn(new Repository([ + $this->application = Double::for(Application::class, override: true); + $this->application->expects('make')->with(DatabaseCliManager::class)->returns($manager); + $this->application->expects('make')->with('config')->returns(new Repository([ 'database' => ['default' => 'testing', 'connections' => ['testing' => $connection]], ])); $input = new ArrayInput([]); $input->bind($command->getDefinition()); $output = new BufferedOutput; - $command->setHypervel($application); + $command->setHypervel($this->application->instance()); $command->setInput($input); $command->setOutput(new OutputStyle($input, $output)); @@ -129,17 +131,19 @@ private function prepareCommand(DbCommand $command, DatabaseCliManager $manager, */ private function expectProcess(array $arguments, array $environment): void { - $execution = m::mock(); - $execution->shouldReceive('setTty')->once()->with(true)->andReturnSelf(); - $execution->shouldReceive('mustRun')->once()->with(m::type(Closure::class)) - ->andReturnUsing(function (Closure $callback) use ($execution): m\MockInterface { + $process = Double::for(Process::class); + $process->expects('setTimeout')->with(null); + $process->expects('setTty')->with(true); + $process->expects('mustRun')->with(Argument::type(Closure::class)) + ->resolves(function (Closure $callback) use ($process): Process { $callback('out', 'connected'); - return $execution; + return $process; }); - $process = m::mock('overload:' . Process::class); - $process->shouldReceive('__construct')->once()->with($arguments, null, $environment); - $process->shouldReceive('setTimeout')->once()->with(null)->andReturn($execution); + $this->application->expects('make')->with(Process::class, [ + 'command' => $arguments, + 'env' => $environment, + ])->returns($process); } } diff --git a/tests/Database/DatabaseDbCommandTest.php b/tests/Database/DatabaseDbCommandTest.php index bef9096fb1..063b087143 100644 --- a/tests/Database/DatabaseDbCommandTest.php +++ b/tests/Database/DatabaseDbCommandTest.php @@ -12,7 +12,9 @@ use Hypervel\Database\DatabaseCliManager; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\DoubleInterface; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use Symfony\Component\Console\Input\ArrayInput; @@ -22,6 +24,8 @@ class DatabaseDbCommandTest extends TestCase { + use VerifiesDoubles; + // REMOVED: Laravel's ::direct and --pooled command routing. Select the configured endpoint by name. public function testDbCommandReadAndWriteOptionsUsePooledConnectionBranches(): void @@ -400,8 +404,8 @@ public function testMissingBuiltInHostReturnsFailureWithTheExistingGuidance(): v $application = $this->applicationWithConfig([ 'mysql' => $this->mysqlConfig(['host' => []]), ]); - $application->shouldReceive('make')->once()->with(DatabaseCliManager::class)->andReturn(new DatabaseCliManager); - $command->setHypervel($application); + $application->expects('make')->with(DatabaseCliManager::class)->returns(new DatabaseCliManager); + $command->setHypervel($application->instance()); $input = $this->inputFor($command, []); $output = new BufferedOutput; @@ -420,7 +424,7 @@ public function testMissingBuiltInHostReturnsFailureWithTheExistingGuidance(): v private function getConnection(array $connections, array $input = []): array { $command = new DbCommand; - $command->setHypervel($this->applicationWithConfig($connections)); + $command->setHypervel($this->applicationWithConfig($connections)->instance()); $command->setInput($this->inputFor($command, $input)); return $command->getConnection(); @@ -429,13 +433,12 @@ private function getConnection(array $connections, array $input = []): array /** * Create an application with the supplied connection configuration. */ - private function applicationWithConfig(array $connections): Application&m\MockInterface + private function applicationWithConfig(array $connections): DoubleInterface { - $application = m::mock(Application::class); - $application->shouldReceive('make') - ->once() + $application = Double::for(Application::class, override: true); + $application->expects('make') ->with('config') - ->andReturn(new Repository([ + ->returns(new Repository([ 'database' => [ 'default' => 'mysql', 'connections' => $connections, diff --git a/tests/Database/DatabaseDriverConnectionLeaseTest.php b/tests/Database/DatabaseDriverConnectionLeaseTest.php index f76e7659c7..3146845095 100644 --- a/tests/Database/DatabaseDriverConnectionLeaseTest.php +++ b/tests/Database/DatabaseDriverConnectionLeaseTest.php @@ -17,8 +17,9 @@ use Hypervel\Support\Facades\DB; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Throwable; @@ -27,6 +28,8 @@ class DatabaseDriverConnectionLeaseTest extends TestCase { + use VerifiesDoubles; + protected int $generations = 0; /** @@ -190,8 +193,8 @@ public function testDisconnectClosesOnlyAHeldPhysicalConnectionAndEachGeneration public function testQueriesRunWhileReconnectingDoNotReconnectAgain(): void { $failure = new RuntimeException('The remote database connection was lost.'); - $detector = m::mock(LostConnectionDetector::class); - $detector->shouldReceive('causedByLostConnection')->with($failure)->andReturnTrue(); + $detector = Double::for(LostConnectionDetector::class); + $detector->allows('causedByLostConnection')->with($failure)->returns(true); $this->app->instance(LostConnectionDetector::class, $detector); $connection = DB::connection('leased'); $reconnects = 0; diff --git a/tests/Database/DatabaseEloquentCreateOrFirstValidationTest.php b/tests/Database/DatabaseEloquentCreateOrFirstValidationTest.php index 4227d0779b..864ead2972 100644 --- a/tests/Database/DatabaseEloquentCreateOrFirstValidationTest.php +++ b/tests/Database/DatabaseEloquentCreateOrFirstValidationTest.php @@ -12,23 +12,26 @@ use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseEloquentCreateOrFirstValidationTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('creationHelpers')] public function testRelatedBuilderValidationRunsBeforeQueriesAndValueCallbacks(string $relation, string $method): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('query')->andReturnUsing(fn () => new QueryBuilder($connection, new Grammar($connection), new Processor)); - $connection->shouldNotReceive('select'); - $connection->shouldNotReceive('insert'); - $connection->shouldNotReceive('update'); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->andReturn($connection); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); + $connection->allows('query')->resolves(fn () => new QueryBuilder($connection, new Grammar($connection), new Processor)); + $connection->expects('select')->never(); + $connection->expects('insert')->never(); + $connection->expects('update')->never(); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); Model::setConnectionResolver($resolver); $parent = new CreationValidationParent(['id' => 1]); $related = CreationValidationModel::class; diff --git a/tests/Database/DatabaseEloquentJsonCastTest.php b/tests/Database/DatabaseEloquentJsonCastTest.php index e82202617c..902000e781 100644 --- a/tests/Database/DatabaseEloquentJsonCastTest.php +++ b/tests/Database/DatabaseEloquentJsonCastTest.php @@ -18,11 +18,14 @@ use Hypervel\Support\Facades\Crypt; use Hypervel\Support\Fluent; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; class DatabaseEloquentJsonCastTest extends TestCase { + use VerifiesDoubles; + public function testPrimitiveJsonCastRoundTripsAtTheMaximumNestingDepth(): void { $value = $this->nestedValue(512); @@ -137,7 +140,7 @@ public function testJsonPathAssignmentRejectsEncoderFalseBeforeStorageOrEncrypti { $model = new JsonCastModel; $model->mergeCasts(['encrypted_payload' => 'encrypted:array']); - $encrypter = m::mock(Encrypter::class); + $encrypter = Double::for(Encrypter::class); $encrypter->expects('encrypt')->never(); Model::encryptUsing($encrypter); diff --git a/tests/Database/DatabaseEloquentRouteBindingTest.php b/tests/Database/DatabaseEloquentRouteBindingTest.php index 68e03ee3cf..9a14016512 100644 --- a/tests/Database/DatabaseEloquentRouteBindingTest.php +++ b/tests/Database/DatabaseEloquentRouteBindingTest.php @@ -10,18 +10,21 @@ use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\ModelNotFoundException; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; class DatabaseEloquentRouteBindingTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('invalidIntegerKeyProvider')] public function testItRejectsValuesThatCannotAddressAnIntegerKeyWithoutQuerying(mixed $value): void { - $query = m::mock(Builder::class); - $query->shouldNotReceive('where'); + $query = Double::for(Builder::class); + $query->expects('where')->never(); $this->expectException(ModelNotFoundException::class); @@ -52,8 +55,8 @@ public static function invalidIntegerKeyProvider(): array #[DataProvider('validIntegerKeyProvider')] public function testItPassesThroughValuesTheDatabaseCanStillMatch(int|string $value): void { - $query = m::mock(Builder::class); - $query->shouldReceive('where')->once()->with('id', $value)->andReturnSelf(); + $query = Double::for(Builder::class); + $query->expects('where')->with('id', $value); $this->assertSame($query, (new RouteBindingIntKeyModel)->resolveRouteBindingQuery($query, $value)); } @@ -80,8 +83,8 @@ public static function validIntegerKeyProvider(): array #[TestWith(['integer'])] public function testItValidatesQualifiedKeyColumnsFromChildBindings(string $keyType): void { - $query = m::mock(Builder::class); - $query->shouldNotReceive('where'); + $query = Double::for(Builder::class); + $query->expects('where')->never(); $this->expectException(ModelNotFoundException::class); @@ -90,16 +93,16 @@ public function testItValidatesQualifiedKeyColumnsFromChildBindings(string $keyT public function testItDoesNotValidateNonKeyBindingFields(): void { - $query = m::mock(Builder::class); - $query->shouldReceive('where')->once()->with('slug', 'abc')->andReturnSelf(); + $query = Double::for(Builder::class); + $query->expects('where')->with('slug', 'abc'); (new RouteBindingIntKeyModel)->resolveRouteBindingQuery($query, 'abc', 'slug'); } public function testItDoesNotValidateModelsWithStringKeys(): void { - $query = m::mock(Builder::class); - $query->shouldReceive('where')->once()->with('id', 'abc')->andReturnSelf(); + $query = Double::for(Builder::class); + $query->expects('where')->with('id', 'abc'); (new RouteBindingStringKeyModel)->resolveRouteBindingQuery($query, 'abc'); } @@ -109,8 +112,8 @@ public function testItDoesNotValidateModelsWithStringKeys(): void public function testItValidatesNonIncrementingModelsWithTheDefaultKeyType(): void { - $query = m::mock(Builder::class); - $query->shouldNotReceive('where'); + $query = Double::for(Builder::class); + $query->expects('where')->never(); $this->expectException(ModelNotFoundException::class); @@ -119,16 +122,16 @@ public function testItValidatesNonIncrementingModelsWithTheDefaultKeyType(): voi public function testItDoesNotValidateNullValuesForModelsWithStringKeys(): void { - $query = m::mock(Builder::class); - $query->shouldReceive('where')->once()->with('id', null)->andReturnSelf(); + $query = Double::for(Builder::class); + $query->expects('where')->with('id', null); (new RouteBindingStringKeyModel)->resolveRouteBindingQuery($query, null); } public function testTheInvalidKeyHandlerMayBeOverridden(): void { - $query = m::mock(Builder::class); - $query->shouldNotReceive('where'); + $query = Double::for(Builder::class); + $query->expects('where')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Invalid id: abc'); @@ -138,7 +141,7 @@ public function testTheInvalidKeyHandlerMayBeOverridden(): void public function testTheExceptionCarriesTheModelAndValue(): void { - $query = m::mock(Builder::class); + $query = Double::for(Builder::class); try { (new RouteBindingIntKeyModel)->resolveRouteBindingQuery($query, 'abc'); @@ -158,8 +161,8 @@ public function testTheExceptionCarriesTheModelAndValue(): void #[DataProvider('nullRouteKeyModelProvider')] public function testNullValuesCarryNoIdentifiers(string $model): void { - $query = m::mock(Builder::class); - $query->shouldNotReceive('where'); + $query = Double::for(Builder::class); + $query->expects('where')->never(); try { (new $model)->resolveRouteBindingQuery($query, null); @@ -187,8 +190,8 @@ public static function nullRouteKeyModelProvider(): array public function testItValidatesQualifiedUniqueIdColumnsFromChildBindings(): void { - $query = m::mock(Builder::class); - $query->shouldNotReceive('where'); + $query = Double::for(Builder::class); + $query->expects('where')->never(); $this->expectException(ModelNotFoundException::class); @@ -199,8 +202,8 @@ public function testItPassesQualifiedUniqueIdColumnsThroughForValidIds(): void { $uuid = '0190ecbd-0aa7-7cc8-9d51-4b4f6fb3a3c7'; - $query = m::mock(Builder::class); - $query->shouldReceive('where')->once()->with('route_binding_uuid_key_models.id', $uuid)->andReturnSelf(); + $query = Double::for(Builder::class); + $query->expects('where')->with('route_binding_uuid_key_models.id', $uuid); $this->assertSame($query, (new RouteBindingUuidKeyModel)->resolveRouteBindingQuery($query, $uuid, 'route_binding_uuid_key_models.id')); } diff --git a/tests/Database/DatabaseIntegrationTest.php b/tests/Database/DatabaseIntegrationTest.php index 05f7b6efd0..4dd49cd29e 100644 --- a/tests/Database/DatabaseIntegrationTest.php +++ b/tests/Database/DatabaseIntegrationTest.php @@ -4,43 +4,24 @@ namespace Hypervel\Tests\Database; -use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Database\Capsule\Manager as DB; use Hypervel\Database\Events\QueryExecuted; +use Hypervel\Events\Dispatcher; use Hypervel\Tests\TestCase; -use Mockery as m; class DatabaseIntegrationTest extends TestCase { - protected array $listeners = []; - protected function setUp(): void { parent::setUp(); - $this->listeners = []; - - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('listen')->andReturnUsing(function ($event, $callback) { - $this->listeners[$event] = $callback; - }); - $dispatcher->shouldReceive('hasListeners')->andReturnUsing(function ($event) { - return isset($this->listeners[$event]); - }); - $dispatcher->shouldReceive('dispatch')->andReturnUsing(function ($event) { - $eventClass = get_class($event); - if (isset($this->listeners[$eventClass])) { - ($this->listeners[$eventClass])($event); - } - }); - $db = new DB; $db->addConnection([ 'driver' => 'sqlite', 'database' => ':memory:', ]); $db->setAsGlobal(); - $db->setEventDispatcher($dispatcher); + $db->setEventDispatcher(new Dispatcher); } public function testQueryExecutedToRawSql(): void diff --git a/tests/Database/DatabaseManagerSetDefaultConnectionTest.php b/tests/Database/DatabaseManagerSetDefaultConnectionTest.php index 512f660ead..ddeb258659 100644 --- a/tests/Database/DatabaseManagerSetDefaultConnectionTest.php +++ b/tests/Database/DatabaseManagerSetDefaultConnectionTest.php @@ -13,7 +13,8 @@ use Hypervel\Database\Pool\PoolManager; use Hypervel\Engine\Coroutine; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; /** * Regression tests for DatabaseManager::setDefaultConnection() using @@ -23,6 +24,8 @@ */ class DatabaseManagerSetDefaultConnectionTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { CoroutineContext::forget(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY); @@ -124,9 +127,9 @@ protected function makeManager(array $databaseConfig, ?Repository $config = null $app = Container::getInstance(); $app->instance('config', $config); - $app->instance(PoolManager::class, m::mock(PoolManager::class)); + $app->instance(PoolManager::class, Double::for(PoolManager::class)); - $factory = m::mock(ConnectionFactory::class); + $factory = Double::for(ConnectionFactory::class); return new DatabaseManager($app, $factory); } diff --git a/tests/Database/DatabaseMariaDbConnectionTest.php b/tests/Database/DatabaseMariaDbConnectionTest.php index 9866926345..e0483c4b41 100644 --- a/tests/Database/DatabaseMariaDbConnectionTest.php +++ b/tests/Database/DatabaseMariaDbConnectionTest.php @@ -6,21 +6,24 @@ use Hypervel\Database\MariaDbConnection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class DatabaseMariaDbConnectionTest extends TestCase { + use VerifiesDoubles; + public function testWaitingForACommitIdWaitsOnlyForTheMissingDomains(): void { - $connection = m::mock(MariaDbConnection::class)->makePartial(); + $connection = Double::for(MariaDbConnection::class)->passthru(); $connection->expects('selectOne') ->with('select master_gtid_wait(?, 0) as master_gtid_wait, @@gtid_current_pos as gtid_current_pos', ['0-1-5,1-2-9']) - ->andReturn((object) ['master_gtid_wait' => -1, 'gtid_current_pos' => '0-1-5,1-2-7']); + ->returns((object) ['master_gtid_wait' => -1, 'gtid_current_pos' => '0-1-5,1-2-7']); // Domain 0 holds this server's own write, which MASTER_GTID_WAIT never sees. $connection->expects('scalar') ->with('select master_gtid_wait(?, ?)', ['1-2-9', 5]) - ->andReturn(0); + ->returns(0); $this->assertTrue($connection->hasCommitId('0-1-5,1-2-9', 5)); } diff --git a/tests/Redis/Fixtures/FakeRedisClient.php b/tests/Redis/Fixtures/FakeRedisClient.php index c2cca3ee58..a8aff6f662 100644 --- a/tests/Redis/Fixtures/FakeRedisClient.php +++ b/tests/Redis/Fixtures/FakeRedisClient.php @@ -10,11 +10,10 @@ * Fake Redis client for testing SCAN/HSCAN operations with proper reference parameter handling. * * Extends Redis to satisfy type hints (Redis|RedisCluster) while providing - * controlled test behavior. Does NOT connect to any real Redis server. + * controlled test behavior without connecting to a Redis server. * - * Mockery's andReturnUsing doesn't properly propagate modifications to reference - * parameters back to the caller. This stub properly implements the &$iterator - * reference parameter behavior that phpredis's scan()/hScan() uses. + * Generated Double and Mockery callbacks do not propagate scan cursor changes + * back to the caller. Real methods preserve phpredis's reference parameters. * * Usage for SCAN: * ```php @@ -76,7 +75,7 @@ class FakeRedisClient extends Redis /** * Recorded hScan calls for assertions. * - * @var array + * @var array */ private array $hScanCalls = []; @@ -111,6 +110,11 @@ class FakeRedisClient extends Redis */ private array $zRangeResults = []; + /** + * Number of recorded zRange calls. + */ + private int $zRangeCallCount = 0; + /** * Configured hLen results per key. * @@ -118,6 +122,13 @@ class FakeRedisClient extends Redis */ private array $hLenResults = []; + /** + * Recorded hLen keys for assertions. + * + * @var list + */ + private array $hLenCalls = []; + /** * Configured OPT_PREFIX value for getOption(). */ @@ -145,7 +156,7 @@ class FakeRedisClient extends Redis /** * Recorded zScan calls for assertions. * - * @var array + * @var array */ private array $zScanCalls = []; @@ -156,6 +167,13 @@ class FakeRedisClient extends Redis */ private array $zRemCalls = []; + /** + * Recorded del keys for assertions. + * + * @var list> + */ + private array $delCalls = []; + /** * Configured zCard results per key. * @@ -222,8 +240,7 @@ public function __construct( array $zRemRangeByScoreResults = [], array $evalShaResults = [], ) { - // Note: We intentionally do NOT call parent::__construct() to avoid - // any connection attempts. This fake client never connects to Redis. + // Skip native initialization; this fake never connects to Redis. $this->scanResults = $scanResults; $this->execResults = $execResults; $this->hScanResults = $hScanResults; @@ -292,7 +309,7 @@ public function getScanCallCount(): int public function hscan(string $key, int|string|null &$iterator, ?string $pattern = null, int $count = 0): Redis|array|bool { // Record the call for assertions - $this->hScanCalls[] = ['key' => $key, 'pattern' => $pattern, 'count' => $count]; + $this->hScanCalls[] = ['key' => $key, 'iterator' => $iterator, 'pattern' => $pattern, 'count' => $count]; // Initialize call index for this key if not set if (! isset($this->hScanCallIndex[$key])) { @@ -314,7 +331,7 @@ public function hscan(string $key, int|string|null &$iterator, ?string $pattern /** * Get recorded hScan calls for test assertions. * - * @return array + * @return array */ public function getHScanCalls(): array { @@ -398,17 +415,39 @@ public function getEvalShaCalls(): array */ public function zRange(string $key, string|int $start, string|int $end, array|bool|null $options = null): Redis|array|false { + ++$this->zRangeCallCount; + return $this->zRangeResults[$key] ?? []; } + /** + * Get the number of sorted set reads. + */ + public function getZRangeCallCount(): int + { + return $this->zRangeCallCount; + } + /** * Simulate hLen to get hash length. */ public function hLen(string $key): Redis|int|false { + $this->hLenCalls[] = $key; + return $this->hLenResults[$key] ?? 0; } + /** + * Get the keys whose hash lengths were read. + * + * @return list + */ + public function getHLenCalls(): array + { + return $this->hLenCalls; + } + /** * Queue exists in pipeline or execute directly. * @@ -519,6 +558,7 @@ public function zCard(string $key): Redis|int|false public function del(array|string $key, string ...$other_keys): Redis|int|false { $keys = is_array($key) ? $key : array_merge([$key], $other_keys); + $this->delCalls[] = $keys; if ($this->inPipeline) { $this->pipelineQueue[] = ['method' => 'del', 'args' => $keys]; @@ -527,6 +567,16 @@ public function del(array|string $key, string ...$other_keys): Redis|int|false return count($keys); } + /** + * Get recorded deletions. + * + * @return list> + */ + public function getDelCalls(): array + { + return $this->delCalls; + } + /** * Simulate Redis ZSCAN with proper reference parameter handling. * @@ -539,7 +589,7 @@ public function del(array|string $key, string ...$other_keys): Redis|int|false public function zscan(string $key, int|string|null &$iterator, ?string $pattern = null, int $count = 0): Redis|array|false { // Record the call for assertions - $this->zScanCalls[] = ['key' => $key, 'pattern' => $pattern, 'count' => $count]; + $this->zScanCalls[] = ['key' => $key, 'iterator' => $iterator, 'pattern' => $pattern, 'count' => $count]; // Initialize call index for this key if not set if (! isset($this->zScanCallIndex[$key])) { @@ -561,7 +611,7 @@ public function zscan(string $key, int|string|null &$iterator, ?string $pattern /** * Get recorded zScan calls for test assertions. * - * @return array + * @return array */ public function getZScanCalls(): array { @@ -600,9 +650,12 @@ public function resetFakeState(): void $this->scanCalls = []; $this->hScanCallIndex = []; $this->hScanCalls = []; + $this->hLenCalls = []; + $this->zRangeCallCount = 0; $this->zScanCallIndex = []; $this->zScanCalls = []; $this->zRemCalls = []; + $this->delCalls = []; $this->zRemRangeByScoreCalls = []; $this->evalShaCallIndex = 0; $this->evalShaCalls = []; From ca80e9a66ba750b7de7e67ebcdde33341be41e98 Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:42:36 +0000 Subject: [PATCH 3/4] Convert database and Foundation test doubles to Double Replace remaining direct Mockery doubles across database lifecycle tests, DI, Doctor, Encryption, Engine, Filesystem, Fortify and Foundation. Preserve call counts, argument checks, ordering, exception identity and the existing framework APIs that still use Mockery internally. Use real configuration and exception objects where no double is needed. Exercise Flysystem forwarding through real adapters, keep stream reads in call resolvers, and record database trait ordering in its existing fixture. Make the renderer isolation test actually interleave its coroutines, remove redundant framework cleanup, and delete an unused query-builder test base. Complete ViewFinderInterface with getHints(), alongside its existing namespace-registration methods. Remove concrete-finder assumptions from view caching and analyzer discovery, cover namespaced roots in the command test, and document the contract requirements for custom implementations. Tighten tagged-cache flush tests to reject extra native Redis commands and incorrect keys while preserving the two checks needed for racing writers. Validation: each changed test file passed, including the existing analyzer namespace-discovery and cache-invalidation tests. The existing GCS skip is unchanged. Full static analysis, formatting and whitespace checks passed. --- src/docs/porting-from-laravel.md | 2 + .../src/Console/ViewCacheCommand.php | 2 - src/phpstan/src/Support/RuntimeInputs.php | 7 +- src/phpstan/src/Support/ViewFileHelper.php | 6 +- src/view/README.md | 1 + src/view/src/ViewFinderInterface.php | 7 + tests/Cache/Redis/AnyTaggedCacheTest.php | 12 +- .../Redis/Operations/AnyTag/FlushTest.php | 13 +- .../DatabaseMigrationFreshCommandTest.php | 99 ++-- .../DatabaseMigrationStatusCommandTest.php | 27 +- tests/Database/DatabaseMonitorCommandTest.php | 48 +- .../DatabasePostgresConnectionTest.php | 30 +- .../DatabasePostgresSchemaStateTest.php | 54 +- .../DatabaseQueryBuilderBindingTest.php | 9 +- .../DatabaseQueryBuilderEmbeddingTest.php | 11 +- .../Database/DatabaseQueryBuilderJoinTest.php | 9 +- .../DatabaseQueryBuilderPaginationTest.php | 37 +- tests/Database/DatabaseQueryGrammarTest.php | 27 +- tests/Database/DatabaseReadPoolTest.php | 9 +- tests/Database/DatabaseSQLiteBuilderTest.php | 477 +++++++++--------- .../DatabaseSQLiteQueryGrammarTest.php | 7 +- .../DatabaseSQLiteSchemaMetadataTest.php | 81 +-- .../DatabaseSchemaDumpCommandTest.php | 21 +- tests/Database/DatabaseWipeCommandTest.php | 81 ++- .../Eloquent/CustomBuilderForwardingTest.php | 7 +- tests/Database/Eloquent/ModelBootTest.php | 22 +- .../Eloquent/NewBaseQueryBuilderTest.php | 23 +- .../Eloquent/UseEloquentBuilderTest.php | 14 +- .../MigratorCoroutineIsolationTest.php | 21 +- tests/Database/PoolManagerTest.php | 116 +++-- tests/Database/Query/QueryTestCase.php | 72 --- .../SimpleConnectionResolverIsolationTest.php | 16 +- tests/Di/Bootstrap/GenerateProxiesTest.php | 13 +- tests/Di/ServiceProviderDiTest.php | 7 +- .../Diagnostics/CacheStoreIsReachableTest.php | 11 +- .../DatabaseConnectionIsReachableTest.php | 15 +- .../Diagnostics/MigrationsAreUpToDateTest.php | 15 +- .../PublicStorageLinkExistsTest.php | 19 +- .../QueueConnectionIsReachableTest.php | 14 +- .../RecommendedPhpExtensionsAreLoadedTest.php | 9 +- .../SessionDriverIsReachableTest.php | 9 +- .../Feature/Support/InstalledPackagesTest.php | 9 +- tests/Encryption/CryptFacadeTest.php | 20 +- tests/Engine/SocketTest.php | 13 +- tests/Filesystem/AwsS3V3AdapterTest.php | 30 +- .../Filesystem/ClientPooledFilesystemTest.php | 48 +- tests/Filesystem/FileResponseBuilderTest.php | 9 +- tests/Filesystem/FilesystemManagerTest.php | 139 +++-- tests/Filesystem/FilesystemPoolProxyTest.php | 23 +- .../GoogleCloudStorageAdapterTest.php | 167 +++--- tests/Filesystem/LeasedStreamTest.php | 9 +- .../Filesystem/ScopedFilesystemProxyTest.php | 145 +++--- tests/Fortify/Console/InstallCommandTest.php | 9 +- tests/Fortify/FortifyApiTest.php | 7 +- tests/Fortify/FortifyServiceProviderTest.php | 24 +- tests/Fortify/NewPasswordControllerTest.php | 7 +- ...PasswordResetLinkRequestControllerTest.php | 8 +- .../TwoFactorAuthenticationProviderTest.php | 15 +- .../Auth/EmailVerificationRequestTest.php | 45 +- .../Bootstrap/ProviderOrderingTest.php | 15 +- .../Bootstrap/RegisterFacadesTest.php | 19 +- .../Bootstrap/RegisterProvidersTest.php | 28 +- .../Configuration/MiddlewareTest.php | 26 +- tests/Foundation/Console/AboutCommandTest.php | 7 +- .../Console/KernelEventReroutingTest.php | 13 +- .../Console/KernelTerminateTest.php | 16 +- tests/Foundation/Console/KernelTest.php | 54 +- .../Console/VendorPublishCommandTest.php | 13 +- .../Console/ViewCacheCommandTest.php | 32 +- tests/Foundation/DeferredCallbacksTest.php | 27 +- .../Exceptions/Renderer/ExceptionTest.php | 11 +- .../Exceptions/Renderer/FrameTest.php | 3 +- .../Renderer/ListenerContextIsolationTest.php | 14 +- .../Foundation/FoundationApplicationTest.php | 37 +- ...FoundationFileBasedMaintenanceModeTest.php | 38 +- tests/Foundation/FoundationHelpersTest.php | 22 +- tests/Foundation/FoundationViteTest.php | 9 +- tests/Foundation/Http/KernelTest.php | 79 +-- tests/Foundation/Http/WebSocketKernelTest.php | 15 +- .../Listeners/ReloadDotenvAndConfigTest.php | 34 +- tests/Foundation/PendingChainTest.php | 25 +- tests/Foundation/Testing/BootTraitsTest.php | 32 +- .../Concerns/ExternalServiceOptInTest.php | 195 +++---- .../Concerns/InteractsWithContainerTest.php | 10 +- .../InteractsWithParallelDatabaseTest.php | 34 +- .../InteractsWithRedisParallelTest.php | 7 +- .../InteractsWithTestCaseLifecycleTest.php | 27 +- .../DatabaseConnectionResolverTest.php | 29 +- .../DatabaseTransactionsManagerTest.php | 13 +- .../Testing/DatabaseTransactionsTest.php | 37 +- .../Testing/RefreshDatabaseTest.php | 193 +++---- .../WorkerCachedMaintenanceModeTest.php | 109 ++-- 92 files changed, 1776 insertions(+), 1654 deletions(-) delete mode 100644 tests/Database/Query/QueryTestCase.php diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md index dc43428263..1d97d7ddd5 100644 --- a/src/docs/porting-from-laravel.md +++ b/src/docs/porting-from-laravel.md @@ -182,6 +182,8 @@ Some packages also define package-local contracts, such as `Hypervel\Permission\ Custom `Hypervel\Contracts\View\View` implementations must provide `gatherData(): array`, returning the data used to render the view, including any shared values. Extending `Hypervel\View\View` supplies it. +Custom `Hypervel\View\ViewFinderInterface` implementations must provide `prependLocation()`, `getPaths()` and `getHints()`; extending `Hypervel\View\FileViewFinder` supplies them. + ### Missing Equivalents diff --git a/src/foundation/src/Console/ViewCacheCommand.php b/src/foundation/src/Console/ViewCacheCommand.php index 57b1c16d00..9f71583c27 100644 --- a/src/foundation/src/Console/ViewCacheCommand.php +++ b/src/foundation/src/Console/ViewCacheCommand.php @@ -7,7 +7,6 @@ use Hypervel\Console\Command; use Hypervel\Support\Collection; use Hypervel\View\Engines\CompilerEngine; -use Hypervel\View\FileViewFinder; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Finder\Finder; @@ -86,7 +85,6 @@ protected function bladeFilesIn(array $paths): Collection */ protected function paths(): Collection { - /** @var FileViewFinder $finder */ $finder = $this->hypervel->make('view')->getFinder(); $paths = (new Collection($finder->getPaths()))->merge( diff --git a/src/phpstan/src/Support/RuntimeInputs.php b/src/phpstan/src/Support/RuntimeInputs.php index acc51142b9..20b451c231 100644 --- a/src/phpstan/src/Support/RuntimeInputs.php +++ b/src/phpstan/src/Support/RuntimeInputs.php @@ -15,7 +15,6 @@ use Hypervel\Testbench\Bootstrap\LoadConfiguration as TestbenchLoadConfiguration; use Hypervel\Testbench\Bootstrapper; use Hypervel\Testbench\Foundation\Config as TestbenchConfig; -use Hypervel\View\FileViewFinder; use LogicException; use PHPStan\Analyser\DeclarationDependencyTracker; use PHPStan\Analyser\DependencyTracker; @@ -322,10 +321,8 @@ private function createViewsKey(): string $finder = $this->application()->make('view')->getFinder(); $directories = $finder->getPaths(); - if ($finder instanceof FileViewFinder) { - foreach ($finder->getHints() as $paths) { - $directories = [...$directories, ...$paths]; - } + foreach ($finder->getHints() as $paths) { + $directories = [...$directories, ...$paths]; } $listings = []; diff --git a/src/phpstan/src/Support/ViewFileHelper.php b/src/phpstan/src/Support/ViewFileHelper.php index 87e452ae46..eb5edcd5d7 100644 --- a/src/phpstan/src/Support/ViewFileHelper.php +++ b/src/phpstan/src/Support/ViewFileHelper.php @@ -7,7 +7,6 @@ use Generator; use Hypervel\PHPStan\Concerns\HasContainer; use Hypervel\View\Factory as ViewFactory; -use Hypervel\View\FileViewFinder; use Hypervel\View\ViewFinderInterface; use PHPStan\Analyser\DependencyTracker; use PHPStan\Analyser\Scope; @@ -74,10 +73,7 @@ public function __construct( $finder = $this->finder(); $viewDirectories = $finder->getPaths(); - // Hypervel's finder contract has no namespace hints; the standard finder does. - if ($finder instanceof FileViewFinder) { - $hintDirectories = array_merge(...array_values($finder->getHints())); - } + $hintDirectories = array_merge(...array_values($finder->getHints())); } // View names are derived from these directories, so a relative directory is diff --git a/src/view/README.md b/src/view/README.md index de4ab43a37..284cd20cca 100644 --- a/src/view/README.md +++ b/src/view/README.md @@ -6,6 +6,7 @@ Documentation: https://hypervel.org/docs/views ## Differences From Laravel +- `ViewFinderInterface` includes `prependLocation()`, `getPaths()` and `getHints()` so callers can prepend locations and read the registered paths and namespace hints. Extending `FileViewFinder` supplies these methods. - `Blade::component()` accepts the component alias before the class name: `Blade::component('package-alert', Alert::class)`. - A `View` passed as section content is rendered before the content is stored, so later changes to that `View` instance do not affect the section. diff --git a/src/view/src/ViewFinderInterface.php b/src/view/src/ViewFinderInterface.php index ea9d2aba95..80305c4383 100755 --- a/src/view/src/ViewFinderInterface.php +++ b/src/view/src/ViewFinderInterface.php @@ -63,4 +63,11 @@ public function prependLocation(string $location): void; * Get the active view paths. */ public function getPaths(): array; + + /** + * Get the namespace to file path hints. + * + * Hypervel pairs namespace registration with discovery on the contract. + */ + public function getHints(): array; } diff --git a/tests/Cache/Redis/AnyTaggedCacheTest.php b/tests/Cache/Redis/AnyTaggedCacheTest.php index 66da2b81a6..7f6bcfc3fd 100644 --- a/tests/Cache/Redis/AnyTaggedCacheTest.php +++ b/tests/Cache/Redis/AnyTaggedCacheTest.php @@ -488,9 +488,11 @@ public function testFlushDeletesAllTaggedItems(): void // GetTaggedKeys uses hlen to check size // When small (< threshold), it uses hkeys directly instead of scan - $connection->client()->allows('hlen') + $connection->client()->expects('hlen') + ->with('prefix:_any:tag:users:entries') ->returns(2); $connection->client()->expects('hkeys') + ->with('prefix:_any:tag:users:entries') ->returns(['key1', 'key2']); $connection->expects('evalWithShaCache') @@ -510,9 +512,11 @@ public function testClearFlushesTaggedItems(): void { $connection = $this->mockConnection(); - $connection->client()->allows('hlen') + $connection->client()->expects('hlen') + ->with('prefix:_any:tag:users:entries') ->returns(2); $connection->client()->expects('hkeys') + ->with('prefix:_any:tag:users:entries') ->returns(['key1', 'key2']); $connection->expects('evalWithShaCache') ->with(Argument::type('string'), ['prefix:_any:tag:users:entries', 'prefix:key1:_any:tags', 'prefix:key2:_any:tags', 'prefix:key1', 'prefix:key2'], [2, 'key1', 'key2']) @@ -1269,11 +1273,13 @@ public function testItemsReturnsGenerator(): void $connection = $this->mockConnection(); // GetTaggedKeys uses hlen to check size first - $connection->client()->allows('hlen') + $connection->client()->expects('hlen') + ->with('prefix:_any:tag:users:entries') ->returns(2); // When small (< threshold), it uses hkeys directly $connection->client()->expects('hkeys') + ->with('prefix:_any:tag:users:entries') ->returns(['key1', 'key2']); // Get values for found keys (mget receives array) diff --git a/tests/Cache/Redis/Operations/AnyTag/FlushTest.php b/tests/Cache/Redis/Operations/AnyTag/FlushTest.php index a33d34a43d..869a415c6f 100644 --- a/tests/Cache/Redis/Operations/AnyTag/FlushTest.php +++ b/tests/Cache/Redis/Operations/AnyTag/FlushTest.php @@ -217,9 +217,12 @@ public function testFlushClusterModeWithMultipleTags(): void $client->expects('hdel')->with('prefix:_any:tag:posts:entries', 'shared_key', 'post_key')->returns(2); $client->expects('hlen')->with('prefix:_any:tag:users:entries')->times(2)->returns(0); $client->expects('hlen')->with('prefix:_any:tag:posts:entries')->times(2)->returns(0); - $client->allows('del')->returns(1); - $client->allows('unlink')->returns(1); - $client->allows('zrem')->returns(1); + $client->expects('del')->with('prefix:user_key:_any:tags', 'prefix:shared_key:_any:tags')->returns(2); + $client->expects('del')->with('prefix:shared_key:_any:tags', 'prefix:post_key:_any:tags')->returns(1); + $client->expects('unlink')->with('prefix:user_key', 'prefix:shared_key')->returns(2); + $client->expects('unlink')->with('prefix:shared_key', 'prefix:post_key')->returns(1); + $client->expects('zrem')->with('prefix:_any:tag:registry', 'users')->returns(1); + $client->expects('zrem')->with('prefix:_any:tag:registry', 'posts')->returns(1); $operation = new Flush($store->getContext(), $getTaggedKeys, new RemoveEmptyTags($store->getContext())); $result = $operation->execute(['users', 'posts']); @@ -231,10 +234,10 @@ public function testFlushViaRedisStoreMethod(): void $connection = $this->mockConnection(); // Mock hlen/hkeys for GetTaggedKeys internal calls - $connection->client()->allows('hlen') + $connection->client()->expects('hlen') ->with('prefix:_any:tag:users:entries') ->returns(1); - $connection->client()->allows('hkeys') + $connection->client()->expects('hkeys') ->with('prefix:_any:tag:users:entries') ->returns(['mykey']); diff --git a/tests/Database/DatabaseMigrationFreshCommandTest.php b/tests/Database/DatabaseMigrationFreshCommandTest.php index 0e447fc887..115284813d 100644 --- a/tests/Database/DatabaseMigrationFreshCommandTest.php +++ b/tests/Database/DatabaseMigrationFreshCommandTest.php @@ -11,7 +11,9 @@ use Hypervel\Database\SQLiteDatabaseDoesNotExistException; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; @@ -22,14 +24,15 @@ class DatabaseMigrationFreshCommandTest extends TestCase { + use VerifiesDoubles; + public function testFreshWipesEveryPreExistingTargetThenMigratesDispatchesAndSeeds(): void { $app = $this->makeApplication(); - $dispatcher = $app->instance(Dispatcher::class, m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->byDefault()->andReturn(false); + $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); $this->expectPreExistingMigrationTargets($migrator, ['sqlite', 'analytics'], registeredPaths: ['/registered']); @@ -73,8 +76,9 @@ function (string $name, array $arguments) use (&$operations): int { return 0; } ); - $dispatcher->shouldReceive('hasListeners')->once()->with(DatabaseRefreshed::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->with(m::type(DatabaseRefreshed::class))->andReturnUsing( + $dispatcher->allows('hasListeners')->with(Argument::not(DatabaseRefreshed::class))->returns(false); + $dispatcher->expects('hasListeners')->with(DatabaseRefreshed::class)->returns(true); + $dispatcher->expects('dispatch')->with(Argument::type(DatabaseRefreshed::class))->resolves( function (DatabaseRefreshed $event) use (&$operations): void { $this->assertSame('sqlite', $event->database); $this->assertTrue($event->seeding); @@ -99,7 +103,7 @@ public function testReachableDatabaseWithoutMigrationRepositoryIsStillWiped(): v $app = $this->makeApplication(); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); $this->expectPreExistingMigrationTargets($migrator, ['sqlite'], repositoryExists: false); @@ -122,16 +126,16 @@ public function testMissingTargetIsCreatedAndVerifiedButNeverWiped(): void $app = $this->makeApplication(); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); $paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations']; $currentConnection = null; $analyticsInspections = 0; - $migrator->shouldReceive('paths')->once()->andReturn([]); - $migrator->shouldReceive('getMigrationConnections')->once()->with($paths, 'sqlite')->andReturn(['sqlite', 'analytics']); - $migrator->shouldReceive('usingConnection')->times(3)->andReturnUsing( + $migrator->expects('paths')->returns([]); + $migrator->expects('getMigrationConnections')->with($paths, 'sqlite')->returns(['sqlite', 'analytics']); + $migrator->expects('usingConnection')->times(3)->resolves( function ($name, $callback) use (&$currentConnection) { $currentConnection = $name; @@ -142,7 +146,7 @@ function ($name, $callback) use (&$currentConnection) { } } ); - $migrator->shouldReceive('repositoryExists')->times(3)->andReturnUsing( + $migrator->expects('repositoryExists')->times(3)->resolves( function () use (&$currentConnection, &$analyticsInspections, $path): bool { if ($currentConnection === 'analytics') { ++$analyticsInspections; @@ -192,17 +196,17 @@ public function testDecliningProductionConfirmationCreatesAndWipesNothing(): voi $app = $this->makeApplication('production'); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); $paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations']; $inspection = 0; - $migrator->shouldReceive('paths')->once()->andReturn([]); - $migrator->shouldReceive('getMigrationConnections')->once()->with($paths, 'sqlite')->andReturn(['sqlite', 'analytics']); - $migrator->shouldReceive('usingConnection')->twice()->andReturnUsing(function ($name, $callback) { + $migrator->expects('paths')->returns([]); + $migrator->expects('getMigrationConnections')->with($paths, 'sqlite')->returns(['sqlite', 'analytics']); + $migrator->expects('usingConnection')->times(2)->resolves(function ($name, $callback) { return $callback(); }); - $migrator->shouldReceive('repositoryExists')->twice()->andReturnUsing( + $migrator->expects('repositoryExists')->times(2)->resolves( function () use (&$inspection, $path): bool { if (++$inspection === 2) { throw new SQLiteDatabaseDoesNotExistException($path); @@ -228,18 +232,18 @@ public function testCreationFailurePreventsEveryWipeAndMigration(): void $app = $this->makeApplication(); $command = $this->getMockBuilder(TestableFreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->creationFailure = $failure = new RuntimeException('create failed'); $command->setHypervel($app); $paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations']; $inspection = 0; - $migrator->shouldReceive('paths')->once()->andReturn([]); - $migrator->shouldReceive('getMigrationConnections')->once()->with($paths, 'sqlite')->andReturn(['sqlite', 'analytics']); - $migrator->shouldReceive('usingConnection')->twice()->andReturnUsing(function ($name, $callback) { + $migrator->expects('paths')->returns([]); + $migrator->expects('getMigrationConnections')->with($paths, 'sqlite')->returns(['sqlite', 'analytics']); + $migrator->expects('usingConnection')->times(2)->resolves(function ($name, $callback) { return $callback(); }); - $migrator->shouldReceive('repositoryExists')->twice()->andReturnUsing( + $migrator->expects('repositoryExists')->times(2)->resolves( function () use (&$inspection, $path): bool { if (++$inspection === 2) { throw new SQLiteDatabaseDoesNotExistException($path); @@ -266,7 +270,7 @@ public function testWipeFailureAbortsBeforeMigration(): void $app = $this->makeApplication(); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); $this->expectPreExistingMigrationTargets($migrator, ['analytics']); @@ -286,11 +290,10 @@ public function testWipeFailureAbortsBeforeMigration(): void public function testMigrationFailureAbortsBeforeEventAndSeeding(): void { $app = $this->makeApplication(); - $dispatcher = $app->instance(Dispatcher::class, m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->byDefault()->andReturn(false); + $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); $this->expectPreExistingMigrationTargets($migrator, ['sqlite']); @@ -299,7 +302,7 @@ public function testMigrationFailureAbortsBeforeEventAndSeeding(): void '--database' => 'sqlite', '--force' => true, ])->willReturn(1); - $dispatcher->shouldReceive('dispatch')->never(); + $dispatcher->expects('dispatch')->never(); $caught = null; try { @@ -314,11 +317,10 @@ public function testMigrationFailureAbortsBeforeEventAndSeeding(): void public function testSeedFailureOccursAfterDatabaseRefreshedEventAndFailsTheCommand(): void { $app = $this->makeApplication(); - $dispatcher = $app->instance(Dispatcher::class, m::mock(Dispatcher::class)); - $dispatcher->shouldReceive('hasListeners')->byDefault()->andReturn(false); + $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); $this->expectPreExistingMigrationTargets($migrator, ['sqlite']); @@ -331,8 +333,9 @@ function (string $name) use (&$operations): int { return $name === 'migrate' ? 0 : 1; } ); - $dispatcher->shouldReceive('hasListeners')->once()->with(DatabaseRefreshed::class)->andReturnTrue(); - $dispatcher->shouldReceive('dispatch')->once()->andReturnUsing(function () use (&$operations): void { + $dispatcher->allows('hasListeners')->with(Argument::not(DatabaseRefreshed::class))->returns(false); + $dispatcher->expects('hasListeners')->with(DatabaseRefreshed::class)->returns(true); + $dispatcher->expects('dispatch')->resolves(function () use (&$operations): void { $operations[] = 'event'; }); $caught = null; @@ -352,17 +355,17 @@ public function testUnclassifiedInspectionFailurePropagatesBeforeMutation(): voi $app = $this->makeApplication(); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); $paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations']; $failure = new RuntimeException('Authentication failed.'); - $migrator->shouldReceive('paths')->once()->andReturn([]); - $migrator->shouldReceive('getMigrationConnections')->once()->with($paths, 'sqlite')->andReturn(['sqlite']); - $migrator->shouldReceive('usingConnection')->once()->andReturnUsing(function ($name, $callback) { + $migrator->expects('paths')->returns([]); + $migrator->expects('getMigrationConnections')->with($paths, 'sqlite')->returns(['sqlite']); + $migrator->expects('usingConnection')->resolves(function ($name, $callback) { return $callback(); }); - $migrator->shouldReceive('repositoryExists')->once()->andThrow($failure); + $migrator->expects('repositoryExists')->throws($failure); $command->expects($this->never())->method('callSilent'); $command->expects($this->never())->method('call'); $caught = null; @@ -385,15 +388,15 @@ public function testFreshUsesTheSamePathOptionsForDiscoveryAndNestedMigrate( $app = $this->makeApplication(); $command = $this->getMockBuilder(FreshCommand::class) ->onlyMethods(['call', 'callSilent']) - ->setConstructorArgs([$migrator = m::mock(Migrator::class)]) + ->setConstructorArgs([$migrator = Double::for(Migrator::class)]) ->getMock(); $command->setHypervel($app); - $migrator->shouldReceive('paths')->never(); - $migrator->shouldReceive('getMigrationConnections')->once()->with($discoveryPaths, 'sqlite')->andReturn(['sqlite']); - $migrator->shouldReceive('usingConnection')->once()->andReturnUsing(function ($name, $callback) { + $migrator->expects('paths')->never(); + $migrator->expects('getMigrationConnections')->with($discoveryPaths, 'sqlite')->returns(['sqlite']); + $migrator->expects('usingConnection')->resolves(function ($name, $callback) { return $callback(); }); - $migrator->shouldReceive('repositoryExists')->once()->andReturn(true); + $migrator->expects('repositoryExists')->returns(true); $command->expects($this->once())->method('callSilent')->willReturn(0); $command->expects($this->once())->method('call')->with('migrate', $migrateArguments)->willReturn(0); @@ -428,9 +431,9 @@ public static function migrationPathProvider(): array public function testProhibitedFreshReturnsBeforeDiscovery(): void { $app = $this->makeApplication(); - $command = new FreshCommand($migrator = m::mock(Migrator::class)); + $command = new FreshCommand($migrator = Double::for(Migrator::class)); $command->setHypervel($app); - $migrator->shouldNotReceive('getMigrationConnections'); + $migrator->expects('getMigrationConnections')->never(); FreshCommand::prohibit(); $this->assertSame(1, $this->runCommand($command, ['--database' => 'sqlite'])); @@ -445,12 +448,12 @@ private function expectPreExistingMigrationTargets( ): void { $paths = [...$registeredPaths, __DIR__ . DIRECTORY_SEPARATOR . 'migrations']; - $migrator->shouldReceive('paths')->once()->andReturn($registeredPaths); - $migrator->shouldReceive('getMigrationConnections')->once()->with($paths, $database)->andReturn($connections); - $migrator->shouldReceive('usingConnection')->times(count($connections))->andReturnUsing(function ($name, $callback) { + $migrator->expects('paths')->returns($registeredPaths); + $migrator->expects('getMigrationConnections')->with($paths, $database)->returns($connections); + $migrator->expects('usingConnection')->times(count($connections))->resolves(function ($name, $callback) { return $callback(); }); - $migrator->shouldReceive('repositoryExists')->times(count($connections))->andReturn($repositoryExists); + $migrator->expects('repositoryExists')->times(count($connections))->returns($repositoryExists); } private function makeApplication(string $environment = 'development'): ApplicationDatabaseFreshStub diff --git a/tests/Database/DatabaseMigrationStatusCommandTest.php b/tests/Database/DatabaseMigrationStatusCommandTest.php index 966774d76a..87d877a66a 100644 --- a/tests/Database/DatabaseMigrationStatusCommandTest.php +++ b/tests/Database/DatabaseMigrationStatusCommandTest.php @@ -9,32 +9,35 @@ use Hypervel\Database\Migrations\Migrator; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class DatabaseMigrationStatusCommandTest extends TestCase { + use VerifiesDoubles; + public function testPendingOptionReturnsConfiguredExitCodeAsInteger(): void { $app = new ApplicationDatabaseStatusStub(['path.database' => __DIR__]); $app->useDatabasePath(__DIR__); - $command = new StatusCommand($migrator = m::mock(Migrator::class)); + $command = new StatusCommand($migrator = Double::for(Migrator::class)); $command->setHypervel($app); - $repository = m::mock(MigrationRepositoryInterface::class); - $migrator->shouldReceive('usingConnection')->once()->andReturnUsing(function ($name, $callback) { + $repository = Double::for(MigrationRepositoryInterface::class); + $migrator->expects('usingConnection')->resolves(function ($name, $callback) { return $callback(); }); - $migrator->shouldReceive('repositoryExists')->once()->andReturn(true); - $migrator->shouldReceive('getRepository')->twice()->andReturn($repository); - $repository->shouldReceive('getRan')->once()->andReturn([]); - $repository->shouldReceive('getMigrationBatches')->once()->andReturn([]); - $migrator->shouldReceive('paths')->once()->andReturn([]); - $migrator->shouldReceive('getMigrationFiles')->once()->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'])->andReturn([ + $migrator->expects('repositoryExists')->returns(true); + $migrator->expects('getRepository')->times(2)->returns($repository); + $repository->expects('getRan')->returns([]); + $repository->expects('getMigrationBatches')->returns([]); + $migrator->expects('paths')->returns([]); + $migrator->expects('getMigrationFiles')->with([__DIR__ . DIRECTORY_SEPARATOR . 'migrations'])->returns([ '/tmp/2024_01_01_000000_create_users_table.php', ]); - $migrator->shouldReceive('getMigrationName')->once()->with('/tmp/2024_01_01_000000_create_users_table.php')->andReturn('2024_01_01_000000_create_users_table'); - $migrator->shouldReceive('shouldSkip')->once()->with('/tmp/2024_01_01_000000_create_users_table.php')->andReturn(false); + $migrator->expects('getMigrationName')->with('/tmp/2024_01_01_000000_create_users_table.php')->returns('2024_01_01_000000_create_users_table'); + $migrator->expects('shouldSkip')->with('/tmp/2024_01_01_000000_create_users_table.php')->returns(false); $code = $this->runCommand($command, ['--pending' => '5']); diff --git a/tests/Database/DatabaseMonitorCommandTest.php b/tests/Database/DatabaseMonitorCommandTest.php index 31ba0176c1..77fac89a7c 100644 --- a/tests/Database/DatabaseMonitorCommandTest.php +++ b/tests/Database/DatabaseMonitorCommandTest.php @@ -12,19 +12,23 @@ use Hypervel\Database\Events\DatabaseBusy; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class DatabaseMonitorCommandTest extends TestCase { + use VerifiesDoubles; + public function testMonitorCommandFailsWhenDatabaseDefaultIsMissing(): void { $this->app->instance('config', new Repository(['database' => []])); - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); - $command = new MonitorCommand($resolver, m::mock(Dispatcher::class)); + $command = new MonitorCommand($resolver, Double::for(Dispatcher::class)); $command->setHypervel($this->app); $this->expectException(InvalidArgumentException::class); @@ -35,13 +39,13 @@ public function testMonitorCommandFailsWhenDatabaseDefaultIsMissing(): void public function testMonitorCommandPreservesConnectionNameZero(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('threadCount')->once()->andReturn(1); + $connection = Double::for(Connection::class); + $connection->expects('threadCount')->returns(1); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->once()->with('0')->andReturn($connection); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with('0')->returns($connection); - $command = new MonitorCommand($resolver, m::mock(Dispatcher::class)); + $command = new MonitorCommand($resolver, Double::for(Dispatcher::class)); $command->setHypervel($this->app); $this->assertSame(0, $command->run(new ArrayInput(['--databases' => '0']), new NullOutput)); @@ -49,13 +53,13 @@ public function testMonitorCommandPreservesConnectionNameZero(): void public function testBusyEventIsNotDispatchedWithoutListeners(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('threadCount')->once()->andReturn(2); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->once()->with('primary')->andReturn($connection); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(DatabaseBusy::class)->andReturnFalse(); - $events->shouldReceive('dispatch')->never(); + $connection = Double::for(Connection::class); + $connection->expects('threadCount')->returns(2); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with('primary')->returns($connection); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(DatabaseBusy::class)->returns(false); + $events->expects('dispatch')->never(); $command = new MonitorCommand($resolver, $events); $command->setHypervel($this->app); @@ -67,13 +71,13 @@ public function testBusyEventIsNotDispatchedWithoutListeners(): void public function testBusyEventIsDispatchedWithAListener(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('threadCount')->once()->andReturn(2); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->shouldReceive('connection')->once()->with('primary')->andReturn($connection); - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(DatabaseBusy::class)->andReturnTrue(); - $events->shouldReceive('dispatch')->once()->with(m::on( + $connection = Double::for(Connection::class); + $connection->expects('threadCount')->returns(2); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with('primary')->returns($connection); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(DatabaseBusy::class)->returns(true); + $events->expects('dispatch')->with(Argument::satisfies( static fn (DatabaseBusy $event): bool => $event->connectionName === 'primary' && $event->connections === 2 )); diff --git a/tests/Database/DatabasePostgresConnectionTest.php b/tests/Database/DatabasePostgresConnectionTest.php index 5f82ebd6f0..26948b8b56 100644 --- a/tests/Database/DatabasePostgresConnectionTest.php +++ b/tests/Database/DatabasePostgresConnectionTest.php @@ -7,8 +7,8 @@ use DateTimeImmutable; use Hypervel\Database\PostgresConnection; use Hypervel\Tests\TestCase; -use Mockery as m; -use Mockery\MockInterface; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PDOStatement; use PHPUnit\Framework\Attributes\DataProvider; @@ -16,6 +16,8 @@ class DatabasePostgresConnectionTest extends TestCase { + use VerifiesDoubles; + public function testBooleanBindingsAreStringifiedWhenUsingEmulatedPrepares(): void { $connection = $this->newConnection(emulatePrepares: true); @@ -99,12 +101,12 @@ public function testWaitingForACommitIdUsesOnlyTheReadConnection(string $status, $readPdo = $this->commitIdReadPdo('19.0'); $readPdo->expects('prepare') ->with("wait for lsn '0/16B3748' with (timeout '5s', no_throw)") - ->andReturn($this->commitIdStatement($status)); + ->returns($this->commitIdStatement($status)); if ($immediateResult !== null) { $readPdo->expects('prepare') ->with('select case when pg_is_in_recovery() then pg_last_wal_replay_lsn() else pg_current_wal_insert_lsn() end >= ?::pg_lsn') - ->andReturn($this->commitIdStatement($immediateResult)); + ->returns($this->commitIdStatement($immediateResult)); } $this->assertSame($expected, $this->newCommitIdConnection($readPdo)->hasCommitId('0/16B3748', 5)); @@ -127,7 +129,7 @@ public static function commitIdWaitStatuses(): array public function testWaitingForACommitIdRequiresPostgres19OnTheReadConnection(): void { $readPdo = $this->commitIdReadPdo('18.4'); - $readPdo->shouldNotReceive('prepare'); + $readPdo->expects('prepare')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessage('PostgreSQL 19 or newer is required.'); @@ -138,11 +140,11 @@ public function testWaitingForACommitIdRequiresPostgres19OnTheReadConnection(): /** * Create a read PDO reporting the given server version. */ - protected function commitIdReadPdo(string $version): PDO&MockInterface + protected function commitIdReadPdo(string $version): PDO { - $pdo = m::mock(PDO::class); - $pdo->shouldReceive('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->andReturn($version); - $pdo->shouldReceive('quote')->andReturnUsing(fn (string $value): string => "'{$value}'"); + $pdo = Double::for(PDO::class); + $pdo->allows('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns($version); + $pdo->allows('quote')->resolves(fn (string $value): string => "'{$value}'"); return $pdo; } @@ -152,11 +154,11 @@ protected function commitIdReadPdo(string $version): PDO&MockInterface */ protected function commitIdStatement(bool|string $value): PDOStatement { - $statement = m::mock(PDOStatement::class); - $statement->shouldReceive('setFetchMode')->andReturnTrue(); - $statement->shouldReceive('bindValue')->andReturnTrue(); - $statement->expects('execute')->andReturnTrue(); - $statement->expects('fetchAll')->andReturn([(object) ['result' => $value]]); + $statement = Double::for(PDOStatement::class); + $statement->allows('setFetchMode')->returns(true); + $statement->allows('bindValue')->returns(true); + $statement->expects('execute')->returns(true); + $statement->expects('fetchAll')->returns([(object) ['result' => $value]]); return $statement; } diff --git a/tests/Database/DatabasePostgresSchemaStateTest.php b/tests/Database/DatabasePostgresSchemaStateTest.php index 8352522794..f033f58be9 100644 --- a/tests/Database/DatabasePostgresSchemaStateTest.php +++ b/tests/Database/DatabasePostgresSchemaStateTest.php @@ -9,7 +9,9 @@ use Hypervel\Database\Schema\PostgresBuilder; use Hypervel\Database\Schema\PostgresSchemaState; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionMethod; use RuntimeException; use Symfony\Component\Process\Process; @@ -17,6 +19,8 @@ class DatabasePostgresSchemaStateTest extends TestCase { + use VerifiesDoubles; + public function testDumpOutputFailureStopsTheProcess(): void { $process = new Process([PHP_BINARY, '-r', 'echo "progress"; usleep(5000000);']); @@ -45,7 +49,7 @@ public function testDumpOutputFailureStopsTheProcess(): void public function testBaseVariablesUseConfiguredConnectionByDefault(): void { - $schemaState = new PostgresSchemaState(m::mock(PostgresConnection::class)); + $schemaState = new PostgresSchemaState(Double::for(PostgresConnection::class)); $variables = (new ReflectionMethod(PostgresSchemaState::class, 'baseVariables'))->invoke($schemaState, [ 'host' => 'pooler-host', @@ -70,7 +74,7 @@ public function testBaseVariablesUseConfiguredConnectionByDefault(): void public function testBaseVariablesDoNotExportEmptySslMode(): void { - $connection = m::mock(PostgresConnection::class); + $connection = Double::for(PostgresConnection::class); $schemaState = new PostgresSchemaState($connection); $method = new ReflectionMethod($schemaState, 'baseVariables'); @@ -101,22 +105,22 @@ public function testDumpPassesSchemaPathToProcessEnvironment(): void 'database' => 'hypervel', ]; - $schema = m::mock(PostgresBuilder::class); - $schema->shouldReceive('hasTable')->once()->with('migrations')->andReturnFalse(); + $schema = Double::for(PostgresBuilder::class); + $schema->expects('hasTable')->with('migrations')->returns(false); - $connection = m::mock(PostgresConnection::class); - $connection->shouldReceive('getConfig')->andReturn($config); - $connection->shouldReceive('getSchemaBuilder')->once()->andReturn($schema); + $connection = Double::for(PostgresConnection::class); + $connection->allows('getConfig')->returns($config); + $connection->expects('getSchemaBuilder')->returns($schema); - $process = m::mock(Process::class); - $process->shouldReceive('mustRun')->once()->with(m::type('callable'), [ + $process = Double::for(Process::class); + $process->expects('mustRun')->with(Argument::type('callable'), [ 'HYPERVEL_LOAD_HOST' => '127.0.0.1', 'HYPERVEL_LOAD_PORT' => '5432', 'HYPERVEL_LOAD_USER' => 'forge', 'PGPASSWORD' => 'secret', 'HYPERVEL_LOAD_DATABASE' => 'hypervel', 'HYPERVEL_LOAD_PATH' => $path, - ])->andReturnSelf(); + ]); $factoryCalledWith = null; $schemaState = new PostgresSchemaState( @@ -138,13 +142,13 @@ public function testDumpPassesSchemaPathToProcessEnvironment(): void public function testMigrationDataUsesLiteralPathAndTableArguments(): void { - $schema = m::mock(PostgresBuilder::class); - $schema->shouldReceive('hasTable')->once()->with('archive.Migration"History')->andReturnTrue(); - $schema->shouldReceive('parseSchemaAndTable')->once()->with('archive.Migration"History', true)->andReturn(['archive', 'Migration"History']); - $connection = m::mock(PostgresConnection::class); - $connection->shouldReceive('getSchemaBuilder')->twice()->andReturn($schema); - $connection->shouldReceive('getTablePrefix')->once()->andReturn('pre.'); - $connection->shouldReceive('getConfig')->andReturn([ + $schema = Double::for(PostgresBuilder::class); + $schema->expects('hasTable')->with('archive.Migration"History')->returns(true); + $schema->expects('parseSchemaAndTable')->with('archive.Migration"History', true)->returns(['archive', 'Migration"History']); + $connection = Double::for(PostgresConnection::class); + $connection->expects('getSchemaBuilder')->times(2)->returns($schema); + $connection->expects('getTablePrefix')->returns('pre.'); + $connection->allows('getConfig')->returns([ 'host' => 'localhost', 'username' => 'user', 'password' => '', 'database' => 'app', ]); @@ -175,16 +179,16 @@ static function (?callable $output, array $variables) use (&$calls, $command, $p public function testMigrationTableUsesTheActualSchemaUnlessExplicitlyQualified(): void { - $connection = m::mock(PostgresConnection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(m::mock(PostgresGrammar::class)); - $connection->shouldReceive('scalar') - ->twice() + $connection = Double::for(PostgresConnection::class); + $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)); + $connection->expects('scalar') + ->times(2) ->with('select current_schema()', [], false) - ->andReturn('public', 'Schema.With.Dot'); - $connection->shouldReceive('getTablePrefix')->times(3)->andReturn('', '', 'prefix.with.dot_'); + ->returns('public', 'Schema.With.Dot'); + $connection->expects('getTablePrefix')->times(3)->returns('', '', 'prefix.with.dot_'); $builder = new PostgresBuilder($connection); - $connection->shouldReceive('getSchemaBuilder')->times(3)->andReturn($builder); + $connection->expects('getSchemaBuilder')->times(3)->returns($builder); $schemaState = new PostgresSchemaState($connection); $method = new ReflectionMethod($schemaState, 'getMigrationTable'); diff --git a/tests/Database/DatabaseQueryBuilderBindingTest.php b/tests/Database/DatabaseQueryBuilderBindingTest.php index 464cdb3465..21fb51f262 100644 --- a/tests/Database/DatabaseQueryBuilderBindingTest.php +++ b/tests/Database/DatabaseQueryBuilderBindingTest.php @@ -13,13 +13,16 @@ use Hypervel\Database\SQLiteConnection; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use stdClass; class DatabaseQueryBuilderBindingTest extends TestCase { + use VerifiesDoubles; + public function testHavingAcceptsBooleanOperandsInBothOverloadsAndNestedClauses(): void { $query = $this->builder()->from('users') @@ -179,8 +182,8 @@ public static function betweenMethods(): iterable */ protected function builder(): Builder { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); return new Builder($connection, new Grammar($connection), new Processor); } diff --git a/tests/Database/DatabaseQueryBuilderEmbeddingTest.php b/tests/Database/DatabaseQueryBuilderEmbeddingTest.php index f7d4ad83b4..ffc1b44bd6 100644 --- a/tests/Database/DatabaseQueryBuilderEmbeddingTest.php +++ b/tests/Database/DatabaseQueryBuilderEmbeddingTest.php @@ -11,11 +11,14 @@ use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseQueryBuilderEmbeddingTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('attachmentPaths')] public function testEmbeddingValidationCanRejectBeforeChangingTheOuterQuery(Closure $attach): void { @@ -95,9 +98,9 @@ public static function attachmentPaths(): iterable */ protected function builder(): EmbeddingAwareQueryBuilder { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); + $connection->allows('getDatabaseName')->returns('database'); return new EmbeddingAwareQueryBuilder($connection, new Grammar($connection), new Processor); } diff --git a/tests/Database/DatabaseQueryBuilderJoinTest.php b/tests/Database/DatabaseQueryBuilderJoinTest.php index 6bdb223acb..a35498f488 100644 --- a/tests/Database/DatabaseQueryBuilderJoinTest.php +++ b/tests/Database/DatabaseQueryBuilderJoinTest.php @@ -12,11 +12,14 @@ use Hypervel\Database\Query\JoinClause; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseQueryBuilderJoinTest extends TestCase { + use VerifiesDoubles; + public function testNestedJoinSupportsGroupedOnConditions(): void { $query = $this->builder()->from('users') @@ -131,8 +134,8 @@ public static function joinWhereOperands(): iterable */ protected function builder(): Builder { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); return new Builder($connection, new Grammar($connection), new Processor); } diff --git a/tests/Database/DatabaseQueryBuilderPaginationTest.php b/tests/Database/DatabaseQueryBuilderPaginationTest.php index 007026c411..805c1cb8e4 100644 --- a/tests/Database/DatabaseQueryBuilderPaginationTest.php +++ b/tests/Database/DatabaseQueryBuilderPaginationTest.php @@ -18,7 +18,8 @@ use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; @@ -26,6 +27,8 @@ class DatabaseQueryBuilderPaginationTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('keysetIterators')] public function testKeysetIterationVisitsEveryUnionRowOnce(string $method, bool $lazy, bool $descending): void { @@ -342,7 +345,9 @@ public function testDirectKeysetPagesPreserveScopesLimitsAndCurrentBindings(): v $model = new class extends Model { protected ?string $table = 'posts'; }; - $model::setConnectionResolver(m::mock(ConnectionResolverInterface::class, ['connection' => $connection])); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->returns($connection); + $model::setConnectionResolver($resolver); $query = (new EloquentBuilder($connection->query()))->setModel($model) ->withGlobalScope('visible', static fn (EloquentBuilder $query): EloquentBuilder => $query->where('posts.id', '<', 3)) ->select('id')->orderByDesc('id')->limit(2) @@ -625,18 +630,18 @@ public function testAggregatePreparesCallbacksBeforeSelectingItsBindings(bool $g public function testGroupedCountTransfersCallbackTimeoutAndRoutingToTheOuterStatement(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); $query = new Builder($connection, new MySqlGrammar($connection), new Processor); $query->from('events')->groupBy('tenant_id')->beforeQuery(function (Builder $query): void { $query->timeout(5)->useWritePdo(); }); - $connection->shouldReceive('select')->once()->with( + $connection->expects('select')->with( 'select /*+ MAX_EXECUTION_TIME(5000) */ count(*) as `aggregate` from (select * from `events` group by `tenant_id`) as `aggregate_table`', [], false, [], - )->andReturn([['aggregate' => 2]]); + )->returns([['aggregate' => 2]]); $this->assertSame(2, $query->getCountForPagination()); $this->assertNull($query->timeout); @@ -646,8 +651,8 @@ public function testGroupedCountTransfersCallbackTimeoutAndRoutingToTheOuterStat public function testCallbackFailurePreservesIdentityAndRestoresTheOriginalFetchMode(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn(''); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns(''); $query = new Builder($connection, new Grammar($connection), new Processor); $exception = new RuntimeException('Cannot prepare the query.'); $query->from('events')->select('tenant_id')->fetchUsing(PDO::FETCH_COLUMN) @@ -665,21 +670,21 @@ public function testCallbackFailurePreservesIdentityAndRestoresTheOriginalFetchM $this->assertCount(1, $query->beforeQueryCallbacks); $this->assertSame([PDO::FETCH_COLUMN], $query->fetchUsing); $query->beforeQueryCallbacks = []; - $connection->shouldReceive('select')->once()->with( + $connection->expects('select')->with( 'select "tenant_id" from "events"', [], true, [PDO::FETCH_COLUMN], - )->andReturn([1, 2]); + )->returns([1, 2]); $this->assertSame([1, 2], $query->get()->all()); } #[DataProvider('tablePrefixes')] public function testRetainedInnerBindingsBelongToTheDerivedTable(string $prefix): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn($prefix); - $processor = m::mock(Processor::class); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns($prefix); + $processor = Double::for(Processor::class); $query = new PaginationWithOrderingBuilder($connection, new Grammar($connection), $processor); $query->from('events')->selectRaw('tenant_id + ? as bucket', [11]) ->where('tenant_id', '>', 12)->groupBy('tenant_id') @@ -691,13 +696,13 @@ public function testRetainedInnerBindingsBelongToTheDerivedTable(string $prefix) $originalBindings = $query->getRawBindings(); $originalOrders = $query->orders; - $connection->shouldReceive('select')->once()->with( + $connection->expects('select')->with( 'select count(*) as "aggregate" from (select tenant_id + ? as bucket from "' . $prefix . 'events" where "tenant_id" > ? and "active" = ? group by "tenant_id" having count(*) > ? order by tenant_id + ?) as "aggregate_table"', [11, 12, 15, 13, 14], false, [], - )->andReturn([['aggregate' => 3]]); - $processor->shouldReceive('processSelect')->once()->andReturnUsing(function (Builder $countQuery, array $results): array { + )->returns([['aggregate' => 3]]); + $processor->expects('processSelect')->resolves(function (Builder $countQuery, array $results): array { $this->assertSame([11, 12, 15, 13, 14], $countQuery->getRawBindings()['from']); $this->assertSame([], $countQuery->getRawBindings()['select']); $this->assertSame([], $countQuery->getRawBindings()['where']); diff --git a/tests/Database/DatabaseQueryGrammarTest.php b/tests/Database/DatabaseQueryGrammarTest.php index d239071b10..e03440a7bc 100644 --- a/tests/Database/DatabaseQueryGrammarTest.php +++ b/tests/Database/DatabaseQueryGrammarTest.php @@ -13,24 +13,27 @@ use Hypervel\Database\Query\Grammars\MySqlGrammar; use Hypervel\Database\SQLiteConnection; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use PDO; use ReflectionClass; class DatabaseQueryGrammarTest extends TestCase { + use VerifiesDoubles; + public function testJsonContainsBindingRejectsUnencodableValues(): void { $this->expectException(JsonException::class); - (new Grammar(m::mock(Connection::class)))->prepareBindingForJsonContains(NAN); + (new Grammar(Double::for(Connection::class)))->prepareBindingForJsonContains(NAN); } public function testWrapIdentifierEscapesOneIdentifierWithoutApplyingTheTablePrefix(): void { - $connection = m::mock(Connection::class); - $connection->shouldNotReceive('getTablePrefix'); + $connection = Double::for(Connection::class); + $connection->expects('getTablePrefix')->never(); $grammar = new Grammar($connection); @@ -41,8 +44,8 @@ public function testWrapIdentifierEscapesOneIdentifierWithoutApplyingTheTablePre public function testQualifiedColumnsPrefixOnlyTheTableSegment(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getTablePrefix')->andReturn('app_'); + $connection = Double::for(Connection::class); + $connection->allows('getTablePrefix')->returns('app_'); $grammar = new Grammar($connection); $this->assertSame('"id"', $grammar->wrap('id')); @@ -119,9 +122,9 @@ public function testRawSqlBindingSubstitutionPreservesParserSemantics(): void $resourceIdentity = (string) $resource; try { - $connection = m::mock(Connection::class); - $connection->shouldReceive('escape')->once()->with('first', false)->andReturn("'first'"); - $connection->shouldReceive('escape')->once()->with($resourceIdentity, false)->andReturn("'resource'"); + $connection = Double::for(Connection::class); + $connection->expects('escape')->with('first', false)->returns("'first'"); + $connection->expects('escape')->with($resourceIdentity, false)->returns("'resource'"); $sql = (new Grammar($connection))->substituteBindingsIntoRawSql( "select ?, '?', ??, ?, ?", @@ -199,10 +202,10 @@ public function escape(string|float|int|bool|null $value, bool $binary = false): public function testRawSqlBindingSubstitutionHandlesLongBindingLists(): void { $bindings = range(1, 250); - $connection = m::mock(Connection::class); - $connection->shouldReceive('escape') + $connection = Double::for(Connection::class); + $connection->expects('escape') ->times(count($bindings)) - ->andReturnUsing(static fn (int $value, bool $binary): string => (string) $value); + ->resolves(static fn (int $value, bool $binary): string => (string) $value); $sql = (new Grammar($connection))->substituteBindingsIntoRawSql( implode(', ', array_fill(0, count($bindings), '?')), diff --git a/tests/Database/DatabaseReadPoolTest.php b/tests/Database/DatabaseReadPoolTest.php index 524e786224..bcdfd9ed6f 100644 --- a/tests/Database/DatabaseReadPoolTest.php +++ b/tests/Database/DatabaseReadPoolTest.php @@ -9,12 +9,15 @@ use Hypervel\Database\Pool\DatabasePool; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseReadPoolTest extends TestCase { + use VerifiesDoubles; + public function testReadRecordsAreSelectedForEachPhysicalCreationAndReconnect(): void { config(['database.connections.read_pool' => [ @@ -26,8 +29,8 @@ public function testReadRecordsAreSelectedForEachPhysicalCreationAndReconnect(): $factory = new ReadPoolConnectionFactory($this->app); $this->app->instance('db.factory', $factory); $hosts = []; - $connector = m::mock(ConnectorInterface::class); - $connector->expects('connect')->times(3)->andReturnUsing(static function (array $config) use (&$hosts): PDO { + $connector = Double::for(ConnectorInterface::class); + $connector->expects('connect')->times(3)->resolves(static function (array $config) use (&$hosts): PDO { $hosts[] = $config['host']; return new PDO('sqlite::memory:'); diff --git a/tests/Database/DatabaseSQLiteBuilderTest.php b/tests/Database/DatabaseSQLiteBuilderTest.php index 5118893731..4881cda0f9 100644 --- a/tests/Database/DatabaseSQLiteBuilderTest.php +++ b/tests/Database/DatabaseSQLiteBuilderTest.php @@ -14,8 +14,10 @@ use Hypervel\Support\Fluent; use Hypervel\Testbench\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; +use Override; use PDO; use PDOException; use PHPUnit\Framework\Attributes\DataProvider; @@ -23,6 +25,8 @@ class DatabaseSQLiteBuilderTest extends TestCase { + use VerifiesDoubles; + public function testCreateDatabase(): void { $connection = new SQLiteConnection(new PDO('sqlite::memory:')); @@ -75,8 +79,8 @@ public function testDropDatabaseIfExists(): void #[DataProvider('nonFileDatabaseNames')] public function testCreateDatabaseRejectsNonFileDatabaseNames(string $name): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); File::shouldReceive('put')->never(); @@ -91,8 +95,8 @@ public function testCreateDatabaseRejectsNonFileDatabaseNames(string $name): voi #[DataProvider('nonFileDatabaseNames')] public function testDropDatabaseRejectsNonFileDatabaseNames(string $name): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); File::shouldReceive('exists')->never(); File::shouldReceive('delete')->never(); @@ -116,79 +120,77 @@ public static function nonFileDatabaseNames(): array public function testExecuteBlueprintWrapsAKnownRebuildAndMaintainsForeignKeyStateOutsideTheTransaction(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $blueprint = $this->executionBlueprint( ['pragma foreign_keys = 0', 'first statement', 'second statement', 'pragma foreign_keys = 1'], [new Fluent(['name' => 'alter'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma foreign_keys = 0')->ordered(); - $connection->shouldReceive('transaction') - ->once() - ->andReturnUsing(static fn (Closure $callback) => $callback()) + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('pretending')->returns(false); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('executeSessionStatement')->with('pragma foreign_keys = 0')->ordered(); + $connection->expects('transaction') + ->resolves(static fn (Closure $callback) => $callback()) ->ordered(); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma foreign_keys = 1')->ordered(); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); + $connection->expects('executeSessionStatement')->with('pragma foreign_keys = 1')->ordered(); (new SQLiteBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintPreservesDisabledForeignKeysOutsideTheTransaction(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $blueprint = $this->executionBlueprint( ['first statement', 'second statement'], [new Fluent(['name' => 'alter'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('executeSessionStatement')->never(); - $connection->shouldReceive('transaction') - ->once() - ->andReturnUsing(static fn (Closure $callback) => $callback()); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('pretending')->returns(false); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('executeSessionStatement')->never(); + $connection->expects('transaction') + ->resolves(static fn (Closure $callback) => $callback()); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); (new SQLiteBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintDoesNotWrapASingleStatement(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $blueprint = $this->executionBlueprint( ['statement'], [new Fluent(['name' => 'create'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('pretending')->never(); - $connection->shouldReceive('transactionLevel')->never(); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('statement')->once()->with('statement')->andReturnTrue(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('pretending')->never(); + $connection->expects('transactionLevel')->never(); + $connection->expects('transaction')->never(); + $connection->expects('statement')->with('statement')->returns(true); (new SQLiteBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintDoesNotWrapCommandsAddedByAnExtensionGrammar(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteBuilderExtensionGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->twice()->andReturn($grammar); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.45.0'); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->never(); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('statement')->once()->with('extension statement one')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('extension statement two')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->times(2)->returns($grammar); + $connection->expects('getServerVersion')->returns('3.45.0'); + $connection->expects('pretending')->returns(false); + $connection->expects('transactionLevel')->never(); + $connection->expects('transaction')->never(); + $connection->expects('statement')->with('extension statement one')->returns(true)->ordered(); + $connection->expects('statement')->with('extension statement two')->returns(true)->ordered(); $blueprint = new SQLiteBuilderExtensionBlueprint( $connection, @@ -201,18 +203,17 @@ public function testExecuteBlueprintDoesNotWrapCommandsAddedByAnExtensionGrammar public function testExecuteBlueprintWrapsFrameworkCommandsOverriddenByAnExtensionGrammar(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteBuilderExtensionGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->twice()->andReturn($grammar); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.45.0'); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('transaction') - ->once() - ->andReturnUsing(static fn (Closure $callback) => $callback()); - $connection->shouldReceive('statement')->once()->with('overridden alter')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->times(2)->returns($grammar); + $connection->expects('getServerVersion')->returns('3.45.0'); + $connection->expects('pretending')->returns(false); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('transaction') + ->resolves(static fn (Closure $callback) => $callback()); + $connection->expects('statement')->with('overridden alter')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); $blueprint = new SQLiteBuilderExtensionBlueprint( $connection, @@ -225,26 +226,24 @@ public function testExecuteBlueprintWrapsFrameworkCommandsOverriddenByAnExtensio public function testExecuteBlueprintRestoresForeignKeysWhenTheTransactionFails(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $blueprint = $this->executionBlueprint( ['pragma foreign_keys = 0', 'failing statement', 'pragma foreign_keys = 1'], [new Fluent(['name' => 'alter'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma foreign_keys = 0')->ordered(); - $connection->shouldReceive('transaction') - ->once() - ->andReturnUsing(static fn (Closure $callback) => $callback()) + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('pretending')->returns(false); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('executeSessionStatement')->with('pragma foreign_keys = 0')->ordered(); + $connection->expects('transaction') + ->resolves(static fn (Closure $callback) => $callback()) ->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('statement') ->with('failing statement') - ->andThrow(new LogicException('statement failed')) + ->throws(new LogicException('statement failed')) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma foreign_keys = 1')->ordered(); + $connection->expects('executeSessionStatement')->with('pragma foreign_keys = 1')->ordered(); $this->expectException(LogicException::class); $this->expectExceptionMessageIs('statement failed'); @@ -299,24 +298,23 @@ public function testExecuteBlueprintCommitsSchemaBeforeForeignKeyRestorationFail public function testExecuteBlueprintRejectsAPopulatedRebuildInsideATransactionWithForeignKeysEnabled(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $blueprint = $this->executionBlueprint( ['pragma foreign_keys = 0', 'first statement', 'second statement', 'pragma foreign_keys = 1'], [new Fluent(['name' => 'alter'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldReceive('getTablePrefix')->once()->andReturn(''); - $blueprint->shouldReceive('getTable')->twice()->andReturn('users'); - $connection->shouldReceive('scalar') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('pretending')->returns(false); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('getTablePrefix')->returns(''); + $blueprint->expects('getTable')->times(2)->returns('users'); + $connection->expects('scalar') ->with('select exists (select 1 from "users" limit 1)', [], false) - ->andReturn(1); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('statement')->never(); + ->returns(1); + $connection->expects('transaction')->never(); + $connection->expects('statement')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs( @@ -328,83 +326,80 @@ public function testExecuteBlueprintRejectsAPopulatedRebuildInsideATransactionWi public function testExecuteBlueprintUsesASavepointForAnEmptyRebuildInsideATransaction(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $blueprint = $this->executionBlueprint( ['pragma foreign_keys = 0', 'first statement', 'second statement', 'pragma foreign_keys = 1'], [new Fluent(['name' => 'alter'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldReceive('getTablePrefix')->once()->andReturn(''); - $blueprint->shouldReceive('getTable')->once()->andReturn('users'); - $connection->shouldReceive('scalar') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('pretending')->returns(false); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('getTablePrefix')->returns(''); + $blueprint->expects('getTable')->returns('users'); + $connection->expects('scalar') ->with('select exists (select 1 from "users" limit 1)', [], false) - ->andReturn(0); - $connection->shouldReceive('transaction') - ->once() - ->andReturnUsing(static fn (Closure $callback) => $callback()); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + ->returns(0); + $connection->expects('transaction') + ->resolves(static fn (Closure $callback) => $callback()); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); (new SQLiteBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintUsesASavepointInsideATransactionWhenForeignKeysAreDisabled(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $blueprint = $this->executionBlueprint( ['first statement', 'second statement'], [new Fluent(['name' => 'alter'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('pretending')->once()->andReturnFalse(); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldReceive('scalar')->never(); - $connection->shouldReceive('transaction') - ->once() - ->andReturnUsing(static fn (Closure $callback) => $callback()); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('pretending')->returns(false); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('scalar')->never(); + $connection->expects('transaction') + ->resolves(static fn (Closure $callback) => $callback()); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); (new SQLiteBuilder($connection))->executeBlueprint($blueprint); } public function testExecuteBlueprintDoesNotMutateSessionOrTransactionStateWhilePretending(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $blueprint = $this->executionBlueprint( ['pragma foreign_keys = 0', 'first statement', 'second statement', 'pragma foreign_keys = 1'], [new Fluent(['name' => 'alter'])], ); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('pretending')->once()->andReturnTrue(); - $connection->shouldReceive('transactionLevel')->never(); - $connection->shouldReceive('transaction')->never(); - $connection->shouldReceive('executeSessionStatement')->never(); - $connection->shouldReceive('statement')->once()->with('pragma foreign_keys = 0')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('first statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('second statement')->andReturnTrue()->ordered(); - $connection->shouldReceive('statement')->once()->with('pragma foreign_keys = 1')->andReturnTrue()->ordered(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('pretending')->returns(true); + $connection->expects('transactionLevel')->never(); + $connection->expects('transaction')->never(); + $connection->expects('executeSessionStatement')->never(); + $connection->expects('statement')->with('pragma foreign_keys = 0')->returns(true)->ordered(); + $connection->expects('statement')->with('first statement')->returns(true)->ordered(); + $connection->expects('statement')->with('second statement')->returns(true)->ordered(); + $connection->expects('statement')->with('pragma foreign_keys = 1')->returns(true)->ordered(); (new SQLiteBuilder($connection))->executeBlueprint($blueprint); } public function testChangingForeignKeyConstraintsInsideATransactionFailsBeforeExecutingThePragma(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldReceive('statement')->never(); + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('statement')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs( @@ -541,24 +536,22 @@ public function testWithoutForeignKeyConstraintsAllowsAnAlreadyDisabledStateInsi public function testDropAllTablesUsesGuardedCatalogCleanup(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0)->ordered(); - $connection->shouldReceive('scalar')->once()->with('pragma writable_schema', [], false)->andReturn(0)->ordered(); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.45.0')->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = 1')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0)->ordered(); + $connection->expects('scalar')->with('pragma writable_schema', [], false)->returns(0)->ordered(); + $connection->expects('getServerVersion')->returns('3.45.0')->ordered(); + $connection->expects('executeSessionStatement')->with('pragma writable_schema = 1')->ordered(); + $connection->expects('statement') ->with($grammar->compileDropAllTables('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = RESET')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('executeSessionStatement')->with('pragma writable_schema = RESET')->ordered(); + $connection->expects('statement') ->with($grammar->compileRebuild('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); (new SQLiteBuilder($connection))->dropAllTables(); @@ -566,46 +559,43 @@ public function testDropAllTablesUsesGuardedCatalogCleanup(): void public function testDropAllViewsRestoresAnEnabledWritableSchema(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0)->ordered(); - $connection->shouldReceive('scalar')->once()->with('pragma writable_schema', [], false)->andReturn(1)->ordered(); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.45.0')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0)->ordered(); + $connection->expects('scalar')->with('pragma writable_schema', [], false)->returns(1)->ordered(); + $connection->expects('getServerVersion')->returns('3.45.0')->ordered(); + $connection->expects('statement') ->with($grammar->compileDropAllViews('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = RESET')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('executeSessionStatement')->with('pragma writable_schema = RESET')->ordered(); + $connection->expects('statement') ->with($grammar->compileRebuild('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = 1')->ordered(); + $connection->expects('executeSessionStatement')->with('pragma writable_schema = 1')->ordered(); (new SQLiteBuilder($connection))->dropAllViews(); } public function testDropAllTablesReloadsTheSchemaAfterADeleteFailure(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('scalar')->once()->with('pragma writable_schema', [], false)->andReturn(0); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.45.0'); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = 1')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('scalar')->with('pragma writable_schema', [], false)->returns(0); + $connection->expects('getServerVersion')->returns('3.45.0'); + $connection->expects('executeSessionStatement')->with('pragma writable_schema = 1')->ordered(); + $connection->expects('statement') ->with($grammar->compileDropAllTables('main')) - ->andReturnFalse() + ->returns(false) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = RESET')->ordered(); - $connection->shouldReceive('statement')->with($grammar->compileRebuild('main'))->never(); + $connection->expects('executeSessionStatement')->with('pragma writable_schema = RESET')->ordered(); + $connection->expects('statement')->with($grammar->compileRebuild('main'))->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs( @@ -617,26 +607,24 @@ public function testDropAllTablesReloadsTheSchemaAfterADeleteFailure(): void public function testDropAllTablesMarksALegacySessionUnknownWhenVacuumFails(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('scalar')->once()->with('pragma writable_schema', [], false)->andReturn(0); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.36.0'); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = 1')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('scalar')->with('pragma writable_schema', [], false)->returns(0); + $connection->expects('getServerVersion')->returns('3.36.0'); + $connection->expects('executeSessionStatement')->with('pragma writable_schema = 1')->ordered(); + $connection->expects('statement') ->with($grammar->compileDropAllTables('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = 0')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('executeSessionStatement')->with('pragma writable_schema = 0')->ordered(); + $connection->expects('statement') ->with($grammar->compileRebuild('main')) - ->andReturnFalse() + ->returns(false) ->ordered(); - $connection->shouldReceive('markCurrentSessionStateUnknown')->once(); + $connection->expects('markCurrentSessionStateUnknown'); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Failed to execute schema statement [vacuum "main"].'); @@ -646,26 +634,24 @@ public function testDropAllTablesMarksALegacySessionUnknownWhenVacuumFails(): vo public function testDropAllTablesKeepsAModernSessionKnownWhenVacuumFailsAfterReset(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('scalar')->once()->with('pragma writable_schema', [], false)->andReturn(0); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.45.0'); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = 1')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('scalar')->with('pragma writable_schema', [], false)->returns(0); + $connection->expects('getServerVersion')->returns('3.45.0'); + $connection->expects('executeSessionStatement')->with('pragma writable_schema = 1')->ordered(); + $connection->expects('statement') ->with($grammar->compileDropAllTables('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = RESET')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('executeSessionStatement')->with('pragma writable_schema = RESET')->ordered(); + $connection->expects('statement') ->with($grammar->compileRebuild('main')) - ->andReturnFalse() + ->returns(false) ->ordered(); - $connection->shouldReceive('markCurrentSessionStateUnknown')->never(); + $connection->expects('markCurrentSessionStateUnknown')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('Failed to execute schema statement [vacuum "main"].'); @@ -675,26 +661,24 @@ public function testDropAllTablesKeepsAModernSessionKnownWhenVacuumFailsAfterRes public function testDropAllTablesStopsBeforeSchemaReloadWhenWritableSchemaResetFails(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $failure = new PDOException('Failed to reset writable_schema.'); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('scalar')->once()->with('pragma writable_schema', [], false)->andReturn(0); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.45.0'); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = 1')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('scalar')->with('pragma writable_schema', [], false)->returns(0); + $connection->expects('getServerVersion')->returns('3.45.0'); + $connection->expects('executeSessionStatement')->with('pragma writable_schema = 1')->ordered(); + $connection->expects('statement') ->with($grammar->compileDropAllTables('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement') - ->once() + $connection->expects('executeSessionStatement') ->with('pragma writable_schema = RESET') - ->andThrow($failure) + ->throws($failure) ->ordered(); - $connection->shouldReceive('statement')->with($grammar->compileRebuild('main'))->never(); + $connection->expects('statement')->with($grammar->compileRebuild('main'))->never(); try { (new SQLiteBuilder($connection))->dropAllTables(); @@ -706,29 +690,26 @@ public function testDropAllTablesStopsBeforeSchemaReloadWhenWritableSchemaResetF public function testDropAllViewsPropagatesWritableModeRestorationFailure(): void { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $grammar = new SQLiteGrammar($connection); $failure = new PDOException('Failed to restore writable_schema.'); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn($grammar); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('scalar')->once()->with('pragma writable_schema', [], false)->andReturn(1); - $connection->shouldReceive('getServerVersion')->once()->andReturn('3.45.0'); - $connection->shouldReceive('statement') - ->once() + $connection->expects('getSchemaGrammar')->returns($grammar); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('scalar')->with('pragma writable_schema', [], false)->returns(1); + $connection->expects('getServerVersion')->returns('3.45.0'); + $connection->expects('statement') ->with($grammar->compileDropAllViews('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement')->once()->with('pragma writable_schema = RESET')->ordered(); - $connection->shouldReceive('statement') - ->once() + $connection->expects('executeSessionStatement')->with('pragma writable_schema = RESET')->ordered(); + $connection->expects('statement') ->with($grammar->compileRebuild('main')) - ->andReturnTrue() + ->returns(true) ->ordered(); - $connection->shouldReceive('executeSessionStatement') - ->once() + $connection->expects('executeSessionStatement') ->with('pragma writable_schema = 1') - ->andThrow($failure) + ->throws($failure) ->ordered(); try { @@ -741,11 +722,11 @@ public function testDropAllViewsPropagatesWritableModeRestorationFailure(): void public function testDropAllTablesRejectsAnActiveTransactionBeforeInspectingTheSchema(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldReceive('scalar')->never(); - $connection->shouldReceive('statement')->never(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('scalar')->never(); + $connection->expects('statement')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('SQLite cannot drop all tables within an active transaction.'); @@ -755,11 +736,11 @@ public function testDropAllTablesRejectsAnActiveTransactionBeforeInspectingTheSc public function testDropAllViewsRejectsAnActiveTransactionBeforeInspectingTheSchema(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldReceive('scalar')->never(); - $connection->shouldReceive('statement')->never(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('scalar')->never(); + $connection->expects('statement')->never(); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs('SQLite cannot drop all views within an active transaction.'); @@ -769,14 +750,14 @@ public function testDropAllViewsRejectsAnActiveTransactionBeforeInspectingTheSch public function testRefreshDatabaseFileUsesTheCanonicalMainDatabasePath(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('getDatabaseName')->once()->andReturn('file:database.sqlite?mode=rwc'); - $connection->shouldReceive('scalar')->once()->with('pragma journal_mode', [], false)->andReturn('delete'); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('getDatabaseName')->returns('file:database.sqlite?mode=rwc'); + $connection->expects('scalar')->with('pragma journal_mode', [], false)->returns('delete'); - $builder = m::mock(SQLiteBuilder::class, [$connection])->makePartial(); - $builder->shouldReceive('getSchemas')->once()->andReturn([ + $builder = Double::for(new SQLiteBuilder($connection))->passthru(); + $builder->expects('getSchemas')->returns([ ['name' => 'main', 'path' => '/canonical/database.sqlite'], ]); @@ -787,12 +768,12 @@ public function testRefreshDatabaseFileUsesTheCanonicalMainDatabasePath(): void public function testRefreshDatabaseFileRejectsWalForTheConnectedDatabase(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('getDatabaseName')->once()->andReturn('/database.sqlite'); - $connection->shouldReceive('scalar')->once()->with('pragma journal_mode', [], false)->andReturn('wal'); - $connection->shouldReceive('selectFromWriteConnection')->never(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('getDatabaseName')->returns('/database.sqlite'); + $connection->expects('scalar')->with('pragma journal_mode', [], false)->returns('wal'); + $connection->expects('selectFromWriteConnection')->never(); File::shouldReceive('put')->never(); $this->expectException(RuntimeException::class); @@ -805,11 +786,11 @@ public function testRefreshDatabaseFileRejectsWalForTheConnectedDatabase(): void public function testRefreshDatabaseFileRejectsAnActiveTransactionBeforeInspectingTheDatabase(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); - $connection->shouldReceive('transactionLevel')->once()->andReturn(1); - $connection->shouldReceive('getDatabaseName')->never(); - $connection->shouldReceive('scalar')->never(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); + $connection->expects('transactionLevel')->returns(1); + $connection->expects('getDatabaseName')->never(); + $connection->expects('scalar')->never(); File::shouldReceive('put')->never(); $this->expectException(RuntimeException::class); @@ -820,12 +801,12 @@ public function testRefreshDatabaseFileRejectsAnActiveTransactionBeforeInspectin public function testRefreshDatabaseFileWithAnExplicitPathDoesNotInspectTheConnection(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); - $connection->shouldReceive('transactionLevel')->never(); - $connection->shouldReceive('getDatabaseName')->never(); - $connection->shouldReceive('scalar')->never(); - $connection->shouldReceive('selectFromWriteConnection')->never(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); + $connection->expects('transactionLevel')->never(); + $connection->expects('getDatabaseName')->never(); + $connection->expects('scalar')->never(); + $connection->expects('selectFromWriteConnection')->never(); File::shouldReceive('put')->once()->with('/database.sqlite', '')->andReturn(0); (new SQLiteBuilder($connection))->refreshDatabaseFile('/database.sqlite'); @@ -834,11 +815,11 @@ public function testRefreshDatabaseFileWithAnExplicitPathDoesNotInspectTheConnec #[DataProvider('inMemoryDatabaseNames')] public function testRefreshDatabaseFileRejectsInMemoryDatabasesWithoutWritingAFile(string $database): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); - $connection->shouldReceive('transactionLevel')->once()->andReturn(0); - $connection->shouldReceive('getDatabaseName')->once()->andReturn($database); - $connection->shouldReceive('scalar')->never(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); + $connection->expects('transactionLevel')->returns(0); + $connection->expects('getDatabaseName')->returns($database); + $connection->expects('scalar')->never(); File::shouldReceive('put')->never(); $this->expectException(InvalidArgumentException::class); @@ -863,8 +844,8 @@ public static function inMemoryDatabaseNames(): array public function testRefreshDatabaseFileThrowsWhenTheFileCannotBeWritten(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getSchemaGrammar')->once()->andReturn(new SQLiteGrammar($connection)); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection)); File::shouldReceive('put') ->once() @@ -885,9 +866,9 @@ public function testRefreshDatabaseFileThrowsWhenTheFileCannotBeWritten(): void */ protected function executionBlueprint(array $statements, array $commands): Blueprint { - $blueprint = m::mock(Blueprint::class); - $blueprint->shouldReceive('toSql')->once()->andReturn($statements); - $blueprint->shouldReceive('getCommands')->andReturn($commands); + $blueprint = Double::for(Blueprint::class); + $blueprint->expects('toSql')->returns($statements); + $blueprint->allows('getCommands')->returns($commands); return $blueprint; } diff --git a/tests/Database/DatabaseSQLiteQueryGrammarTest.php b/tests/Database/DatabaseSQLiteQueryGrammarTest.php index 5994047d23..bcaae5685c 100755 --- a/tests/Database/DatabaseSQLiteQueryGrammarTest.php +++ b/tests/Database/DatabaseSQLiteQueryGrammarTest.php @@ -8,17 +8,20 @@ use Hypervel\Database\PdoConnection; use Hypervel\Database\Query\Grammars\SQLiteGrammar; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use PDO; class DatabaseSQLiteQueryGrammarTest extends TestCase { + use VerifiesDoubles; + public function testUpdateBindingsRejectUnencodableArrays(): void { $this->expectException(JsonException::class); - (new SQLiteGrammar(m::mock(Connection::class))) + (new SQLiteGrammar(Double::for(Connection::class))) ->prepareBindingsForUpdate([], ['payload' => [NAN]]); } diff --git a/tests/Database/DatabaseSQLiteSchemaMetadataTest.php b/tests/Database/DatabaseSQLiteSchemaMetadataTest.php index bd9a5d65a9..3fb8708890 100644 --- a/tests/Database/DatabaseSQLiteSchemaMetadataTest.php +++ b/tests/Database/DatabaseSQLiteSchemaMetadataTest.php @@ -10,23 +10,26 @@ use Hypervel\Database\Schema\Grammars\SQLiteGrammar; use Hypervel\Database\Schema\SQLiteBuilder; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Override; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseSQLiteSchemaMetadataTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('tableListingVersions')] public function testBothTableListingPathsUseTheMetadataHook(string $version, string $compiler): void { [$builder, $connection, $grammar, $processor] = $this->builder(); - $connection->shouldReceive('getServerVersion')->once()->andReturn($version); - $grammar->shouldReceive('compileDbstatExists')->once()->andReturn('dbstat sql'); - $connection->shouldReceive('scalar')->once()->with('dbstat sql')->andReturn(1); - $grammar->shouldReceive($compiler)->once()->with('main', true)->andReturn('tables sql'); + $connection->expects('getServerVersion')->returns($version); + $grammar->expects('compileDbstatExists')->returns('dbstat sql'); + $connection->expects('scalar')->with('dbstat sql')->returns(1); + $grammar->expects($compiler)->with('main', true)->returns('tables sql'); $rows = [(object) ['name' => 'users']]; - $connection->shouldReceive('selectFromWriteConnection')->once()->with('tables sql')->andReturn($rows); - $processor->shouldReceive('processTables')->once()->with($rows)->andReturn([['name' => 'users']]); + $connection->expects('selectFromWriteConnection')->with('tables sql')->returns($rows); + $processor->expects('processTables')->with($rows)->returns([['name' => 'users']]); $this->assertSame([['name' => 'users']], $builder->getTables('main')); $this->assertSame(['tables sql'], $builder->metadataQueries); @@ -43,23 +46,23 @@ public static function tableListingVersions(): array public function testViewsAndSchemaStateReadsUseTheMetadataHook(): void { [$builder, $connection, $grammar, $processor] = $this->builder(); - $connection->shouldReceive('getTablePrefix')->andReturn('app_'); - $grammar->shouldReceive('compileViews')->once()->with('main')->andReturn('views sql'); - $grammar->shouldReceive('compileColumns')->once()->with('main', 'app_users')->andReturn('columns sql'); - $grammar->shouldReceive('compileIndexes')->once()->with('main', 'app_users')->andReturn('indexes sql'); - $grammar->shouldReceive('compileForeignKeys')->once()->with('main', 'app_users')->andReturn('foreign keys sql'); - $grammar->shouldReceive('compileSqlCreateStatement')->once()->with('main', 'app_users')->andReturn('definition sql'); - $connection->shouldNotReceive('scalar'); - $connection->shouldReceive('selectFromWriteConnection')->once()->with('definition sql')->andReturn([(object) ['sql' => 'create table app_users (id integer)']]); + $connection->allows('getTablePrefix')->returns('app_'); + $grammar->expects('compileViews')->with('main')->returns('views sql'); + $grammar->expects('compileColumns')->with('main', 'app_users')->returns('columns sql'); + $grammar->expects('compileIndexes')->with('main', 'app_users')->returns('indexes sql'); + $grammar->expects('compileForeignKeys')->with('main', 'app_users')->returns('foreign keys sql'); + $grammar->expects('compileSqlCreateStatement')->with('main', 'app_users')->returns('definition sql'); + $connection->expects('scalar')->never(); + $connection->expects('selectFromWriteConnection')->with('definition sql')->returns([(object) ['sql' => 'create table app_users (id integer)']]); foreach (['views', 'columns', 'indexes', 'foreign keys'] as $kind) { - $connection->shouldReceive('selectFromWriteConnection')->once()->with($kind . ' sql')->andReturn([(object) ['name' => $kind]]); + $connection->expects('selectFromWriteConnection')->with($kind . ' sql')->returns([(object) ['name' => $kind]]); } - $processor->shouldReceive('processViews')->once()->with([(object) ['name' => 'views']])->andReturn([['name' => 'active_users']]); - $processor->shouldReceive('processColumns')->once()->with([(object) ['name' => 'columns']], 'create table app_users (id integer)')->andReturn([['name' => 'id']]); - $processor->shouldReceive('processIndexesForSchemaState')->once()->with([(object) ['name' => 'indexes']])->andReturn([['name' => 'primary']]); - $processor->shouldReceive('processForeignKeysForSchemaState')->once()->with([(object) ['name' => 'foreign keys']])->andReturn([['implicit' => true]]); + $processor->expects('processViews')->with([(object) ['name' => 'views']])->returns([['name' => 'active_users']]); + $processor->expects('processColumns')->with([(object) ['name' => 'columns']], 'create table app_users (id integer)')->returns([['name' => 'id']]); + $processor->expects('processIndexesForSchemaState')->with([(object) ['name' => 'indexes']])->returns([['name' => 'primary']]); + $processor->expects('processForeignKeysForSchemaState')->with([(object) ['name' => 'foreign keys']])->returns([['implicit' => true]]); $this->assertSame([['name' => 'active_users']], $builder->getViews('main')); $this->assertSame(['columns' => [['name' => 'id']], 'sql' => 'create table app_users (id integer)'], $builder->getColumnsForSchemaState('main.users')); @@ -72,13 +75,13 @@ public function testViewsAndSchemaStateReadsUseTheMetadataHook(): void public function testStoredDefinitionRetainsScalarResultHandling(array $rows, string $sql): void { [$builder, $connection, $grammar, $processor] = $this->builder(); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $grammar->shouldReceive('compileColumns')->once()->with('main', 'users')->andReturn('columns sql'); - $grammar->shouldReceive('compileSqlCreateStatement')->once()->with('main', 'users')->andReturn('definition sql'); - $connection->shouldReceive('selectFromWriteConnection')->once()->with('columns sql')->andReturn([]); - $connection->shouldReceive('selectFromWriteConnection')->once()->with('definition sql')->andReturn($rows); - $connection->shouldNotReceive('scalar'); - $processor->shouldReceive('processColumns')->once()->with([], $sql)->andReturn([]); + $connection->allows('getTablePrefix')->returns(''); + $grammar->expects('compileColumns')->with('main', 'users')->returns('columns sql'); + $grammar->expects('compileSqlCreateStatement')->with('main', 'users')->returns('definition sql'); + $connection->expects('selectFromWriteConnection')->with('columns sql')->returns([]); + $connection->expects('selectFromWriteConnection')->with('definition sql')->returns($rows); + $connection->expects('scalar')->never(); + $processor->expects('processColumns')->with([], $sql)->returns([]); $this->assertSame(['columns' => [], 'sql' => $sql], $builder->getColumnsForSchemaState('main.users')); $this->assertSame(['columns sql', 'definition sql'], $builder->metadataQueries); @@ -96,13 +99,13 @@ public static function storedDefinitions(): array public function testStoredDefinitionRejectsMultipleColumns(): void { [$builder, $connection, $grammar, $processor] = $this->builder(); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $grammar->shouldReceive('compileColumns')->once()->with('main', 'users')->andReturn('columns sql'); - $grammar->shouldReceive('compileSqlCreateStatement')->once()->with('main', 'users')->andReturn('definition sql'); - $connection->shouldReceive('selectFromWriteConnection')->once()->with('columns sql')->andReturn([]); - $connection->shouldReceive('selectFromWriteConnection')->once()->with('definition sql')->andReturn([(object) ['sql' => 'create table users (id integer)', 'extra' => 1]]); - $connection->shouldNotReceive('scalar'); - $processor->shouldNotReceive('processColumns'); + $connection->allows('getTablePrefix')->returns(''); + $grammar->expects('compileColumns')->with('main', 'users')->returns('columns sql'); + $grammar->expects('compileSqlCreateStatement')->with('main', 'users')->returns('definition sql'); + $connection->expects('selectFromWriteConnection')->with('columns sql')->returns([]); + $connection->expects('selectFromWriteConnection')->with('definition sql')->returns([(object) ['sql' => 'create table users (id integer)', 'extra' => 1]]); + $connection->expects('scalar')->never(); + $processor->expects('processColumns')->never(); $this->expectException(MultipleColumnsSelectedException::class); @@ -111,11 +114,11 @@ public function testStoredDefinitionRejectsMultipleColumns(): void protected function builder(): array { - $connection = m::mock(Connection::class); - $grammar = m::mock(SQLiteGrammar::class); - $processor = m::mock(SQLiteProcessor::class); - $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); - $connection->shouldReceive('getPostProcessor')->andReturn($processor); + $connection = Double::for(Connection::class); + $grammar = Double::for(SQLiteGrammar::class); + $processor = Double::for(SQLiteProcessor::class); + $connection->allows('getSchemaGrammar')->returns($grammar); + $connection->allows('getPostProcessor')->returns($processor); return [new SQLiteMetadataRecordingBuilder($connection), $connection, $grammar, $processor]; } diff --git a/tests/Database/DatabaseSchemaDumpCommandTest.php b/tests/Database/DatabaseSchemaDumpCommandTest.php index c7b28e0085..e7d9f3865f 100644 --- a/tests/Database/DatabaseSchemaDumpCommandTest.php +++ b/tests/Database/DatabaseSchemaDumpCommandTest.php @@ -9,11 +9,14 @@ use Hypervel\Database\Console\DumpCommand; use Hypervel\Database\Schema\SchemaState; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class DatabaseSchemaDumpCommandTest extends TestCase { + use VerifiesDoubles; + public function testDumpCommandExitsWhenProhibited(): void { $path = database_path('schema/prohibited-dump.sql'); @@ -50,16 +53,16 @@ public function testDumpUsesAndIsNamedAfterTheMigrationConnection(array $options 'database.connections.pgsql' => ['driver' => 'pgsql'], ]); - $connection = m::mock(Connection::class); - $state = m::mock(SchemaState::class); - $connection->allows('getName')->andReturn('pgsql'); - $connection->allows('getSchemaState')->andReturn($state); - $state->allows('withMigrationTable')->andReturnSelf(); - $state->allows('handleOutputUsing')->andReturnSelf(); + $connection = Double::for(Connection::class); + $state = Double::for(SchemaState::class); + $connection->allows('getName')->returns('pgsql'); + $connection->allows('getSchemaState')->returns($state); + $state->allows('withMigrationTable'); + $state->allows('handleOutputUsing'); $state->expects('dump')->with($connection, database_path('schema/pgsql-schema.sql')); - $connections = m::mock(ConnectionResolverInterface::class); - $connections->expects('connection')->with('pgsql')->andReturn($connection); + $connections = Double::for(ConnectionResolverInterface::class); + $connections->expects('connection')->with('pgsql')->returns($connection); $this->app->instance(ConnectionResolverInterface::class, $connections); $this->artisan('schema:dump', $options)->assertSuccessful(); diff --git a/tests/Database/DatabaseWipeCommandTest.php b/tests/Database/DatabaseWipeCommandTest.php index ef5ab9a913..e34c6edccd 100644 --- a/tests/Database/DatabaseWipeCommandTest.php +++ b/tests/Database/DatabaseWipeCommandTest.php @@ -6,37 +6,36 @@ use Hypervel\Config\Repository; use Hypervel\Context\CoroutineContext; +use Hypervel\Database\Connection; use Hypervel\Database\ConnectionResolver; use Hypervel\Database\Console\WipeCommand; +use Hypervel\Database\DatabaseManager; +use Hypervel\Database\Schema\Builder; use Hypervel\Foundation\Application; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; class DatabaseWipeCommandTest extends TestCase { - protected function tearDown(): void - { - CoroutineContext::forget(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY); - - parent::tearDown(); - } + use VerifiesDoubles; public function testWipeCommandDropsSchemaObjectsAndDisconnectsConnection(): void { - $schemaBuilder = m::mock(); - $schemaBuilder->shouldReceive('dropAllViews')->once(); - $schemaBuilder->shouldReceive('dropAllTables')->once(); - $schemaBuilder->shouldReceive('dropAllTypes')->once(); + $schemaBuilder = Double::for(Builder::class); + $schemaBuilder->expects('dropAllViews'); + $schemaBuilder->expects('dropAllTables'); + $schemaBuilder->expects('dropAllTypes'); - $connection = m::mock(); - $connection->shouldReceive('getSchemaBuilder')->times(3)->andReturn($schemaBuilder); - $connection->shouldReceive('disconnect')->once(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaBuilder')->times(3)->returns($schemaBuilder); + $connection->expects('disconnect'); - $db = m::mock(); - $db->shouldReceive('connection')->times(4)->with('pgsql')->andReturn($connection); - $db->shouldNotReceive('purge'); + $db = Double::for(DatabaseManager::class); + $db->expects('connection')->times(4)->with('pgsql')->returns($connection); + $db->expects('purge')->never(); $app = new ApplicationDatabaseWipeStub([ 'db' => $db, @@ -56,19 +55,19 @@ public function testWipeCommandDropsSchemaObjectsAndDisconnectsConnection(): voi public function testWipeCommandRoutesToMigrationsConnection(): void { - $schemaBuilder = m::mock(); - $schemaBuilder->shouldReceive('dropAllTables')->once(); + $schemaBuilder = Double::for(Builder::class); + $schemaBuilder->expects('dropAllTables'); - $connection = m::mock(); - $connection->shouldReceive('getSchemaBuilder')->once()->andReturn($schemaBuilder); - $connection->shouldReceive('disconnect')->once(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaBuilder')->returns($schemaBuilder); + $connection->expects('disconnect'); - $db = m::mock(); + $db = Double::for(DatabaseManager::class); // db:wipe --database=pgsql-pooled should route to 'pgsql' because // pgsql-pooled has migrations_connection => 'pgsql'. Schema drops // need a direct (unpooled) connection. - $db->shouldReceive('connection')->twice()->with('pgsql')->andReturn($connection); - $db->shouldNotReceive('purge'); + $db->expects('connection')->times(2)->with('pgsql')->returns($connection); + $db->expects('purge')->never(); $app = new ApplicationDatabaseWipeStub([ 'db' => $db, @@ -98,16 +97,16 @@ public function testWipeCommandRoutesThroughDefaultWhenNoDatabaseOptionGiven(): // should use the configured default — and if that default has a // migrations_connection, should route to it rather than dropping // tables on the pooled connection. - $schemaBuilder = m::mock(); - $schemaBuilder->shouldReceive('dropAllTables')->once(); + $schemaBuilder = Double::for(Builder::class); + $schemaBuilder->expects('dropAllTables'); - $connection = m::mock(); - $connection->shouldReceive('getSchemaBuilder')->once()->andReturn($schemaBuilder); - $connection->shouldReceive('disconnect')->once(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaBuilder')->returns($schemaBuilder); + $connection->expects('disconnect'); - $db = m::mock(); - $db->shouldReceive('connection')->twice()->with('pgsql')->andReturn($connection); - $db->shouldNotReceive('purge'); + $db = Double::for(DatabaseManager::class); + $db->expects('connection')->times(2)->with('pgsql')->returns($connection); + $db->expects('purge')->never(); $app = new ApplicationDatabaseWipeStub([ 'db' => $db, @@ -136,16 +135,16 @@ public function testWipeCommandHonorsContextOverrideWhenNoDatabaseOptionGiven(): // when an outer scope has set Context (e.g. via DB::usingConnection), // db:wipe with no --database must route to that Context target's // migrations_connection, not to the configured default's sibling. - $schemaBuilder = m::mock(); - $schemaBuilder->shouldReceive('dropAllTables')->once(); + $schemaBuilder = Double::for(Builder::class); + $schemaBuilder->expects('dropAllTables'); - $connection = m::mock(); - $connection->shouldReceive('getSchemaBuilder')->once()->andReturn($schemaBuilder); - $connection->shouldReceive('disconnect')->once(); + $connection = Double::for(Connection::class); + $connection->expects('getSchemaBuilder')->returns($schemaBuilder); + $connection->expects('disconnect'); - $db = m::mock(); - $db->shouldReceive('connection')->twice()->with('tenant-direct')->andReturn($connection); - $db->shouldNotReceive('purge'); + $db = Double::for(DatabaseManager::class); + $db->expects('connection')->times(2)->with('tenant-direct')->returns($connection); + $db->expects('purge')->never(); $app = new ApplicationDatabaseWipeStub([ 'db' => $db, diff --git a/tests/Database/Eloquent/CustomBuilderForwardingTest.php b/tests/Database/Eloquent/CustomBuilderForwardingTest.php index 18442299ff..e9da8d47f7 100644 --- a/tests/Database/Eloquent/CustomBuilderForwardingTest.php +++ b/tests/Database/Eloquent/CustomBuilderForwardingTest.php @@ -13,10 +13,13 @@ use Hypervel\Database\Query\Processors\Processor; use Hypervel\Support\Collection; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class CustomBuilderForwardingTest extends TestCase { + use VerifiesDoubles; + public function testOrdinaryForwardingDiscardsResultsButPassthruAndNativeTerminalsReturnThem(): void { $builder = $this->builder(new ForwardingTestModel); @@ -70,7 +73,7 @@ public function testScopesWinOverQueryForwardingButNotNativeEloquentOrRelationMe */ private function builder(Model $model): ForwardingTestBuilder { - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $query = new ForwardingTestQuery($connection, new Grammar($connection), new Processor); return (new ForwardingTestBuilder($query))->setModel($model); diff --git a/tests/Database/Eloquent/ModelBootTest.php b/tests/Database/Eloquent/ModelBootTest.php index 6a391fe6b9..8087bae7ac 100644 --- a/tests/Database/Eloquent/ModelBootTest.php +++ b/tests/Database/Eloquent/ModelBootTest.php @@ -9,8 +9,10 @@ use Hypervel\Engine\Channel; use Hypervel\Engine\Coroutine; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use ReflectionProperty; use RuntimeException; use Throwable; @@ -19,6 +21,8 @@ class ModelBootTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -141,15 +145,13 @@ public function testBootedCallbackFailureLeavesTheModelPublishedAndClearsOwnersh public function testBootedEventFailureLeavesTheModelPublishedAndClearsOwnership(): void { $failure = new RuntimeException('booted event failure'); - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with('eloquent.booting: ' . PostPublicationFailureModel::class, m::type(PostPublicationFailureModel::class)) - ->andReturnNull(); - $dispatcher->shouldReceive('dispatch') - ->once() - ->with('eloquent.booted: ' . PostPublicationFailureModel::class, m::type(PostPublicationFailureModel::class)) - ->andThrow($failure); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch') + ->with('eloquent.booting: ' . PostPublicationFailureModel::class, Argument::type(PostPublicationFailureModel::class)) + ->returns(null); + $dispatcher->expects('dispatch') + ->with('eloquent.booted: ' . PostPublicationFailureModel::class, Argument::type(PostPublicationFailureModel::class)) + ->throws($failure); Model::setEventDispatcher($dispatcher); try { diff --git a/tests/Database/Eloquent/NewBaseQueryBuilderTest.php b/tests/Database/Eloquent/NewBaseQueryBuilderTest.php index 042d5795da..ce13371ebd 100644 --- a/tests/Database/Eloquent/NewBaseQueryBuilderTest.php +++ b/tests/Database/Eloquent/NewBaseQueryBuilderTest.php @@ -12,7 +12,8 @@ use Hypervel\Database\Query\Grammars\Grammar; use Hypervel\Database\Query\Processors\Processor; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; /** * Tests that Model, Pivot, and MorphPivot delegate to the connection's @@ -21,17 +22,19 @@ */ class NewBaseQueryBuilderTest extends TestCase { + use VerifiesDoubles; + public function testModelUsesConnectionQueryMethod(): void { - $mockConnection = m::mock(Connection::class); + $mockConnection = Double::for(Connection::class); $customBuilder = new CustomQueryBuilder( $mockConnection, new Grammar($mockConnection), new Processor ); - $connection = m::mock(Connection::class); - $connection->shouldReceive('query')->once()->andReturn($customBuilder); + $connection = Double::for(Connection::class); + $connection->expects('query')->returns($customBuilder); $model = new NewBaseQueryBuilderTestModel; $model->setTestConnection($connection); @@ -44,15 +47,15 @@ public function testModelUsesConnectionQueryMethod(): void public function testPivotUsesConnectionQueryMethod(): void { - $mockConnection = m::mock(Connection::class); + $mockConnection = Double::for(Connection::class); $customBuilder = new CustomQueryBuilder( $mockConnection, new Grammar($mockConnection), new Processor ); - $connection = m::mock(Connection::class); - $connection->shouldReceive('query')->once()->andReturn($customBuilder); + $connection = Double::for(Connection::class); + $connection->expects('query')->returns($customBuilder); $pivot = new NewBaseQueryBuilderTestPivot; $pivot->setTestConnection($connection); @@ -65,15 +68,15 @@ public function testPivotUsesConnectionQueryMethod(): void public function testMorphPivotUsesConnectionQueryMethod(): void { - $mockConnection = m::mock(Connection::class); + $mockConnection = Double::for(Connection::class); $customBuilder = new CustomQueryBuilder( $mockConnection, new Grammar($mockConnection), new Processor ); - $connection = m::mock(Connection::class); - $connection->shouldReceive('query')->once()->andReturn($customBuilder); + $connection = Double::for(Connection::class); + $connection->expects('query')->returns($customBuilder); $morphPivot = new NewBaseQueryBuilderTestMorphPivot; $morphPivot->setTestConnection($connection); diff --git a/tests/Database/Eloquent/UseEloquentBuilderTest.php b/tests/Database/Eloquent/UseEloquentBuilderTest.php index 0307530513..53ec7f8d84 100644 --- a/tests/Database/Eloquent/UseEloquentBuilderTest.php +++ b/tests/Database/Eloquent/UseEloquentBuilderTest.php @@ -7,15 +7,19 @@ use Hypervel\Database\Eloquent\Attributes\UseEloquentBuilder; use Hypervel\Database\Eloquent\Builder; use Hypervel\Database\Eloquent\Model; +use Hypervel\Database\Query\Builder as QueryBuilder; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class UseEloquentBuilderTest extends TestCase { + use VerifiesDoubles; + public function testNewModelBuilderReturnsDefaultBuilderWhenNoAttribute(): void { $model = new UseEloquentBuilderTestModel; - $query = m::mock(\Hypervel\Database\Query\Builder::class); + $query = Double::for(QueryBuilder::class); $builder = $model->newEloquentBuilder($query); @@ -26,7 +30,7 @@ public function testNewModelBuilderReturnsDefaultBuilderWhenNoAttribute(): void public function testNewModelBuilderReturnsCustomBuilderWhenAttributePresent(): void { $model = new UseEloquentBuilderTestModelWithAttribute; - $query = m::mock(\Hypervel\Database\Query\Builder::class); + $query = Double::for(QueryBuilder::class); $builder = $model->newEloquentBuilder($query); @@ -37,7 +41,7 @@ public function testNewModelBuilderCachesResolvedBuilderClass(): void { $model1 = new UseEloquentBuilderTestModelWithAttribute; $model2 = new UseEloquentBuilderTestModelWithAttribute; - $query = m::mock(\Hypervel\Database\Query\Builder::class); + $query = Double::for(QueryBuilder::class); // First call should resolve and cache $builder1 = $model1->newEloquentBuilder($query); @@ -72,7 +76,7 @@ public function testDifferentModelsUseDifferentCaches(): void { $modelWithoutAttribute = new UseEloquentBuilderTestModel; $modelWithAttribute = new UseEloquentBuilderTestModelWithAttribute; - $query = m::mock(\Hypervel\Database\Query\Builder::class); + $query = Double::for(QueryBuilder::class); $builder1 = $modelWithoutAttribute->newEloquentBuilder($query); $builder2 = $modelWithAttribute->newEloquentBuilder($query); diff --git a/tests/Database/MigratorCoroutineIsolationTest.php b/tests/Database/MigratorCoroutineIsolationTest.php index 932a3d2be4..e70f4fe26a 100644 --- a/tests/Database/MigratorCoroutineIsolationTest.php +++ b/tests/Database/MigratorCoroutineIsolationTest.php @@ -13,7 +13,8 @@ use Hypervel\Database\Migrations\Migrator; use Hypervel\Filesystem\Filesystem; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; @@ -23,6 +24,8 @@ class MigratorCoroutineIsolationTest extends TestCase { + use VerifiesDoubles; + protected bool $runTestsInCoroutine = false; public function testConcurrentRunsKeepConnectionsOutputAndRestorationIsolated(): void @@ -160,7 +163,7 @@ public function testNonCoroutineStateIsPreservedAcrossIndependentCoroutineRuns() public function testReplacementMigratorDoesNotInheritReleasedInstanceState(): void { run(function (): void { - $resolver = m::mock(ConnectionResolverInterface::class); + $resolver = Double::for(ConnectionResolverInterface::class); $repository = new DatabaseMigrationRepository($resolver, 'migrations'); $files = new Filesystem; $output = new BufferedOutput; @@ -182,9 +185,9 @@ public function testReplacementMigratorDoesNotInheritReleasedInstanceState(): vo public function testReplacementRepositoryDoesNotInheritReleasedInstanceConnection(): void { run(function (): void { - $connection = m::mock(Connection::class); - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->expects('connection')->with(null)->andReturn($connection); + $connection = Double::for(Connection::class); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->expects('connection')->with(null)->returns($connection); $repository = new DatabaseMigrationRepository($resolver, 'migrations'); $repository->setSource('previous'); unset($repository); @@ -202,10 +205,10 @@ public function testReplacementRepositoryDoesNotInheritReleasedInstanceConnectio */ private function migrator(): array { - $resolver = m::mock(ConnectionResolverInterface::class); - $resolver->allows('connection')->andReturnUsing(static function (?string $name): Connection { - $connection = m::mock(Connection::class); - $connection->allows('getName')->andReturn($name ?? 'default'); + $resolver = Double::for(ConnectionResolverInterface::class); + $resolver->allows('connection')->resolves(static function (?string $name): Connection { + $connection = Double::for(Connection::class); + $connection->allows('getName')->returns($name ?? 'default'); return $connection; }); diff --git a/tests/Database/PoolManagerTest.php b/tests/Database/PoolManagerTest.php index 85461a42c2..b0540d8f00 100644 --- a/tests/Database/PoolManagerTest.php +++ b/tests/Database/PoolManagerTest.php @@ -17,7 +17,9 @@ use Hypervel\Database\Pool\DatabasePool; use Hypervel\Database\Pool\PoolManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionProperty; use RuntimeException; @@ -29,6 +31,8 @@ class PoolManagerTest extends TestCase { + use VerifiesDoubles; + public function testPoolReturnsSameInstance(): void { $container = $this->mockContainerWithPools(); @@ -438,19 +442,19 @@ public function testPurgeAllClearsCachedPools(): void public function testPurgeAllDetachesPoolsBeforeClosingThem(): void { - $container = m::mock(ContainerContract::class); - $original = m::mock(DatabasePool::class); - $replacement = m::mock(DatabasePool::class); - $original->shouldReceive('start')->once(); - $replacement->shouldReceive('start')->once(); - $replacement->shouldReceive('isClosed')->andReturnFalse(); - $container->shouldReceive('make') + $container = Double::for(ContainerContract::class, override: true); + $original = Double::for(DatabasePool::class); + $replacement = Double::for(DatabasePool::class); + $original->expects('start'); + $replacement->expects('start'); + $replacement->allows('isClosed')->returns(false); + $container->expects('make') ->with(DatabasePool::class, ['name' => 'default']) - ->twice() - ->andReturn($original, $replacement); - $poolManager = new PoolManager($container); + ->times(2) + ->returns($original, $replacement); + $poolManager = new PoolManager($container->instance()); $resolvedDuringClose = null; - $original->shouldReceive('close')->once()->andReturnUsing( + $original->expects('close')->resolves( function () use ($poolManager, &$resolvedDuringClose): void { $resolvedDuringClose = $poolManager->pool('default'); } @@ -468,22 +472,22 @@ public function testPurgeAllContinuesClosingAndPreservesFirstFailure(): void { $firstFailure = new RuntimeException('first close failed'); $secondFailure = new RuntimeException('second close failed'); - $firstPool = m::mock(DatabasePool::class); - $secondPool = m::mock(DatabasePool::class); - $thirdPool = m::mock(DatabasePool::class); - $firstPool->shouldReceive('start')->once(); - $secondPool->shouldReceive('start')->once(); - $thirdPool->shouldReceive('start')->once(); - $firstPool->shouldReceive('close')->once()->andThrow($firstFailure); - $secondPool->shouldReceive('close')->once()->andThrow($secondFailure); - $thirdPool->shouldReceive('close')->once(); - - $container = m::mock(ContainerContract::class); - $container->shouldReceive('make')->with(DatabasePool::class, ['name' => 'first'])->once()->andReturn($firstPool); - $container->shouldReceive('make')->with(DatabasePool::class, ['name' => 'second'])->once()->andReturn($secondPool); - $container->shouldReceive('make')->with(DatabasePool::class, ['name' => 'third'])->once()->andReturn($thirdPool); - - $poolManager = new PoolManager($container); + $firstPool = Double::for(DatabasePool::class); + $secondPool = Double::for(DatabasePool::class); + $thirdPool = Double::for(DatabasePool::class); + $firstPool->expects('start'); + $secondPool->expects('start'); + $thirdPool->expects('start'); + $firstPool->expects('close')->throws($firstFailure); + $secondPool->expects('close')->throws($secondFailure); + $thirdPool->expects('close'); + + $container = Double::for(ContainerContract::class, override: true); + $container->expects('make')->with(DatabasePool::class, ['name' => 'first'])->returns($firstPool); + $container->expects('make')->with(DatabasePool::class, ['name' => 'second'])->returns($secondPool); + $container->expects('make')->with(DatabasePool::class, ['name' => 'third'])->returns($thirdPool); + + $poolManager = new PoolManager($container->instance()); $poolManager->pool('first'); $poolManager->pool('second'); $poolManager->pool('third'); @@ -531,19 +535,19 @@ public function testPurgeOnlyRemovesNamedPool(): void public function testPurgeDetachesPoolBeforeClosingIt(): void { - $container = m::mock(ContainerContract::class); - $original = m::mock(DatabasePool::class); - $replacement = m::mock(DatabasePool::class); - $original->shouldReceive('start')->once(); - $replacement->shouldReceive('start')->once(); - $replacement->shouldReceive('isClosed')->andReturnFalse(); - $container->shouldReceive('make') + $container = Double::for(ContainerContract::class, override: true); + $original = Double::for(DatabasePool::class); + $replacement = Double::for(DatabasePool::class); + $original->expects('start'); + $replacement->expects('start'); + $replacement->allows('isClosed')->returns(false); + $container->expects('make') ->with(DatabasePool::class, ['name' => 'default']) - ->twice() - ->andReturn($original, $replacement); - $poolManager = new PoolManager($container); + ->times(2) + ->returns($original, $replacement); + $poolManager = new PoolManager($container->instance()); $resolvedDuringClose = null; - $original->shouldReceive('close')->once()->andReturnUsing( + $original->expects('close')->resolves( function () use ($poolManager, &$resolvedDuringClose): void { $resolvedDuringClose = $poolManager->pool('default'); } @@ -729,21 +733,21 @@ public function testPurgeForConnectionDetachesSelectionAndPrioritizesCancellatio { $ordinaryFailure = new RuntimeException('write pool close failed'); $cancellation = new CanceledException; - $writePool = m::mock(DatabasePool::class); - $readPool = m::mock(DatabasePool::class); - $cachePool = m::mock(DatabasePool::class); - $poolManager = new PoolManager(m::mock(ContainerContract::class)); + $writePool = Double::for(DatabasePool::class); + $readPool = Double::for(DatabasePool::class); + $cachePool = Double::for(DatabasePool::class); + $poolManager = new PoolManager(Double::for(ContainerContract::class, override: true)->instance()); $detachedPools = null; - $writePool->shouldReceive('close')->once()->andReturnUsing( + $writePool->expects('close')->resolves( function () use ($poolManager, &$detachedPools, $ordinaryFailure): never { $detachedPools = $poolManager->getPools(); throw $ordinaryFailure; } ); - $readPool->shouldReceive('close')->once()->andThrow($cancellation); - $cachePool->shouldNotReceive('close'); + $readPool->expects('close')->throws($cancellation); + $cachePool->expects('close')->never(); $pools = new ReflectionProperty($poolManager, 'pools'); $pools->setValue($poolManager, [ @@ -781,7 +785,7 @@ private function publicationContainer(array &$candidates, array $poolOptions = [ return $container; } - private function mockContainerWithPools(?array $connections = null): m\MockInterface|ContainerContract + private function mockContainerWithPools(?array $connections = null): ContainerContract { $connections ??= [ 'default' => $this->connectionConfig(), @@ -794,18 +798,18 @@ private function mockContainerWithPools(?array $connections = null): m\MockInter ], ]); - $container = m::mock(ContainerContract::class); - $factory = new ConnectionFactory($container); + $container = Double::for(ContainerContract::class, override: true); + $factory = new ConnectionFactory($container->instance()); - $container->shouldReceive('make')->with('config')->andReturn($config); - $container->shouldReceive('make')->with('db.factory')->andReturn($factory); - $container->shouldReceive('has')->with(StdoutLoggerInterface::class)->andReturn(false); - $container->shouldReceive('bound')->with('events')->andReturn(false); - $container->shouldReceive('make')->with(DatabasePool::class, m::any())->andReturnUsing( - fn ($class, $arguments) => new PoolManagerTestPool($container, $arguments['name']) + $container->allows('make')->with('config')->returns($config); + $container->allows('make')->with('db.factory')->returns($factory); + $container->allows('has')->with(StdoutLoggerInterface::class)->returns(false); + $container->allows('bound')->with('events')->returns(false); + $container->allows('make')->with(DatabasePool::class, Argument::any())->resolves( + fn ($class, $arguments) => new PoolManagerTestPool($container->instance(), $arguments['name']) ); - return $container; + return $container->instance(); } private function connectionConfig(array $overrides = []): array diff --git a/tests/Database/Query/QueryTestCase.php b/tests/Database/Query/QueryTestCase.php deleted file mode 100644 index e390535407..0000000000 --- a/tests/Database/Query/QueryTestCase.php +++ /dev/null @@ -1,72 +0,0 @@ -getMySqlBuilder(); - } - - protected function getMySqlBuilder(): Builder - { - return new Builder( - $this->getMockConnection(), - new MySqlGrammar, - m::mock(Processor::class) - ); - } - - protected function getPostgresBuilder(): Builder - { - return new Builder( - $this->getMockConnection(), - new PostgresGrammar, - m::mock(Processor::class) - ); - } - - protected function getSQLiteBuilder(): Builder - { - return new Builder( - $this->getMockConnection(), - new SQLiteGrammar, - m::mock(Processor::class) - ); - } - - protected function getMockConnection(): ConnectionInterface - { - $connection = m::mock(ConnectionInterface::class); - $connection->shouldReceive('getDatabaseName')->andReturn('database'); - $connection->shouldReceive('getTablePrefix')->andReturn(''); - $connection->shouldReceive('raw')->andReturnUsing( - fn ($value) => new Expression($value) - ); - - return $connection; - } -} diff --git a/tests/Database/SimpleConnectionResolverIsolationTest.php b/tests/Database/SimpleConnectionResolverIsolationTest.php index 22a521b1a8..611f83c10a 100644 --- a/tests/Database/SimpleConnectionResolverIsolationTest.php +++ b/tests/Database/SimpleConnectionResolverIsolationTest.php @@ -9,7 +9,8 @@ use Hypervel\Database\DatabaseManager; use Hypervel\Database\SimpleConnectionResolver; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; /** * Regression guard: SimpleConnectionResolver must keep its default connection @@ -26,17 +27,12 @@ */ class SimpleConnectionResolverIsolationTest extends TestCase { - protected function tearDown(): void - { - CoroutineContext::forget(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY); - - parent::tearDown(); - } + use VerifiesDoubles; public function testTwoInstancesHaveIndependentDefaults(): void { - $resolverA = new SimpleConnectionResolver(m::mock(DatabaseManager::class)); - $resolverB = new SimpleConnectionResolver(m::mock(DatabaseManager::class)); + $resolverA = new SimpleConnectionResolver(Double::for(DatabaseManager::class)); + $resolverB = new SimpleConnectionResolver(Double::for(DatabaseManager::class)); $resolverA->setDefaultConnection('alpha'); $resolverB->setDefaultConnection('beta'); @@ -47,7 +43,7 @@ public function testTwoInstancesHaveIndependentDefaults(): void public function testSetDefaultConnectionDoesNotWriteToSharedContext(): void { - $resolver = new SimpleConnectionResolver(m::mock(DatabaseManager::class)); + $resolver = new SimpleConnectionResolver(Double::for(DatabaseManager::class)); // Pre-set Context to a sentinel — SimpleConnectionResolver must NOT // touch this key, otherwise its setter is leaking into the pooled diff --git a/tests/Di/Bootstrap/GenerateProxiesTest.php b/tests/Di/Bootstrap/GenerateProxiesTest.php index 717b62408e..5135290a03 100644 --- a/tests/Di/Bootstrap/GenerateProxiesTest.php +++ b/tests/Di/Bootstrap/GenerateProxiesTest.php @@ -20,7 +20,8 @@ use Hypervel\Support\Composer; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PhpParser\NodeVisitorAbstract; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionMethod; @@ -29,6 +30,8 @@ class GenerateProxiesTest extends TestCase { + use VerifiesDoubles; + private ClassLoader $originalLoader; private ClassLoader $loader; @@ -73,18 +76,18 @@ protected function tearDown(): void public function testBootstrapClosesRegistration(string $aspects): void { $this->withProxyFixture(function (string $className, string $sourceFile, string $overrideFile, string $proxyDir) use ($aspects): void { - $app = m::mock(ApplicationContract::class); + $app = Double::for(ApplicationContract::class, override: true); if ($aspects === 'none') { - $app->shouldNotReceive('bootstrapPath'); + $app->expects('bootstrapPath')->never(); } else { AspectCollector::setAround(OverrideSourceAspect::class, [ $aspects === 'matching' ? $className . '::value' : 'Missing\Target', ]); - $app->shouldReceive('bootstrapPath')->with('cache/aop')->andReturn($proxyDir); + $app->allows('bootstrapPath')->with('cache/aop')->returns($proxyDir); } - (new IsolatedProxyGenerator)->bootstrap($app); + (new IsolatedProxyGenerator)->bootstrap($app->instance()); $this->assertSame($aspects !== 'none', AstVisitorRegistry::exists(ProxyCallVisitor::class)); if ($aspects === 'matching') { diff --git a/tests/Di/ServiceProviderDiTest.php b/tests/Di/ServiceProviderDiTest.php index 3283505414..e13dfa3a43 100644 --- a/tests/Di/ServiceProviderDiTest.php +++ b/tests/Di/ServiceProviderDiTest.php @@ -11,10 +11,13 @@ use Hypervel\Tests\Di\Fixtures\Aspect\NoPriorityAspect; use Hypervel\Tests\Di\Fixtures\Aspect\TestAspect; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ServiceProviderDiTest extends TestCase { + use VerifiesDoubles; + public function testAspectsRegistersIntoCollector(): void { $provider = new TestServiceProvider($this->createMockApp()); @@ -61,7 +64,7 @@ public function testClassMapDelegatesToClassMapManager(): void */ protected function createMockApp(): ApplicationContract { - return m::mock(ApplicationContract::class); + return Double::for(ApplicationContract::class, override: true)->instance(); } } diff --git a/tests/Doctor/Feature/Diagnostics/CacheStoreIsReachableTest.php b/tests/Doctor/Feature/Diagnostics/CacheStoreIsReachableTest.php index a78724d34a..fc7af05ad4 100644 --- a/tests/Doctor/Feature/Diagnostics/CacheStoreIsReachableTest.php +++ b/tests/Doctor/Feature/Diagnostics/CacheStoreIsReachableTest.php @@ -19,7 +19,8 @@ use Hypervel\Support\Facades\Schema; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Doctor\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -27,6 +28,8 @@ class CacheStoreIsReachableTest extends TestCase { + use VerifiesDoubles; + private string $directory; private ?string $originalEnvironmentFile; @@ -367,9 +370,9 @@ public function testCleanupPreservesPrimaryFailuresAndCancellation(bool $primary $cleanupCanceled => new CanceledException('cleanup canceled'), default => new RuntimeException('cleanup failed'), }; - $store = m::mock(Store::class); - $store->expects('put')->andThrow($primary); - $store->expects('forget')->andThrow($cleanup); + $store = Double::for(Store::class); + $store->expects('put')->throws($primary); + $store->expects('forget')->throws($cleanup); Cache::extend('probe', fn (): Repository => new Repository($store)); config(['cache.default' => 'probe', 'cache.stores.probe' => ['driver' => 'probe']]); $caught = null; diff --git a/tests/Doctor/Feature/Diagnostics/DatabaseConnectionIsReachableTest.php b/tests/Doctor/Feature/Diagnostics/DatabaseConnectionIsReachableTest.php index 66b578a7e2..1700b37a7e 100644 --- a/tests/Doctor/Feature/Diagnostics/DatabaseConnectionIsReachableTest.php +++ b/tests/Doctor/Feature/Diagnostics/DatabaseConnectionIsReachableTest.php @@ -10,7 +10,8 @@ use Hypervel\Doctor\Results\Link; use Hypervel\Support\Facades\DB; use Hypervel\Tests\Doctor\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; @@ -18,6 +19,8 @@ class DatabaseConnectionIsReachableTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('databaseConfigurations')] public function testChecksTheDefaultDatabaseConnection(array $configuration): void { @@ -143,13 +146,13 @@ public function testCustomDriverNeutralConnectionsAreProbedAndDisconnected(bool 'database.default' => 'analytics', 'database.connections.analytics' => ['driver' => 'custom', 'options' => 'transport-owned'], ]); - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); $version = $connection->expects('getServerVersion'); if ($fails) { - $version->andThrow(new RuntimeException('Custom transport unavailable.')); + $version->throws(new RuntimeException('Custom transport unavailable.')); } else { - $version->andReturn('1.0'); + $version->returns('1.0'); } $connection->expects('disconnect'); @@ -265,9 +268,9 @@ public function testReadRecordExtensionsFollowTheRequestedConnectionRole(string 'read' => ['driver' => 'replica', 'options' => 'transport-owned'], ], ]); - $custom = m::mock(Connection::class); + $custom = Double::for(Connection::class); if ($suffix === '::read') { - $custom->expects('getServerVersion')->andReturn('1.0'); + $custom->expects('getServerVersion')->returns('1.0'); $custom->expects('disconnect'); } DB::extend('replica', function (array $configuration) use ($custom, $suffix): Connection { diff --git a/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php b/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php index 66c923dce0..04e882bb6e 100644 --- a/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php +++ b/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php @@ -16,13 +16,16 @@ use Hypervel\Support\Facades\File; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Doctor\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; class MigrationsAreUpToDateTest extends TestCase { + use VerifiesDoubles; + /** * Configure separate application and migration connections. */ @@ -150,20 +153,20 @@ public function up(): void #[DataProvider('migrationFailures')] public function testReportsWhenPendingMigrationsCannotBeApplied(?string $exceptionClass): void { - $kernel = m::mock(Kernel::class); + $kernel = Double::for(Kernel::class); Artisan::swap($kernel); - $command = $kernel->shouldReceive('call')->once()->with('migrate', ['--no-interaction' => true]); + $command = $kernel->expects('call')->with('migrate', ['--no-interaction' => true]); if ($exceptionClass !== null) { $exception = new $exceptionClass('Database connection refused.'); - $command->andThrow($exception); + $command->throws($exception); if ($exception instanceof CanceledException) { $this->expectExceptionObject($exception); } } else { - $command->andReturn(1); - $kernel->shouldReceive('output')->once()->andReturn('Database connection refused.'); + $command->returns(1); + $kernel->expects('output')->returns('Database connection refused.'); } $fix = (new MigrationsAreUpToDate)->fix(DiagnosticResult::fail('pending')); diff --git a/tests/Doctor/Feature/Diagnostics/PublicStorageLinkExistsTest.php b/tests/Doctor/Feature/Diagnostics/PublicStorageLinkExistsTest.php index 0f39cf8f8a..08b349d70d 100644 --- a/tests/Doctor/Feature/Diagnostics/PublicStorageLinkExistsTest.php +++ b/tests/Doctor/Feature/Diagnostics/PublicStorageLinkExistsTest.php @@ -12,13 +12,16 @@ use Hypervel\Support\Facades\File; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Doctor\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Swoole\Coroutine\CanceledException; class PublicStorageLinkExistsTest extends TestCase { + use VerifiesDoubles; + private string $basePath; /** @@ -159,8 +162,8 @@ public function testPreservesConflictingPathsAndDoesNotOfferAMixedRepair(string 'filesystems.disks.public' => ['driver' => 'local', 'root' => $root], 'filesystems.links' => [$link => $root, $this->basePath . '/missing' => $root], ]); - $kernel = m::mock(Kernel::class); - $kernel->shouldNotReceive('call'); + $kernel = Double::for(Kernel::class); + $kernel->expects('call')->never(); Artisan::swap($kernel); $diagnostic = new PublicStorageLinkExists; $result = $diagnostic->check(); @@ -198,20 +201,20 @@ public function testReportsWhenTheCommandDoesNotRepairTheLink(int $exitCode, ?st 'filesystems.disks.public' => ['driver' => 'local', 'root' => $root], 'filesystems.links' => [$this->basePath . '/uploads' => $root], ]); - $kernel = m::mock(Kernel::class); + $kernel = Double::for(Kernel::class); Artisan::swap($kernel); - $command = $kernel->shouldReceive('call')->once()->with('storage:link'); + $command = $kernel->expects('call')->with('storage:link'); if ($exceptionClass !== null) { $exception = new $exceptionClass('The link could not be created.'); - $command->andThrow($exception); + $command->throws($exception); if ($exception instanceof CanceledException) { $this->expectExceptionObject($exception); } } else { - $command->andReturn($exitCode); - $kernel->shouldReceive('output')->once()->andReturn('The link could not be created.'); + $command->returns($exitCode); + $kernel->expects('output')->returns('The link could not be created.'); } $diagnostic = new PublicStorageLinkExists; diff --git a/tests/Doctor/Feature/Diagnostics/QueueConnectionIsReachableTest.php b/tests/Doctor/Feature/Diagnostics/QueueConnectionIsReachableTest.php index f37067931b..441634ca76 100644 --- a/tests/Doctor/Feature/Diagnostics/QueueConnectionIsReachableTest.php +++ b/tests/Doctor/Feature/Diagnostics/QueueConnectionIsReachableTest.php @@ -12,12 +12,16 @@ use Hypervel\Support\Facades\Schema; use Hypervel\Tests\Doctor\TestCase; use Hypervel\Tests\Queue\Fixtures\IntegerQueueName; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; class QueueConnectionIsReachableTest extends TestCase { + use VerifiesDoubles; + /** * Use an isolated in-memory database for schema probes. */ @@ -115,13 +119,13 @@ public function testBuiltInNullConnectionNeedsNoConfigurationRecord(): void public function testRemoteQueuesMustCompleteAReadOnlyOperation(string $driver, bool $fails): void { config(['queue.default' => 'remote', 'queue.connections.remote' => ['driver' => $driver]]); - $queue = m::mock(QueueContract::class); - $probe = $queue->shouldReceive('size')->once()->withNoArgs(); + $queue = Double::for(QueueContract::class); + $probe = $queue->expects('size')->with(Argument::none()); if ($fails) { - $probe->andThrow(new RuntimeException('Queue service is unreachable.')); + $probe->throws(new RuntimeException('Queue service is unreachable.')); } else { - $probe->andReturn(0); + $probe->returns(0); } Queue::shouldReceive('connection')->with('remote')->andReturn($queue); diff --git a/tests/Doctor/Feature/Diagnostics/RecommendedPhpExtensionsAreLoadedTest.php b/tests/Doctor/Feature/Diagnostics/RecommendedPhpExtensionsAreLoadedTest.php index c14087819c..4ed0dbf104 100644 --- a/tests/Doctor/Feature/Diagnostics/RecommendedPhpExtensionsAreLoadedTest.php +++ b/tests/Doctor/Feature/Diagnostics/RecommendedPhpExtensionsAreLoadedTest.php @@ -9,16 +9,19 @@ use Hypervel\Support\Facades\File; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Doctor\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RequiresPhpExtension; class RecommendedPhpExtensionsAreLoadedTest extends TestCase { + use VerifiesDoubles; + #[RequiresPhpExtension('Zend OPcache')] public function testRecognizesComposerNormalizedExtensionNames(): void { - $composer = m::mock(ComposerJson::class); - $composer->shouldReceive('suggestedExtensions')->andReturn(['zend-opcache']); + $composer = Double::for(ComposerJson::class); + $composer->allows('suggestedExtensions')->returns(['zend-opcache']); $result = (new RecommendedPhpExtensionsAreLoaded($composer))->check(); diff --git a/tests/Doctor/Feature/Diagnostics/SessionDriverIsReachableTest.php b/tests/Doctor/Feature/Diagnostics/SessionDriverIsReachableTest.php index 9d20f330b3..e8e6879f69 100644 --- a/tests/Doctor/Feature/Diagnostics/SessionDriverIsReachableTest.php +++ b/tests/Doctor/Feature/Diagnostics/SessionDriverIsReachableTest.php @@ -12,11 +12,14 @@ use Hypervel\Support\Facades\Schema; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Doctor\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class SessionDriverIsReachableTest extends TestCase { + use VerifiesDoubles; + private string $path; /** @@ -119,8 +122,8 @@ public static function redisConnections(): array public function testDatabaseSessionsKeepTheDefaultSchemaConnection(): void { config(['session.driver' => 'database', 'session.connection' => null, 'session.table' => 'custom_sessions']); - $schema = m::mock(Builder::class); - $schema->expects('hasTable')->with('custom_sessions')->andReturnTrue(); + $schema = Double::for(Builder::class); + $schema->expects('hasTable')->with('custom_sessions')->returns(true); Schema::shouldReceive('connection')->with(null)->andReturn($schema); $this->assertSame('pass', (new SessionDriverIsReachable)->check()->status->value); diff --git a/tests/Doctor/Feature/Support/InstalledPackagesTest.php b/tests/Doctor/Feature/Support/InstalledPackagesTest.php index 4dd0f0bfdd..33116bd338 100644 --- a/tests/Doctor/Feature/Support/InstalledPackagesTest.php +++ b/tests/Doctor/Feature/Support/InstalledPackagesTest.php @@ -9,11 +9,14 @@ use Hypervel\Support\Facades\File; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Doctor\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class InstalledPackagesTest extends TestCase { + use VerifiesDoubles; + private string $path; private InstalledPackages $packages; @@ -128,8 +131,8 @@ public function testDoesNotInventAnUnknownRootSelfVersion(): void */ private function snapshot(array $root): array { - $composer = m::mock(ComposerJson::class); - $composer->allows('contents')->andReturn($root); + $composer = Double::for(ComposerJson::class); + $composer->allows('contents')->returns($root); return $this->packages->platformRequirements($composer); } diff --git a/tests/Encryption/CryptFacadeTest.php b/tests/Encryption/CryptFacadeTest.php index 1e5b7e1913..7b1277b153 100644 --- a/tests/Encryption/CryptFacadeTest.php +++ b/tests/Encryption/CryptFacadeTest.php @@ -7,11 +7,14 @@ use Hypervel\Container\Container; use Hypervel\Support\Facades\Crypt; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class CryptFacadeTest extends TestCase { + use VerifiesDoubles; + protected function setUp(): void { parent::setUp(); @@ -22,11 +25,10 @@ protected function setUp(): void public function testDynamicCallsForwardTheirMethodArgumentsAndReturnValue(): void { - $root = m::mock(); - $root->shouldReceive('probe') - ->once() + $root = Double::for(CryptFacadeRoot::class); + $root->expects('probe') ->with('value', 42) - ->andReturn('result'); + ->returns('result'); $app = new Container; $app->instance('encrypter', $root); @@ -44,3 +46,11 @@ public function testDynamicCallsWithoutAFacadeRootThrowTheBaseException(): void Crypt::probe(); } } + +abstract class CryptFacadeRoot +{ + /** + * Expose a custom method for facade forwarding. + */ + abstract public function probe(string $value, int $number): string; +} diff --git a/tests/Engine/SocketTest.php b/tests/Engine/SocketTest.php index 1d2d11f42e..07eef53ffe 100644 --- a/tests/Engine/SocketTest.php +++ b/tests/Engine/SocketTest.php @@ -13,7 +13,8 @@ use Hypervel\Engine\SafeSocket; use Hypervel\Engine\Socket; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use Psr\Log\LoggerInterface; use ReflectionProperty; @@ -29,6 +30,8 @@ class SocketTest extends TestCase { + use VerifiesDoubles; + public function testSocketConnectFailed(): void { try { @@ -371,13 +374,13 @@ public function testSafeSocketClosesAndReportsWhenItsLoggerFails(): void { $sendFailure = new RuntimeException('Send failed.'); $loggingFailure = new RuntimeException('Logging failed.'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($loggingFailure); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($loggingFailure); $container = new Container; $container->instance(ExceptionHandler::class, $handler); Container::setInstance($container); - $logger = m::mock(LoggerInterface::class); - $logger->shouldReceive('critical')->once()->with((string) $sendFailure)->andThrow($loggingFailure); + $logger = Double::for(LoggerInterface::class); + $logger->expects('critical')->with((string) $sendFailure)->throws($loggingFailure); $nativeSocket = new FailingSendSocket($sendFailure); $socket = new SafeSocket($nativeSocket, logger: $logger); /** @var Channel $channel */ diff --git a/tests/Filesystem/AwsS3V3AdapterTest.php b/tests/Filesystem/AwsS3V3AdapterTest.php index 3180c9c1b8..6ad14b2bea 100644 --- a/tests/Filesystem/AwsS3V3AdapterTest.php +++ b/tests/Filesystem/AwsS3V3AdapterTest.php @@ -25,10 +25,11 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\Flysystem\FilesystemAdapter as FlysystemAdapter; use League\Flysystem\FilesystemOperator; use League\Flysystem\UnableToReadFile; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use Psr\Http\Message\StreamInterface; @@ -40,6 +41,8 @@ class AwsS3V3AdapterTest extends TestCase { + use VerifiesDoubles; + public function testConfiguredAndNativeUrlsEncodeRawPathsIdentically(): void { $path = 'nested/report%2F v?x#y+z.txt'; @@ -329,10 +332,10 @@ function (CommandInterface $request) use (&$command): Result { 'report' => true, 'options' => ['@http' => ['timeout' => 12]], ]); - $adapter->getDriver()->shouldReceive('fileExists')->andReturn(true); - $emptyDriver = m::mock(FilesystemOperator::class); - $emptyDriver->shouldReceive('fileExists')->andReturn(false); - $empty = new FilesystemAdapter($emptyDriver, m::mock(FlysystemAdapter::class)); + $adapter->getDriver()->allows('fileExists')->returns(true); + $emptyDriver = Double::for(FilesystemOperator::class); + $emptyDriver->allows('fileExists')->returns(false); + $empty = new FilesystemAdapter($emptyDriver, Double::for(FlysystemAdapter::class)); $pools = new PoolManager; $definition = new PoolDefinition('filesystem:read-through-range', 's3', 'test', PoolOptions::fromArray([])); $cloud = match ($poolType) { @@ -351,8 +354,8 @@ function (CommandInterface $request) use (&$command): Result { ), null => $adapter, }; - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler = Double::for(ExceptionHandler::class); + $exceptionHandler->expects('report')->never(); Container::getInstance()->instance(ExceptionHandler::class, $exceptionHandler); $manager = new FilesystemManager(Container::getInstance()); $manager->set('primary', $primary ? $cloud : $empty); @@ -432,8 +435,8 @@ public function testReadStreamRangePreservesCancellationWithoutReporting(bool $w { $cancellation = new CanceledException('read canceled'); $failure = $wrapped ? new S3Exception('SDK request canceled.', new Command('GetObject'), previous: $cancellation) : $cancellation; - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler = Double::for(ExceptionHandler::class); + $exceptionHandler->expects('report')->never(); Container::getInstance()->bind(ExceptionHandler::class, static fn () => $exceptionHandler); $handler = new MockHandler([$failure]); $adapter = $this->adapter($handler, [ @@ -456,8 +459,9 @@ public function testReadStreamRangePreservesCancellationWithoutReporting(bool $w public function testReadStreamRangeRejectsAResultWithoutAResource(): void { - $body = m::mock(StreamInterface::class); - $body->shouldReceive('isReadable', 'isWritable')->andReturnFalse(); + $body = Double::for(StreamInterface::class); + $body->allows('isReadable')->returns(false); + $body->allows('isWritable')->returns(false); $handler = new MockHandler([new Result(['Body' => $body])]); $adapter = $this->adapter($handler, ['bucket' => 'bucket', 'throw' => true]); @@ -529,8 +533,8 @@ private function adapter(MockHandler $handler, array $config): AwsS3V3Adapter ]); return new AwsS3V3Adapter( - m::mock(FilesystemOperator::class), - m::mock(FlysystemAdapter::class), + Double::for(FilesystemOperator::class), + Double::for(FlysystemAdapter::class), $config, $client, ); diff --git a/tests/Filesystem/ClientPooledFilesystemTest.php b/tests/Filesystem/ClientPooledFilesystemTest.php index 9d3b3ac3d0..355740bef8 100644 --- a/tests/Filesystem/ClientPooledFilesystemTest.php +++ b/tests/Filesystem/ClientPooledFilesystemTest.php @@ -30,10 +30,12 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use League\Flysystem\Filesystem; use League\Flysystem\FilesystemOperator; use League\Flysystem\Local\LocalFilesystemAdapter; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -43,6 +45,8 @@ class ClientPooledFilesystemTest extends TestCase { + use VerifiesDoubles; + private string $tempDir; private Filesystem $driver; @@ -138,15 +142,15 @@ static function (object $client) use ($root): FilesystemAdapter { $this->assertFalse($source->exists('file.txt')); $source->put('file.txt', 'retained'); - $failedDestination = m::mock(FilesystemContract::class); + $failedDestination = Double::for(FilesystemContract::class); $stream = null; - $failedDestination->shouldReceive('writeStream')->once()->with('file.txt', m::on(function (mixed $resource) use (&$stream): bool { + $failedDestination->expects('writeStream')->with('file.txt', Argument::satisfies(is_resource(...)))->resolves(function (string $path, mixed $resource) use (&$stream): bool { $stream = $resource; $this->assertSame(0, $this->pools->get('filesystem:transfer')->getBorrowedCount()); $this->assertSame('retained', stream_get_contents($resource)); - return true; - }))->andReturnFalse(); + return false; + }); $this->assertFalse($source->moveToDisk($failedDestination, 'file.txt')); $this->assertSame('retained', $source->get('file.txt')); @@ -447,8 +451,8 @@ public function testBufferedReadStreamReleasesTheClientBeforeConsumption(): void fwrite($buffer, 'buffered contents'); rewind($buffer); - $stack = m::mock(FilesystemAdapter::class); - $stack->shouldReceive('readStream')->once()->with('file.txt')->andReturn($buffer); + $stack = Double::for(FilesystemAdapter::class); + $stack->expects('readStream')->with('file.txt')->returns($buffer); $disk = $this->disk( $clientCreations, $stackCreations, @@ -473,8 +477,8 @@ public function testNonResourceReadStreamResultReleasesImmediately(): void { $clientCreations = 0; $stackCreations = 0; - $stack = m::mock(FilesystemAdapter::class); - $stack->shouldReceive('readStream')->once()->with('missing.txt')->andReturnNull(); + $stack = Double::for(FilesystemAdapter::class); + $stack->expects('readStream')->with('missing.txt')->returns(null); $disk = $this->disk( $clientCreations, $stackCreations, @@ -513,15 +517,15 @@ public function testDiscardFailureDoesNotMaskAStackFactoryFailure(): void $client = new ClientPooledFilesystemClient; $stackFailure = new RuntimeException('stack failed'); $discardFailure = new RuntimeException('discard failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($discardFailure); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($discardFailure); $container->instance(ExceptionHandler::class, $handler); - $pool = m::mock(ObjectPoolContract::class); - $pool->shouldReceive('borrow')->once()->andReturn($client); - $pool->shouldReceive('discard')->once()->with($client)->andThrow($discardFailure); - $factory = m::mock(Factory::class); - $factory->shouldReceive('getOrCreate')->once()->andReturn($pool); + $pool = Double::for(ObjectPoolContract::class); + $pool->expects('borrow')->returns($client); + $pool->expects('discard')->with($client)->throws($discardFailure); + $factory = Double::for(Factory::class); + $factory->expects('getOrCreate')->returns($pool); $disk = new ClientPooledFilesystem( $this->definition(), static fn (): object => $client, @@ -607,13 +611,13 @@ public function testOperationExceptionStaysPrimaryWhenReleaseCallbackAlsoThrows( $container = Container::getInstance(); $operationFailure = new RuntimeException('operation failed'); $releaseFailure = new RuntimeException('release failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($releaseFailure); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($releaseFailure); $container->instance(ExceptionHandler::class, $handler); $clientCreations = 0; $stackCreations = 0; - $stack = m::mock(FilesystemAdapter::class); - $stack->shouldReceive('get')->once()->with('file.txt')->andThrow($operationFailure); + $stack = Double::for(FilesystemAdapter::class); + $stack->expects('get')->with('file.txt')->throws($operationFailure); $disk = $this->disk( $clientCreations, $stackCreations, @@ -639,8 +643,8 @@ public function testReleaseCancellationSupersedesAnOperationFailure(): void $releaseCancellation = new CanceledException('release canceled'); $clientCreations = 0; $stackCreations = 0; - $stack = m::mock(FilesystemAdapter::class); - $stack->shouldReceive('get')->once()->with('file.txt')->andThrow($operationFailure); + $stack = Double::for(FilesystemAdapter::class); + $stack->expects('get')->with('file.txt')->throws($operationFailure); $disk = $this->disk( $clientCreations, $stackCreations, diff --git a/tests/Filesystem/FileResponseBuilderTest.php b/tests/Filesystem/FileResponseBuilderTest.php index b932812d2a..3845244e57 100644 --- a/tests/Filesystem/FileResponseBuilderTest.php +++ b/tests/Filesystem/FileResponseBuilderTest.php @@ -15,8 +15,9 @@ use Hypervel\ObjectPool\Lease; use Hypervel\ObjectPool\PoolOptions; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\Flysystem\UnableToReadFile; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use stdClass; @@ -25,6 +26,8 @@ class FileResponseBuilderTest extends TestCase { + use VerifiesDoubles; + public function testBuildsDefaultHeadersAndStreamsFullContentLazily(): void { $sizeCalls = 0; @@ -417,8 +420,8 @@ public function testWriterFailureStaysPrimaryWhenClosingAlsoFails(): void Container::setInstance($container); $writerFailure = new RuntimeException('writer failed'); $closeFailure = new RuntimeException('close failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($closeFailure); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($closeFailure); $container->instance(ExceptionHandler::class, $handler); $state = new FileResponseBuilderStreamState('contents', closeFailure: $closeFailure); $response = $this->build( diff --git a/tests/Filesystem/FilesystemManagerTest.php b/tests/Filesystem/FilesystemManagerTest.php index 7cc412a918..90f4f481ca 100644 --- a/tests/Filesystem/FilesystemManagerTest.php +++ b/tests/Filesystem/FilesystemManagerTest.php @@ -23,6 +23,7 @@ use Hypervel\Contracts\Debug\ExceptionHandler; use Hypervel\Contracts\Filesystem\Filesystem; use Hypervel\Contracts\ObjectPool\Factory as PoolFactory; +use Hypervel\Contracts\Routing\UrlGenerator; use Hypervel\Filesystem\AwsS3V3Adapter; use Hypervel\Filesystem\ClientPooledFilesystem; use Hypervel\Filesystem\FilesystemAdapter; @@ -37,6 +38,9 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use League\Flysystem\AwsS3V3\AwsS3V3Adapter as FlysystemS3Adapter; use League\Flysystem\Filesystem as Flysystem; use League\Flysystem\FilesystemOperator; @@ -46,7 +50,6 @@ use League\Flysystem\ReadOnly\ReadOnlyFilesystemAdapter; use League\Flysystem\UnableToReadFile; use League\Flysystem\UnableToWriteFile; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\RequiresOperatingSystem; use PHPUnit\Framework\Attributes\TestWith; @@ -78,6 +81,8 @@ enum FilesystemTestUnitDisk class FilesystemManagerTest extends TestCase { + use VerifiesDoubles; + private string $tempDir; /** @var list */ @@ -327,7 +332,7 @@ public function testCanBuildOnDemandDisk(): void public function testCanSetDiskUsingEnum(): void { $filesystem = new FilesystemManager($this->getContainer()); - $filesystem->set(FilesystemManagerTestDisk::Local, $disk = m::mock(Filesystem::class)); + $filesystem->set(FilesystemManagerTestDisk::Local, $disk = Double::for(Filesystem::class)); $this->assertSame($disk, $filesystem->disk('local')); } @@ -335,8 +340,8 @@ public function testCanSetDiskUsingEnum(): void public function testCanForgetDiskUsingEnum(): void { $filesystem = $this->filesystemManagerWithLocalDisks(); - $filesystem->set('local', $local = m::mock(Filesystem::class)); - $filesystem->set('backup', $backup = m::mock(Filesystem::class)); + $filesystem->set('local', $local = Double::for(Filesystem::class)); + $filesystem->set('backup', $backup = Double::for(Filesystem::class)); $filesystem->forgetDisk(FilesystemManagerTestDisk::Local); @@ -355,7 +360,7 @@ public function testCanForgetDiskUsingEnum(): void public function testCanPurgeDiskUsingEnum(UnitEnum $name, string $key): void { $filesystem = $this->filesystemManagerWithLocalDisks(); - $filesystem->set($key, $local = m::mock(Filesystem::class)); + $filesystem->set($key, $local = Double::for(Filesystem::class)); $filesystem->purge($name); @@ -508,15 +513,13 @@ public function testScopedLocalDiskUsesItsNearestServedRouteForSignedUrls(): voi ], ]); $expiration = new DateTimeImmutable('+5 minutes'); - $url = m::mock(); - $url->shouldReceive('temporarySignedRoute') - ->once() + $url = Double::for(UrlGenerator::class); + $url->expects('temporarySignedRoute') ->with('storage.local', $expiration, ['path' => 'tenant/file.txt'], false) - ->andReturn('/signed/file.txt'); - $url->shouldReceive('to') - ->once() + ->returns('/signed/file.txt'); + $url->expects('to') ->with('/signed/file.txt') - ->andReturn('https://example.test/signed/file.txt'); + ->returns('https://example.test/signed/file.txt'); $container->instance('url', $url); $filesystem = new FilesystemManager($container); @@ -550,15 +553,13 @@ public function testNestedScopedLocalDiskUsesOriginalRoutePrefixes(): void ], ]); $expiration = new DateTimeImmutable('+5 minutes'); - $url = m::mock(); - $url->shouldReceive('temporarySignedRoute') - ->once() + $url = Double::for(UrlGenerator::class); + $url->expects('temporarySignedRoute') ->with('storage.local', $expiration, ['path' => 'tenant/documents/file.txt'], false) - ->andReturn('/signed/file.txt'); - $url->shouldReceive('to') - ->once() + ->returns('/signed/file.txt'); + $url->expects('to') ->with('/signed/file.txt') - ->andReturn('https://example.test/signed/file.txt'); + ->returns('https://example.test/signed/file.txt'); $container->instance('url', $url); $filesystem = new FilesystemManager($container); $disk = $filesystem->disk('documents'); @@ -610,15 +611,13 @@ public function testAnonymousScopedDiskCanUseANamedServedAncestorRoute(): void ], ]); $expiration = new DateTimeImmutable('+5 minutes'); - $url = m::mock(); - $url->shouldReceive('temporarySignedRoute') - ->once() + $url = Double::for(UrlGenerator::class); + $url->expects('temporarySignedRoute') ->with('storage.local', $expiration, ['path' => 'tenant/file.txt'], false) - ->andReturn('/signed/file.txt'); - $url->shouldReceive('to') - ->once() + ->returns('/signed/file.txt'); + $url->expects('to') ->with('/signed/file.txt') - ->andReturn('https://example.test/signed/file.txt'); + ->returns('https://example.test/signed/file.txt'); $container->instance('url', $url); $filesystem = new FilesystemManager($container); $disk = $filesystem->build([ @@ -660,8 +659,8 @@ public function testScopedDiskPreservesViewBehaviorAndPoolOverrides(): void ], ]); Container::setInstance($container); - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldReceive('report')->once()->with(m::type(UnableToWriteFile::class)); + $exceptionHandler = Double::for(ExceptionHandler::class); + $exceptionHandler->expects('report')->with(Argument::type(UnableToWriteFile::class)); $container->instance(ExceptionHandler::class, $exceptionHandler); $filesystem = (new FilesystemManager($container))->addPoolableDriver('local'); $disk = $filesystem->disk('archive'); @@ -719,15 +718,13 @@ public function testServedOuterScopedDiskUsesItsOwnRouteWithoutAPathPrefix(): vo ], ]); $expiration = new DateTimeImmutable('+5 minutes'); - $url = m::mock(); - $url->shouldReceive('temporarySignedRoute') - ->once() + $url = Double::for(UrlGenerator::class); + $url->expects('temporarySignedRoute') ->with('storage.uploads', $expiration, ['path' => 'file.txt'], false) - ->andReturn('/signed/file.txt'); - $url->shouldReceive('to') - ->once() + ->returns('/signed/file.txt'); + $url->expects('to') ->with('/signed/file.txt') - ->andReturn('https://example.test/signed/file.txt'); + ->returns('https://example.test/signed/file.txt'); $container->instance('url', $url); $filesystem = new FilesystemManager($container); @@ -764,15 +761,13 @@ public function testNamedOnDemandLocalDiskUsesTheMatchingConfiguredRoute(): void ]; $container = $this->getContainer(['disks' => ['public' => $config]]); $expiration = new DateTimeImmutable('+5 minutes'); - $url = m::mock(); - $url->shouldReceive('temporarySignedRoute') - ->once() + $url = Double::for(UrlGenerator::class); + $url->expects('temporarySignedRoute') ->with('storage.public', $expiration, ['path' => 'file.txt'], false) - ->andReturn('/signed/file.txt'); - $url->shouldReceive('to') - ->once() + ->returns('/signed/file.txt'); + $url->expects('to') ->with('/signed/file.txt') - ->andReturn('https://example.test/signed/file.txt'); + ->returns('https://example.test/signed/file.txt'); $container->instance('url', $url); $disk = (new FilesystemManager($container))->build($config, 'public'); @@ -1129,17 +1124,17 @@ public function testReadThroughPromotionCancellationClosesOwnedStreams(bool $wra $temporary = null; $cancellation = new CanceledException('promotion canceled'); $failure = $wrapped ? UnableToWriteFile::atLocation('file.txt', previous: $cancellation) : $cancellation; - $primary = m::mock(FilesystemOperator::class); - $primary->shouldReceive('fileExists')->twice()->with('file.txt')->andReturn(false); - $primary->shouldReceive('writeStream')->once()->andReturnUsing( + $primary = Double::for(FilesystemOperator::class); + $primary->expects('fileExists')->times(2)->with('file.txt')->returns(false); + $primary->expects('writeStream')->resolves( static function (string $path, mixed $stream) use (&$temporary, $failure): never { $temporary = $stream; throw $failure; }, ); - $fallback = m::mock(FilesystemOperator::class); - $fallback->shouldReceive('readStream')->once()->with('file.txt')->andReturn($source); + $fallback = Double::for(FilesystemOperator::class); + $fallback->expects('readStream')->with('file.txt')->returns($source); $adapter = new ReadThroughFilesystemAdapter($primary, $fallback); $caught = null; @@ -1173,11 +1168,11 @@ static function (string $path, mixed $stream) use (&$temporary, $failure): never public function testReadThroughPromotionPreservesWrappedCancellationForStringReads(): void { $failure = UnableToWriteFile::atLocation('file.txt', previous: new CanceledException); - $primary = m::mock(FilesystemOperator::class); - $primary->shouldReceive('fileExists')->twice()->with('file.txt')->andReturnFalse(); - $primary->shouldReceive('write')->once()->with('file.txt', 'contents')->andThrow($failure); - $fallback = m::mock(FilesystemOperator::class); - $fallback->shouldReceive('read')->once()->with('file.txt')->andReturn('contents'); + $primary = Double::for(FilesystemOperator::class); + $primary->expects('fileExists')->times(2)->with('file.txt')->returns(false); + $primary->expects('write')->with('file.txt', 'contents')->throws($failure); + $fallback = Double::for(FilesystemOperator::class); + $fallback->expects('read')->with('file.txt')->returns('contents'); $adapter = new ReadThroughFilesystemAdapter($primary, $fallback); $caught = null; @@ -1196,9 +1191,9 @@ public function testReadThroughPromotionRetainsItsStreamWhenThePrimaryClosesItsI $filesystem = $this->readThroughFilesystemManager(); $fallback = $filesystem->disk('fallback'); $fallback->put('file.txt', 'fallback contents'); - $primary = m::mock(FilesystemOperator::class); - $primary->shouldReceive('fileExists')->twice()->with('file.txt')->andReturn(false); - $primary->shouldReceive('writeStream')->once()->andReturnUsing( + $primary = Double::for(FilesystemOperator::class); + $primary->expects('fileExists')->times(2)->with('file.txt')->returns(false); + $primary->expects('writeStream')->resolves( function (string $path, mixed $stream) use ($fails): void { $this->assertSame('file.txt', $path); $this->assertSame('fallback contents', stream_get_contents($stream)); @@ -1236,9 +1231,9 @@ public function testReadThroughFallbackTransfersAllowThePrimaryToCloseItsInput(s $filesystem = $this->readThroughFilesystemManager(); $fallback = $filesystem->disk('fallback'); $fallback->put('source.txt', 'contents'); - $primary = m::mock(FilesystemOperator::class); - $primary->shouldReceive('fileExists')->once()->with('source.txt')->andReturn(false); - $primary->shouldReceive('writeStream')->once()->andReturnUsing( + $primary = Double::for(FilesystemOperator::class); + $primary->expects('fileExists')->with('source.txt')->returns(false); + $primary->expects('writeStream')->resolves( function (string $path, mixed $stream, array $config): void { $this->assertSame('destination.txt', $path); $this->assertSame('contents', stream_get_contents($stream)); @@ -2506,17 +2501,13 @@ function (CommandInterface $command) use ($expectedAcl): Result { ]); $disk = $filesystem->buildS3DiskForTest($client, $config); } else { - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('upload')->once()->withArgs( - function (string $contents, array $options) use ($expectedAcl): bool { - $this->assertSame('contents', $contents); - $this->assertSame($expectedAcl, $options['predefinedAcl']); - - return true; - }, + $bucket = Double::for(Bucket::class); + $bucket->expects('upload')->with( + 'contents', + Argument::satisfies(fn (array $options): bool => $options['predefinedAcl'] === $expectedAcl), ); - $client = m::mock(GcsClient::class); - $client->shouldReceive('bucket')->once()->with('documents')->andReturn($bucket); + $client = Double::for(GcsClient::class); + $client->expects('bucket')->with('documents')->returns($bucket); $disk = $filesystem->buildGcsDiskForTest($client, $config); } @@ -2556,9 +2547,9 @@ public function testGcsClientConfigSupportsFlatKeysAndTheFullExplicitSdkSurface( public function testGcsDiskUsesTheSharedFlysystemStackConfiguration(): void { - $bucket = m::mock(Bucket::class); - $client = m::mock(GcsClient::class); - $client->shouldReceive('bucket')->once()->with('documents')->andReturn($bucket); + $bucket = Double::for(Bucket::class); + $client = Double::for(GcsClient::class); + $client->expects('bucket')->with('documents')->returns($bucket); $filesystem = new InspectableFilesystemManager($this->getContainer()); $disk = $filesystem->buildGcsDiskForTest($client, [ 'bucket' => 'documents', @@ -2599,9 +2590,9 @@ public function testGcsDiskUsesTheSharedFlysystemStackConfiguration(): void public function testGcsDiskDefaultsStreamingReadsAndAllowsOptOut(): void { - $bucket = m::mock(Bucket::class); - $client = m::mock(GcsClient::class); - $client->shouldReceive('bucket')->twice()->with('documents')->andReturn($bucket); + $bucket = Double::for(Bucket::class); + $client = Double::for(GcsClient::class); + $client->expects('bucket')->times(2)->with('documents')->returns($bucket); $filesystem = new InspectableFilesystemManager($this->getContainer()); $default = $filesystem->buildGcsDiskForTest($client, ['bucket' => 'documents']); diff --git a/tests/Filesystem/FilesystemPoolProxyTest.php b/tests/Filesystem/FilesystemPoolProxyTest.php index 0341ec613e..0bca434581 100644 --- a/tests/Filesystem/FilesystemPoolProxyTest.php +++ b/tests/Filesystem/FilesystemPoolProxyTest.php @@ -26,11 +26,12 @@ use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\Flysystem\Filesystem; use League\Flysystem\FilesystemOperator; use League\Flysystem\Local\LocalFilesystemAdapter; use League\Flysystem\UnableToReadFile; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -39,6 +40,8 @@ class FilesystemPoolProxyTest extends TestCase { + use VerifiesDoubles; + private string $tempDir; private Filesystem $driver; @@ -83,9 +86,9 @@ protected function tearDown(): void public function testRemoteOperationsReleaseIdleDatabaseSessionsButPathFormattingDoesNot(string $operation): void { $this->driver->write('file.txt', 'contents'); - $adapter = m::mock(FilesystemAdapter::class, [$this->driver, $this->adapter, ['root' => $this->tempDir]])->makePartial(); + $adapter = Double::for(new FilesystemAdapter($this->driver, $this->adapter, ['root' => $this->tempDir]))->passthru(); if ($operation === 'url') { - $adapter->shouldReceive('url')->once()->with('file.txt')->andReturn('https://storage.example/file.txt'); + $adapter->expects('url')->with('file.txt')->returns('https://storage.example/file.txt'); } $proxy = $this->proxy(static fn (): FilesystemAdapter => $adapter); $connection = DB::connection('filesystem_release'); @@ -292,8 +295,8 @@ function (object $filesystem) use (&$releaseCalls): void { #[DataProvider('bufferedReadProvider')] public function testBufferedReadsReleaseTheWholeDriverImmediately(string $uri, ?int $start, ?int $end, string $expected): void { - $driver = m::mock(FilesystemOperator::class); - $driver->shouldReceive('readStream')->once()->with('file.txt')->andReturnUsing(static function () use ($uri): mixed { + $driver = Double::for(FilesystemOperator::class); + $driver->expects('readStream')->with('file.txt')->resolves(static function () use ($uri): mixed { $stream = fopen($uri, 'w+b'); fwrite($stream, '0123456789'); rewind($stream); @@ -339,8 +342,8 @@ public function testCachedLiveRangeKeepsTheWholeDriverBorrowedUntilClose(): void return ++$reads === 1 ? 'remote bytes' : false; }); $range = StreamWrapper::getResource(new LimitStream(new CachingStream($source), 3)); - $driver = m::mock(FilesystemOperator::class); - $driver->shouldReceive('readStream')->once()->with('file.txt')->andReturn($range); + $driver = Double::for(FilesystemOperator::class); + $driver->expects('readStream')->with('file.txt')->returns($range); $proxy = $this->proxy(fn (): FilesystemAdapter => new FilesystemAdapter($driver, $this->adapter)); $stream = $proxy->readStream('file.txt'); @@ -454,8 +457,8 @@ public function testUnknownMethodsAreRejectedInsteadOfDynamicallyForwarded(): vo public function testContractOnlyFilesystemPoolsWhenCallbacksAreUnset(): void { - $filesystem = m::mock(FilesystemContract::class); - $filesystem->shouldReceive('exists')->once()->with('file.txt')->andReturnTrue(); + $filesystem = Double::for(FilesystemContract::class); + $filesystem->expects('exists')->with('file.txt')->returns(true); $proxy = $this->proxy(static fn (): FilesystemContract => $filesystem); $this->assertTrue($proxy->exists('file.txt')); @@ -465,7 +468,7 @@ public function testContractOnlyFilesystemPoolsWhenCallbacksAreUnset(): void public function testSettingCallbacksOnAContractOnlyFilesystemFailsAndDiscardsIt(): void { - $filesystem = m::mock(FilesystemContract::class); + $filesystem = Double::for(FilesystemContract::class); $proxy = $this->proxy(static fn (): FilesystemContract => $filesystem); $proxy->buildTemporaryUrlsUsing(static fn (): string => 'url'); diff --git a/tests/Filesystem/GoogleCloudStorageAdapterTest.php b/tests/Filesystem/GoogleCloudStorageAdapterTest.php index b9bfe1d986..5c58bb9538 100644 --- a/tests/Filesystem/GoogleCloudStorageAdapterTest.php +++ b/tests/Filesystem/GoogleCloudStorageAdapterTest.php @@ -22,11 +22,12 @@ use Hypervel\Filesystem\ReadThroughFilesystemAdapter; use Hypervel\Tests\TestCase; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\Flysystem\Filesystem; use League\Flysystem\FilesystemOperator; use League\Flysystem\GoogleCloudStorage\GoogleCloudStorageAdapter as FlysystemGoogleCloudAdapter; use League\Flysystem\UnableToReadFile; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\StreamInterface; @@ -38,6 +39,8 @@ class GoogleCloudStorageAdapterTest extends TestCase { + use VerifiesDoubles; + public function testResumableUploadPreservesCancellation(): void { // @TODO: Remove this skip once google/cloud-core's ResumableUploader::upload preserves @@ -113,8 +116,8 @@ public function testReadThroughPromotionRetainsItsStreamAfterGoogleUploads(bool $source = fopen('php://temp', 'w+b'); fwrite($source, 'fallback contents'); rewind($source); - $fallback = m::mock(FilesystemOperator::class); - $fallback->shouldReceive('readStream')->once()->with('file.txt')->andReturn($source); + $fallback = Double::for(FilesystemOperator::class); + $fallback->expects('readStream')->with('file.txt')->returns($source); $adapter = new ReadThroughFilesystemAdapter($primary, $fallback); $stream = null; @@ -137,7 +140,7 @@ public function testReadThroughPromotionRetainsItsStreamAfterGoogleUploads(bool public function testUrlUsesTheConfiguredApiUriOrBucketEndpoint(): void { - $client = m::mock(StorageClient::class); + $client = Double::for(StorageClient::class); $path = 'nested/report%2F v?x#y+z.txt'; $encodedPath = 'nested/report%252F%20v%3Fx%23y%2Bz.txt'; @@ -158,20 +161,19 @@ public function testUrlUsesTheConfiguredApiUriOrBucketEndpoint(): void public function testReadStreamRangeSendsANativeRangeHeaderForThePrefixedObject(): void { $stream = Utils::streamFor('range-body'); - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream') - ->once() + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream') ->with([ 'restOptions' => [ - 'headers' => ['Range' => 'bytes=3-5'], 'stream' => true, + 'headers' => ['Range' => 'bytes=3-5'], ], ]) - ->andReturn($stream); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('tenant/file.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->once()->with('bucket')->andReturn($bucket); + ->returns($stream); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('tenant/file.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->with('bucket')->returns($bucket); $adapter = $this->adapter($client, [ 'bucket' => 'bucket', 'root' => 'tenant', @@ -187,19 +189,17 @@ public function testReadStreamRangeSendsANativeRangeHeaderForThePrefixedObject() public function testReadStreamRangeSupportsOpenAndSuffixRangesWithoutForcingStreaming(): void { - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream') - ->once() + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream') ->with(['restOptions' => ['headers' => ['Range' => 'bytes=3-']]]) - ->andReturn(Utils::streamFor('open')); - $object->shouldReceive('downloadAsStream') - ->once() + ->returns(Utils::streamFor('open')); + $object->expects('downloadAsStream') ->with(['restOptions' => ['headers' => ['Range' => 'bytes=-3']]]) - ->andReturn(Utils::streamFor('suffix')); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->twice()->with('file.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->twice()->with('bucket')->andReturn($bucket); + ->returns(Utils::streamFor('suffix')); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->times(2)->with('file.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->times(2)->with('bucket')->returns($bucket); $adapter = $this->adapter($client, [ 'bucket' => 'bucket', 'stream_reads' => false, @@ -217,15 +217,14 @@ public function testReadStreamRangeSupportsOpenAndSuffixRangesWithoutForcingStre public function testReadStreamRangeWithoutBoundsDelegatesToTheFullStream(): void { $body = Utils::streamFor('full-body'); - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream') - ->once() + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream') ->with(['restOptions' => ['stream' => true]]) - ->andReturn($body); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('file.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->once()->with('bucket')->andReturn($bucket); + ->returns($body); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('file.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->with('bucket')->returns($bucket); $adapter = $this->adapter($client, ['bucket' => 'bucket']); $stream = $adapter->readStreamRange('file.txt', null, null); @@ -241,15 +240,14 @@ public function testReadStreamDefaultsToLazyCoroutineSafeStreaming(): void $this->assertIsArray($sockets); [$reader, $writer] = $sockets; $this->assertTrue(stream_set_timeout($reader, 1)); - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream') - ->once() + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream') ->with(['restOptions' => ['stream' => true]]) - ->andReturn(Utils::streamFor($reader)); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('file.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->once()->with('bucket')->andReturn($bucket); + ->returns(Utils::streamFor($reader)); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('file.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->with('bucket')->returns($bucket); $adapter = $this->adapter($client, ['bucket' => 'bucket']); $stream = null; @@ -280,7 +278,7 @@ public function testReadStreamDefaultsToLazyCoroutineSafeStreaming(): void public function testReadStreamRangeRejectsInvalidArgumentsBeforeClientIo(): void { - $adapter = $this->adapter(m::mock(StorageClient::class), ['bucket' => 'bucket']); + $adapter = $this->adapter(Double::for(StorageClient::class)->strict(), ['bucket' => 'bucket']); foreach ([[-1, 2], [1, -2], [3, 2], [null, 0]] as [$start, $end]) { try { @@ -294,12 +292,12 @@ public function testReadStreamRangeRejectsInvalidArgumentsBeforeClientIo(): void public function testReadStreamRangeWrapsClientFailures(): void { - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream')->once()->andThrow(new RuntimeException('GCS failed')); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('file.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->once()->with('bucket')->andReturn($bucket); + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream')->throws(new RuntimeException('GCS failed')); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('file.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->with('bucket')->returns($bucket); $adapter = $this->adapter($client, ['bucket' => 'bucket', 'throw' => true]); $this->expectException(UnableToReadFile::class); @@ -316,15 +314,15 @@ public function testReadStreamRangePreservesCancellationWithoutReporting(bool $w { $cancellation = new CanceledException('read canceled'); $failure = $wrapped ? new ServiceException('SDK request canceled.', 0, $cancellation) : $cancellation; - $exceptionHandler = m::mock(ExceptionHandler::class); - $exceptionHandler->shouldNotReceive('report'); + $exceptionHandler = Double::for(ExceptionHandler::class); + $exceptionHandler->expects('report')->never(); Container::getInstance()->bind(ExceptionHandler::class, static fn () => $exceptionHandler); - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream')->once()->andThrow($failure); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('file.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->once()->with('bucket')->andReturn($bucket); + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream')->throws($failure); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('file.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->with('bucket')->returns($bucket); $adapter = $this->adapter($client, [ 'bucket' => 'bucket', 'report' => true, @@ -345,14 +343,15 @@ public function testReadStreamRangePreservesCancellationWithoutReporting(bool $w public function testReadStreamRangeRejectsAResultWithoutAResourceWhenConfigured(): void { - $stream = m::mock(StreamInterface::class); - $stream->shouldReceive('isReadable', 'isWritable')->andReturnFalse(); - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream')->once()->andReturn($stream); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('file.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->once()->with('bucket')->andReturn($bucket); + $stream = Double::for(StreamInterface::class); + $stream->allows('isReadable')->returns(false); + $stream->allows('isWritable')->returns(false); + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream')->returns($stream); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('file.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->with('bucket')->returns($bucket); $adapter = $this->adapter($client, ['bucket' => 'bucket', 'throw' => true]); $this->expectException(UnableToReadFile::class); @@ -363,13 +362,13 @@ public function testReadStreamRangeRejectsAResultWithoutAResourceWhenConfigured( public function testReadFailuresReturnNullWhenExceptionsAreDisabled(): void { - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream')->twice()->andThrow(new RuntimeException('GCS failed')); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('plain.txt')->andReturn($object); - $bucket->shouldReceive('object')->once()->with('range.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->twice()->with('bucket')->andReturn($bucket); + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream')->times(2)->throws(new RuntimeException('GCS failed')); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('plain.txt')->returns($object); + $bucket->expects('object')->with('range.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->times(2)->with('bucket')->returns($bucket); $adapter = $this->adapter($client, ['bucket' => 'bucket']); $this->assertNull($adapter->readStream('plain.txt')); @@ -380,12 +379,12 @@ public function testNonResourceReturnsNullWhenExceptionsAreDisabled(): void { $stream = Utils::streamFor('contents'); fclose($stream->detach()); - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream')->once()->andReturn($stream); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('file.txt')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->once()->with('bucket')->andReturn($bucket); + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream')->returns($stream); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('file.txt')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->with('bucket')->returns($bucket); $adapter = $this->adapter($client, ['bucket' => 'bucket']); $this->assertNull($adapter->readStream('file.txt')); @@ -402,12 +401,12 @@ public function testDecodedReadStreamPreservesCancellationAndClosesItsBody(bool $body = new InflateBodyStream($cancel ? new PumpStream(static fn () => throw $failure) : Utils::streamFor($native)); - $object = m::mock(StorageObject::class); - $object->shouldReceive('downloadAsStream')->once()->andReturn($body); - $bucket = m::mock(Bucket::class); - $bucket->shouldReceive('object')->once()->with('file.gz')->andReturn($object); - $client = m::mock(StorageClient::class); - $client->shouldReceive('bucket')->once()->with('bucket')->andReturn($bucket); + $object = Double::for(StorageObject::class); + $object->expects('downloadAsStream')->returns($body); + $bucket = Double::for(Bucket::class); + $bucket->expects('object')->with('file.gz')->returns($object); + $client = Double::for(StorageClient::class); + $client->expects('bucket')->with('bucket')->returns($bucket); $adapter = $this->adapter($client, ['bucket' => 'bucket']); $resource = $adapter->readStream('file.gz'); $caught = null; @@ -442,8 +441,8 @@ public function testDecodedReadStreamPreservesCancellationAndClosesItsBody(bool private function adapter(StorageClient $client, array $config): GoogleCloudStorageAdapter { return new GoogleCloudStorageAdapter( - m::mock(FilesystemOperator::class), - m::mock(FlysystemGoogleCloudAdapter::class), + Double::for(FilesystemOperator::class), + Double::for(FlysystemGoogleCloudAdapter::class), $config, $client, ); diff --git a/tests/Filesystem/LeasedStreamTest.php b/tests/Filesystem/LeasedStreamTest.php index 5798812e96..55bd09f6a0 100644 --- a/tests/Filesystem/LeasedStreamTest.php +++ b/tests/Filesystem/LeasedStreamTest.php @@ -13,7 +13,8 @@ use Hypervel\ObjectPool\PoolOptions; use Hypervel\Tests\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use stdClass; use Swoole\Coroutine\CanceledException; @@ -21,6 +22,8 @@ class LeasedStreamTest extends TestCase { + use VerifiesDoubles; + /** @var list */ private array $pools = []; @@ -172,8 +175,8 @@ public function testReleaseFailureDuringCloseIsReportedAndSwallowed(): void $container = new Container; Container::setInstance($container); $failure = new RuntimeException('release cleanup failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($failure); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($failure); $container->instance(ExceptionHandler::class, $handler); $pool = $this->pool(); $lease = new Lease($pool, $pool->borrow(), function () use ($failure): never { diff --git a/tests/Filesystem/ScopedFilesystemProxyTest.php b/tests/Filesystem/ScopedFilesystemProxyTest.php index 6fd17d1a10..63d224421d 100644 --- a/tests/Filesystem/ScopedFilesystemProxyTest.php +++ b/tests/Filesystem/ScopedFilesystemProxyTest.php @@ -19,11 +19,13 @@ use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; use InvalidArgumentException; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use League\Flysystem\CorruptedPathDetected; use League\Flysystem\Filesystem; +use League\Flysystem\FilesystemOperator; use League\Flysystem\Local\LocalFilesystemAdapter; use League\Flysystem\PathTraversalDetected; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; @@ -34,6 +36,8 @@ class ScopedFilesystemProxyTest extends TestCase { + use VerifiesDoubles; + private string $tempDir; private FilesystemAdapter $disk; @@ -68,14 +72,14 @@ public function testTransfersUseContractMethodsAndResolveSourceOnce(string $meth $stream = fopen('php://temp', 'w+b'); fwrite($stream, 'contents'); rewind($stream); - $source = m::mock(FilesystemContract::class); - $source->shouldReceive('readStream')->once()->with('tenant/file.txt')->andReturn($stream); - $destination = $sameDisk ? $source : m::mock(FilesystemContract::class); - $destination->shouldReceive('writeStream')->once() - ->with(($sameDisk ? 'tenant/' : '') . ($to ?? 'file.txt'), $stream)->andReturnTrue(); + $source = Double::for(FilesystemContract::class); + $source->expects('readStream')->with('tenant/file.txt')->returns($stream); + $destination = $sameDisk ? $source : Double::for(FilesystemContract::class); + $destination->expects('writeStream') + ->with(($sameDisk ? 'tenant/' : '') . ($to ?? 'file.txt'), $stream)->returns(true); if ($method === 'moveToDisk') { - $source->shouldReceive('delete')->once()->with('tenant/file.txt')->andReturnTrue(); + $source->expects('delete')->with('tenant/file.txt')->returns(true); } $diskCalls = $prefixCalls = 0; @@ -126,8 +130,7 @@ public function testEveryMappedMethodPrefixesExactlyOnce( mixed $innerResult, mixed $expectedResult, ): void { - $inner = m::mock(FilesystemAdapter::class); - $inner->shouldReceive($method)->once()->with(...$innerArguments)->andReturn($innerResult); + $inner = $this->expectInnerCall($method, $innerArguments, $innerResult); $prefixCalls = 0; $proxy = new ScopedFilesystemProxy($inner, function () use (&$prefixCalls): string { ++$prefixCalls; @@ -149,8 +152,7 @@ public function testEveryMappedMethodResolvesTheDiskExactlyOnce( mixed $innerResult, mixed $expectedResult, ): void { - $inner = m::mock(FilesystemAdapter::class); - $inner->shouldReceive($method)->once()->with(...$innerArguments)->andReturn($innerResult); + $inner = $this->expectInnerCall($method, $innerArguments, $innerResult); $diskCalls = 0; $proxy = new ScopedFilesystemProxy( function () use ($inner, &$diskCalls): FilesystemContract { @@ -222,6 +224,27 @@ public static function mappedMethodProvider(): array ]; } + /** + * Expect the mapped call on its declared adapter or Flysystem boundary. + */ + private function expectInnerCall(string $method, array $arguments, mixed $result): FilesystemAdapter + { + if (method_exists(FilesystemAdapter::class, $method)) { + $inner = $target = Double::for(FilesystemAdapter::class); + } else { + $target = Double::for(FilesystemOperator::class); + $inner = new FilesystemAdapter($target, $this->disk->getAdapter()); + } + + $expectation = $target->expects($method)->with(...$arguments); + + if ($result !== null) { + $expectation->returns($result); + } + + return $inner; + } + public function testFlysystemMethodsAndConditionableUseTheScopedBoundary(): void { $prefixCalls = 0; @@ -255,13 +278,13 @@ public function testFlysystemMethodsAndConditionableUseTheScopedBoundary(): void public function testReadAndWriteStreamsAreMappedWithoutConsumingDeferredResults(): void { - $inner = m::mock(FilesystemAdapter::class); + $inner = Double::for(FilesystemAdapter::class); $readStream = fopen('php://temp', 'r+'); $writeStream = fopen('php://temp', 'r+'); $this->assertIsResource($readStream); $this->assertIsResource($writeStream); - $inner->shouldReceive('readStream')->once()->with('tenant/read.txt')->andReturn($readStream); - $inner->shouldReceive('writeStream')->once()->with('tenant/write.txt', $writeStream, ['visibility' => 'private'])->andReturnTrue(); + $inner->expects('readStream')->with('tenant/read.txt')->returns($readStream); + $inner->expects('writeStream')->with('tenant/write.txt', $writeStream, ['visibility' => 'private'])->returns(true); $prefixCalls = 0; $proxy = new ScopedFilesystemProxy($inner, function () use (&$prefixCalls): string { ++$prefixCalls; @@ -283,15 +306,13 @@ public function testPutFileOverloadsPrefixAndStripReturnedPaths(): void $path = $this->tempDir . '/upload.txt'; file_put_contents($path, 'upload'); $upload = new UploadedFile($path, 'upload.txt', test: true); - $inner = m::mock(FilesystemAdapter::class); - $inner->shouldReceive('putFile') - ->once() + $inner = Double::for(FilesystemAdapter::class); + $inner->expects('putFile') ->with('tenant', $upload, []) - ->andReturn('tenant/generated.txt'); - $inner->shouldReceive('putFileAs') - ->once() + ->returns('tenant/generated.txt'); + $inner->expects('putFileAs') ->with('tenant/named.txt', $upload, '', []) - ->andReturn('tenant/named.txt'); + ->returns('tenant/named.txt'); $prefixCalls = 0; $proxy = new ScopedFilesystemProxy($inner, function () use (&$prefixCalls): string { ++$prefixCalls; @@ -326,17 +347,16 @@ public function testPutFileAsRejectsFinalTargetEscapeBeforeWriting(): void public function testImageCapturesTheNormalizedPrefixAndResolvedDiskBeforeLazyReading(): void { $readCalls = 0; - $first = m::mock(FilesystemContract::class); - $first->shouldReceive('get') - ->once() + $first = Double::for(FilesystemContract::class); + $first->expects('get') ->with('tenants/first/photo.jpg') - ->andReturnUsing(function () use (&$readCalls): string { + ->resolves(function () use (&$readCalls): string { ++$readCalls; return 'first image'; }); - $second = m::mock(FilesystemContract::class); - $second->shouldNotReceive('get'); + $second = Double::for(FilesystemContract::class); + $second->expects('get')->never(); $currentDisk = $first; $currentPrefix = 'tenants/first/images/..'; $diskCalls = 0; @@ -391,8 +411,8 @@ public function testImageHonorsExplicitRootPassthrough(): void public function testMissingImageReportsOnlyTheCallerPath(): void { - $inner = m::mock(FilesystemContract::class); - $inner->shouldReceive('get')->once()->with('secret-tenant/missing.jpg')->andReturnNull(); + $inner = Double::for(FilesystemContract::class); + $inner->expects('get')->with('secret-tenant/missing.jpg')->returns(null); $proxy = new ScopedFilesystemProxy($inner, static fn (): string => 'secret-tenant'); $image = $proxy->image('missing.jpg'); @@ -410,10 +430,10 @@ public function testMissingImageReportsOnlyTheCallerPath(): void public function testNoPathMethodsDoNotResolveThePrefix(): void { - $inner = m::mock(FilesystemAdapter::class); - $inner->shouldReceive('providesTemporaryUrls')->once()->andReturnTrue(); - $inner->shouldReceive('providesTemporaryUploadUrls')->once()->andReturnFalse(); - $inner->shouldReceive('getConfig')->once()->andReturn(['driver' => 'local']); + $inner = Double::for(FilesystemAdapter::class); + $inner->expects('providesTemporaryUrls')->returns(true); + $inner->expects('providesTemporaryUploadUrls')->returns(false); + $inner->expects('getConfig')->returns(['driver' => 'local']); $proxy = new ScopedFilesystemProxy( $inner, static fn (): never => throw new RuntimeException('prefix must not be resolved'), @@ -426,10 +446,10 @@ public function testNoPathMethodsDoNotResolveThePrefix(): void public function testNoPathMethodsResolveTheDiskOncePerCallWithoutResolvingThePrefix(): void { - $inner = m::mock(FilesystemAdapter::class); - $inner->shouldReceive('providesTemporaryUrls')->once()->andReturnTrue(); - $inner->shouldReceive('providesTemporaryUploadUrls')->once()->andReturnFalse(); - $inner->shouldReceive('getConfig')->once()->andReturn(['driver' => 'local']); + $inner = Double::for(FilesystemAdapter::class); + $inner->expects('providesTemporaryUrls')->returns(true); + $inner->expects('providesTemporaryUploadUrls')->returns(false); + $inner->expects('getConfig')->returns(['driver' => 'local']); $diskCalls = 0; $proxy = new ScopedFilesystemProxy( function () use ($inner, &$diskCalls): FilesystemContract { @@ -448,12 +468,12 @@ function () use ($inner, &$diskCalls): FilesystemContract { public function testEveryAssertionMapsPathsAndReturnsTheScopedProxy(): void { - $inner = m::mock(FilesystemAdapter::class); - $inner->shouldReceive('assertExists')->once()->with(['tenant/a.txt', 'tenant/b.txt'], 'content')->andReturnSelf(); - $inner->shouldReceive('assertMissing')->once()->with(['tenant/c.txt', 'tenant/d.txt'])->andReturnSelf(); - $inner->shouldReceive('assertCount')->once()->with('tenant/dir', 2, true)->andReturnSelf(); - $inner->shouldReceive('assertDirectoryEmpty')->once()->with('tenant/empty')->andReturnSelf(); - $inner->shouldReceive('assertDirectoryEmpty')->once()->with('tenant')->andReturnSelf(); + $inner = Double::for(FilesystemAdapter::class); + $inner->expects('assertExists')->with(['tenant/a.txt', 'tenant/b.txt'], 'content'); + $inner->expects('assertMissing')->with(['tenant/c.txt', 'tenant/d.txt']); + $inner->expects('assertCount')->with('tenant/dir', 2, true); + $inner->expects('assertDirectoryEmpty')->with('tenant/empty'); + $inner->expects('assertDirectoryEmpty')->with('tenant'); $prefixCalls = 0; $proxy = new ScopedFilesystemProxy($inner, function () use (&$prefixCalls): string { ++$prefixCalls; @@ -528,9 +548,9 @@ public function testPrefixTraversalIsRejected(): void public function testInternalTraversalNormalizesWhilePercentEncodingRemainsLiteral(): void { - $inner = m::mock(FilesystemAdapter::class); - $inner->shouldReceive('exists')->once()->with('tenant/b.txt')->andReturnTrue(); - $inner->shouldReceive('exists')->once()->with('tenant/%2e%2e%2fsecret')->andReturnTrue(); + $inner = Double::for(FilesystemAdapter::class); + $inner->expects('exists')->with('tenant/b.txt')->returns(true); + $inner->expects('exists')->with('tenant/%2e%2e%2fsecret')->returns(true); $proxy = new ScopedFilesystemProxy($inner, static fn (): string => 'tenant'); $this->assertTrue($proxy->exists('a/../b.txt')); @@ -540,8 +560,8 @@ public function testInternalTraversalNormalizesWhilePercentEncodingRemainsLitera #[DataProvider('foreignReturnedPathProvider')] public function testReturnedPathsOutsideTheNormalizedPrefixFailClosed(string $returned): void { - $inner = m::mock(FilesystemAdapter::class); - $inner->shouldReceive('files')->once()->with('tenant', false)->andReturn([$returned]); + $inner = Double::for(FilesystemAdapter::class); + $inner->expects('files')->with('tenant', false)->returns([$returned]); $proxy = new ScopedFilesystemProxy($inner, static fn (): string => 'tenant'); $this->expectException(RuntimeException::class); @@ -584,10 +604,10 @@ function () use ($proxy): void { public function testDiskIsResolvedPerOperation(): void { - $first = m::mock(FilesystemContract::class); - $first->shouldReceive('get')->once()->with('tenant/file.txt')->andReturn('first'); - $second = m::mock(FilesystemContract::class); - $second->shouldReceive('get')->once()->with('tenant/file.txt')->andReturn('second'); + $first = Double::for(FilesystemContract::class); + $first->expects('get')->with('tenant/file.txt')->returns('first'); + $second = Double::for(FilesystemContract::class); + $second->expects('get')->with('tenant/file.txt')->returns('second'); $current = $first; $diskCalls = 0; $proxy = new ScopedFilesystemProxy( @@ -697,7 +717,7 @@ public function testUnknownMethodsAndUnsupportedInnerCapabilitiesAreRejected(): $this->assertStringContainsString('unmapped calls could bypass', $exception->getMessage()); } - $inner = m::mock(FilesystemContract::class); + $inner = Double::for(FilesystemContract::class); $proxy = new ScopedFilesystemProxy($inner, static fn (): string => 'tenant'); $this->expectException(BadMethodCallException::class); @@ -736,7 +756,7 @@ function () use (&$diskCalls): FilesystemContract { public function testResolvedDiskWithoutMappedCapabilityIsRejected(): void { - $inner = m::mock(FilesystemContract::class); + $inner = Double::for(FilesystemContract::class); $proxy = new ScopedFilesystemProxy( static fn (): FilesystemContract => $inner, static fn (): string => 'tenant', @@ -750,8 +770,8 @@ public function testResolvedDiskWithoutMappedCapabilityIsRejected(): void public function testCloudVariantMapsUrlAndResolvesPrefixOnce(): void { - $inner = m::mock(Cloud::class); - $inner->shouldReceive('url')->once()->with('tenant/file.txt')->andReturn('https://example.test/file.txt'); + $inner = Double::for(Cloud::class); + $inner->expects('url')->with('tenant/file.txt')->returns('https://example.test/file.txt'); $prefixCalls = 0; $proxy = new ScopedCloudFilesystemProxy($inner, function () use (&$prefixCalls): string { ++$prefixCalls; @@ -765,8 +785,8 @@ public function testCloudVariantMapsUrlAndResolvesPrefixOnce(): void public function testCloudVariantResolvesTheDiskOnce(): void { - $inner = m::mock(Cloud::class); - $inner->shouldReceive('url')->once()->with('tenant/file.txt')->andReturn('https://example.test/file.txt'); + $inner = Double::for(Cloud::class); + $inner->expects('url')->with('tenant/file.txt')->returns('https://example.test/file.txt'); $diskCalls = 0; $proxy = new ScopedCloudFilesystemProxy( function () use ($inner, &$diskCalls): Cloud { @@ -784,11 +804,10 @@ function () use ($inner, &$diskCalls): Cloud { public function testCloudVariantInheritsLazyImageScoping(): void { $readCalls = 0; - $inner = m::mock(Cloud::class); - $inner->shouldReceive('get') - ->once() + $inner = Double::for(Cloud::class); + $inner->expects('get') ->with('tenant/photo.jpg') - ->andReturnUsing(function () use (&$readCalls): string { + ->resolves(function () use (&$readCalls): string { ++$readCalls; return 'cloud image'; @@ -804,7 +823,7 @@ public function testCloudVariantInheritsLazyImageScoping(): void public function testCloudVariantRejectsANonCloudResolvedDisk(): void { - $inner = m::mock(FilesystemContract::class); + $inner = Double::for(FilesystemContract::class); $proxy = new ScopedCloudFilesystemProxy( static fn (): FilesystemContract => $inner, static fn (): string => 'tenant', diff --git a/tests/Fortify/Console/InstallCommandTest.php b/tests/Fortify/Console/InstallCommandTest.php index 246f70e8e0..93724133a2 100644 --- a/tests/Fortify/Console/InstallCommandTest.php +++ b/tests/Fortify/Console/InstallCommandTest.php @@ -13,12 +13,15 @@ use Hypervel\Passkeys\Passkeys; use Hypervel\Testbench\TestCase; use Hypervel\Tests\Testing\Fixtures\CleanupActions; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\Console\Command\Command as SymfonyCommand; class InstallCommandTest extends TestCase { + use VerifiesDoubles; + protected ?string $originalProvidersContents = null; protected function setUp(): void @@ -169,8 +172,8 @@ public function testInstallCommandStopsAfterPublishedFileReplacementFails(): voi $laterFile = $this->publishedSupportFiles()[1]; (new Filesystem)->replace($laterFile, 'shouldReceive('replace')->once()->andThrow(new RuntimeException('replace failed')); + $files = Double::for(Filesystem::class); + $files->expects('replace')->throws(new RuntimeException('replace failed')); $this->app->instance(Filesystem::class, $files); $this->artisan('fortify:install') diff --git a/tests/Fortify/FortifyApiTest.php b/tests/Fortify/FortifyApiTest.php index 81d73eae79..2e67474c63 100644 --- a/tests/Fortify/FortifyApiTest.php +++ b/tests/Fortify/FortifyApiTest.php @@ -47,7 +47,8 @@ use Hypervel\Http\Request; use Hypervel\RateLimiter\RateLimiter; use Hypervel\Support\Facades\Password; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use ReflectionClass; use ReflectionProperty; @@ -55,6 +56,8 @@ class FortifyApiTest extends TestCase { + use VerifiesDoubles; + #[DataProvider('controllersWithoutRequiredConstructorsProvider')] public function testControllersHaveNoRequiredConstructor(string $controller): void { @@ -196,7 +199,7 @@ public function testConfirmPasswordDispatchesThroughProtectedCustomCallbackMetho $action = new FortifyApiConfirmPassword; - $this->assertTrue($action(m::mock(StatefulGuard::class), new User, 'secret')); + $this->assertTrue($action(Double::for(StatefulGuard::class), new User, 'secret')); $this->assertTrue($action->customCallbackInvoked); } diff --git a/tests/Fortify/FortifyServiceProviderTest.php b/tests/Fortify/FortifyServiceProviderTest.php index 11faf1e8b3..3a1a85cbc8 100644 --- a/tests/Fortify/FortifyServiceProviderTest.php +++ b/tests/Fortify/FortifyServiceProviderTest.php @@ -25,7 +25,9 @@ use Hypervel\Session\Store; use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Tests\Fortify\Fixtures\FixedClock; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Nyholm\Psr7\Response as PsrResponse; use OTPHP\TOTP; use Psr\Clock\ClockInterface; @@ -36,6 +38,8 @@ class FortifyServiceProviderTest extends TestCase { + use VerifiesDoubles; + public function testViewsCanBeCustomized(): void { Fortify::loginView(function () { @@ -67,10 +71,10 @@ public function toResponse(Request $request): Response public function testNamedViewsReceiveTheRequest(): void { - $factory = m::mock(ResponseFactory::class); - $factory->shouldReceive('view')->once()->with('auth.login', m::on( + $factory = Double::for(ResponseFactory::class); + $factory->expects('view')->with('auth.login', Argument::satisfies( static fn (array $parameters): bool => $parameters['request'] instanceof Request, - ))->andReturn(new HttpResponse('Login')); + ))->returns(new HttpResponse('Login')); $this->app->instance(ResponseFactory::class, $factory); Fortify::loginView('auth.login'); @@ -190,12 +194,12 @@ public function testPasskeySettingsAreComputedAgainAgainstTheRebuiltConfiguratio ]); $tracker = new ConfigMutationTracker; $tracker->observe($masterConfig); - $app = m::mock(Application::class)->makePartial(); - $app->shouldReceive('configurationIsCached')->andReturnFalse(); - $app->shouldReceive('make')->with('config')->andReturn($masterConfig); - $app->shouldReceive('make')->with(ConfigMutationTracker::class)->andReturn($tracker); + $app = Double::for(Application::class, override: true)->passthru(); + $app->allows('configurationIsCached')->returns(false); + $app->allows('make')->with('config')->returns($masterConfig); + $app->allows('make')->with(ConfigMutationTracker::class)->returns($tracker); - (new ReflectionMethod(FortifyServiceProvider::class, 'configurePasskeys'))->invoke(new FortifyServiceProvider($app)); + (new ReflectionMethod(FortifyServiceProvider::class, 'configurePasskeys'))->invoke(new FortifyServiceProvider($app->instance())); $this->assertSame('old.example.test', $masterConfig->get('passkeys.relying_party_id')); @@ -259,7 +263,7 @@ public function testRecoveryCodeGenerationCanBeCustomized(): void public function testActionsCanBeRegisteredWithNonClosureCallables(): void { - $creator = m::mock(CreatesNewUsers::class); + $creator = Double::for(CreatesNewUsers::class); Fortify::createUsersUsing(new class($creator) { public function __construct( diff --git a/tests/Fortify/NewPasswordControllerTest.php b/tests/Fortify/NewPasswordControllerTest.php index aa9673453e..a623c92f65 100644 --- a/tests/Fortify/NewPasswordControllerTest.php +++ b/tests/Fortify/NewPasswordControllerTest.php @@ -13,6 +13,8 @@ use Hypervel\Support\Facades\Event; use Hypervel\Support\Facades\Password; use Hypervel\Testbench\Attributes\WithMigration; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Mockery as m; use Workbench\App\Models\User; use Workbench\Database\Factories\UserFactory; @@ -21,6 +23,7 @@ class NewPasswordControllerTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; public function testTheNewPasswordViewIsReturned(): void { @@ -91,7 +94,7 @@ public function testPasswordResetCanFailWithJson(): void public function testPasswordCanBeResetWithCustomizedEmailAddressField(): void { $this->app->make('config')->set('fortify.email', 'emailAddress'); - Password::shouldReceive('broker')->andReturn($broker = m::mock(PasswordBroker::class)); + Password::shouldReceive('broker')->andReturn($broker = Double::for(PasswordBroker::class)); $user = User::forceCreate(UserFactory::new()->raw()); $rememberToken = $user->remember_token; @@ -101,7 +104,7 @@ public function testPasswordCanBeResetWithCustomizedEmailAddressField(): void ->once() ->with($user, m::type('array')); - $broker->shouldReceive('reset')->once()->andReturnUsing(function (array $input, callable $callback) use ($user): string { + $broker->expects('reset')->resolves(function (array $input, callable $callback) use ($user): string { $callback($user, 'password'); return Password::PASSWORD_RESET; diff --git a/tests/Fortify/PasswordResetLinkRequestControllerTest.php b/tests/Fortify/PasswordResetLinkRequestControllerTest.php index 167173906f..25ebcf614f 100644 --- a/tests/Fortify/PasswordResetLinkRequestControllerTest.php +++ b/tests/Fortify/PasswordResetLinkRequestControllerTest.php @@ -12,7 +12,8 @@ use Hypervel\Support\Facades\Password; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\Attributes\WithMigration; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Workbench\App\Models\User; use Workbench\Database\Factories\UserFactory; @@ -21,6 +22,7 @@ class PasswordResetLinkRequestControllerTest extends TestCase { use RefreshDatabase; + use VerifiesDoubles; public function testTheResetLinkRequestViewIsReturned(): void { @@ -76,9 +78,9 @@ public function testResetLinkRequestCanFailWithJson(): void public function testResetLinkCanBeSuccessfullyRequestedWithCustomizedEmailField(): void { $this->app->make('config')->set('fortify.email', 'emailAddress'); - Password::shouldReceive('broker')->andReturn($broker = m::mock(PasswordBroker::class)); + Password::shouldReceive('broker')->andReturn($broker = Double::for(PasswordBroker::class)); - $broker->shouldReceive('sendResetLink')->once()->andReturn(Password::RESET_LINK_SENT); + $broker->expects('sendResetLink')->returns(Password::RESET_LINK_SENT); $response = $this->from(url('/forgot-password')) ->post('/forgot-password', ['emailAddress' => 'taylor@laravel.com']); diff --git a/tests/Fortify/TwoFactorAuthenticationProviderTest.php b/tests/Fortify/TwoFactorAuthenticationProviderTest.php index d52d87df99..24ef75a487 100644 --- a/tests/Fortify/TwoFactorAuthenticationProviderTest.php +++ b/tests/Fortify/TwoFactorAuthenticationProviderTest.php @@ -11,12 +11,15 @@ use Hypervel\Fortify\TwoFactorAuthenticationProvider; use Hypervel\Tests\Fortify\Fixtures\FixedClock; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use OTPHP\TOTP; use OTPHP\TOTPInterface; class TwoFactorAuthenticationProviderTest extends TestCase { + use VerifiesDoubles; + private const int TIMESTAMP = 1234567890; private const string SECRET = 'JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP'; @@ -127,12 +130,12 @@ public function testReplayCacheKeyIncludesSecretAndCode(): void $secondKey = 'fortify.2fa_codes.' . hash('xxh128', $secondSecret . '|' . $code); $timecode = intdiv(self::TIMESTAMP, TOTPInterface::DEFAULT_PERIOD); $ttl = 90; - $cache = m::mock(CacheRepositoryContract::class); + $cache = Double::for(CacheRepositoryContract::class); $this->assertSame($code, $this->codeAt($secondSecret, self::TIMESTAMP)); $this->assertNotSame($firstKey, $secondKey); - $cache->shouldReceive('add')->once()->with($firstKey, $timecode, $ttl)->andReturnTrue(); - $cache->shouldReceive('add')->once()->with($secondKey, $timecode, $ttl)->andReturnTrue(); + $cache->expects('add')->with($firstKey, $timecode, $ttl)->returns(true); + $cache->expects('add')->with($secondKey, $timecode, $ttl)->returns(true); $provider = $this->provider(cache: $cache); @@ -166,11 +169,11 @@ public function testReplayCacheTtlCoversFullAcceptedWindow(): void foreach ([0 => 30, 1 => 90, 2 => 150] as $window => $ttl) { Features::twoFactorAuthentication(['window' => $window]); - $cache = m::mock(CacheRepositoryContract::class); + $cache = Double::for(CacheRepositoryContract::class); $key = 'fortify.2fa_codes.' . hash('xxh128', self::SECRET . '|' . $this->codeAt(self::SECRET, self::TIMESTAMP)); $timecode = intdiv(self::TIMESTAMP, TOTPInterface::DEFAULT_PERIOD); - $cache->shouldReceive('add')->once()->with($key, $timecode, $ttl)->andReturnTrue(); + $cache->expects('add')->with($key, $timecode, $ttl)->returns(true); $this->assertTrue($this->provider(cache: $cache)->verify(self::SECRET, $this->codeAt(self::SECRET, self::TIMESTAMP))); } diff --git a/tests/Foundation/Auth/EmailVerificationRequestTest.php b/tests/Foundation/Auth/EmailVerificationRequestTest.php index e1d816f29f..e528ae22fa 100644 --- a/tests/Foundation/Auth/EmailVerificationRequestTest.php +++ b/tests/Foundation/Auth/EmailVerificationRequestTest.php @@ -13,11 +13,14 @@ use Hypervel\Routing\Router; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Override; class EmailVerificationRequestTest extends TestCase { + use VerifiesDoubles; + #[Override] protected function defineRoutes(Router $router): void { @@ -31,8 +34,8 @@ protected function defineRoutes(Router $router): void public function testAuthorizeReturnsTrueWhenIdAndHashMatch(): void { $user = $this->mockUser(123, 'user@example.com'); - $user->shouldReceive('hasVerifiedEmail')->andReturn(false); - $user->shouldReceive('markEmailAsVerified')->once(); + $user->allows('hasVerifiedEmail')->returns(false); + $user->expects('markEmailAsVerified'); $this->actingAs($user) ->get('/email/verify/123/' . sha1('user@example.com')) @@ -62,8 +65,8 @@ public function testFulfillMarksEmailAsVerifiedAndDispatchesEvent(): void Event::fake([Verified::class]); $user = $this->mockUser(123, 'user@example.com'); - $user->shouldReceive('hasVerifiedEmail')->once()->andReturn(false); - $user->shouldReceive('markEmailAsVerified')->once(); + $user->expects('hasVerifiedEmail')->returns(false); + $user->expects('markEmailAsVerified'); $this->actingAs($user) ->get('/email/verify/123/' . sha1('user@example.com')) @@ -76,12 +79,12 @@ public function testFulfillDispatchesEventForUserUsingOnlyTheVerificationTrait() { Event::fake([Verified::class]); - $user = m::mock(User::class); - $user->shouldReceive('getKey')->andReturn(123); - $user->shouldReceive('getAuthIdentifier')->andReturn(123); - $user->shouldReceive('getEmailForVerification')->andReturn('user@example.com'); - $user->shouldReceive('hasVerifiedEmail')->once()->andReturn(false); - $user->shouldReceive('markEmailAsVerified')->once()->andReturn(true); + $user = Double::for(User::class); + $user->allows('getKey')->returns(123); + $user->allows('getAuthIdentifier')->returns(123); + $user->allows('getEmailForVerification')->returns('user@example.com'); + $user->expects('hasVerifiedEmail')->returns(false); + $user->expects('markEmailAsVerified')->returns(true); $this->assertNotInstanceOf(MustVerifyEmail::class, $user); @@ -103,8 +106,8 @@ static function (Verified $event) use (&$observedEvents): void { ); $user = $this->mockUser(123, 'user@example.com'); - $user->shouldReceive('hasVerifiedEmail')->once()->andReturn(false); - $user->shouldReceive('markEmailAsVerified')->once(); + $user->expects('hasVerifiedEmail')->returns(false); + $user->expects('markEmailAsVerified'); $this->actingAs($user) ->get('/email/verify/123/' . sha1('user@example.com')) @@ -118,8 +121,8 @@ public function testFulfillSkipsWhenAlreadyVerified(): void Event::fake([Verified::class]); $user = $this->mockUser(123, 'user@example.com'); - $user->shouldReceive('hasVerifiedEmail')->once()->andReturn(true); - $user->shouldNotReceive('markEmailAsVerified'); + $user->expects('hasVerifiedEmail')->returns(true); + $user->expects('markEmailAsVerified')->never(); $this->actingAs($user) ->get('/email/verify/123/' . sha1('user@example.com')) @@ -140,11 +143,15 @@ public function testRulesReturnsEmptyArray(): void */ private function mockUser(int|string $id, string $email): Authenticatable&MustVerifyEmail { - $user = m::mock(Authenticatable::class, MustVerifyEmail::class); - $user->shouldReceive('getKey')->andReturn($id); - $user->shouldReceive('getAuthIdentifier')->andReturn($id); - $user->shouldReceive('getEmailForVerification')->andReturn($email); + $user = Double::for(EmailVerificationUser::class); + $user->allows('getKey')->returns($id); + $user->allows('getAuthIdentifier')->returns($id); + $user->allows('getEmailForVerification')->returns($email); return $user; } } + +class EmailVerificationUser extends User implements MustVerifyEmail +{ +} diff --git a/tests/Foundation/Bootstrap/ProviderOrderingTest.php b/tests/Foundation/Bootstrap/ProviderOrderingTest.php index 3a7b3a42de..dd2bd28a6b 100644 --- a/tests/Foundation/Bootstrap/ProviderOrderingTest.php +++ b/tests/Foundation/Bootstrap/ProviderOrderingTest.php @@ -143,7 +143,6 @@ public function register(): void use Hypervel\Foundation\Bootstrap\RegisterProviders; use Hypervel\Support\ServiceProvider; use Hypervel\Testbench\TestCase; -use Mockery as m; use ReflectionMethod; class ProviderOrderingTest extends TestCase @@ -410,19 +409,7 @@ public function testDefaultPriorityIsZero(): void */ protected function createAppWithProviders(array $configProviders, array $discoveredProviders): Application { - $mergedProviders = null; - - $config = m::mock(Repository::class); - $config->shouldReceive('array') - ->with('app.providers') - ->andReturnUsing(function () use ($configProviders, &$mergedProviders) { - return $mergedProviders ?? $configProviders; - }); - $config->shouldReceive('set') - ->with('app.providers', m::type('array')) - ->andReturnUsing(function (string $key, array $value) use (&$mergedProviders) { - $mergedProviders = $value; - }); + $config = new Repository(['app' => ['providers' => $configProviders]]); // Use an Application subclass that returns our test discovered providers $app = new TestApplication($this->app->basePath(), $discoveredProviders); diff --git a/tests/Foundation/Bootstrap/RegisterFacadesTest.php b/tests/Foundation/Bootstrap/RegisterFacadesTest.php index 3248f42ae2..91a8ae9298 100644 --- a/tests/Foundation/Bootstrap/RegisterFacadesTest.php +++ b/tests/Foundation/Bootstrap/RegisterFacadesTest.php @@ -9,26 +9,27 @@ use Hypervel\Foundation\Bootstrap\RegisterFacades; use Hypervel\Foundation\PackageManifest; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class RegisterFacadesTest extends TestCase { + use VerifiesDoubles; + // REMOVED: Laravel's AliasLoader real-time facade path; Hypervel supports // only explicit facade aliases. public function testRegisterAliases(): void { - $config = m::mock(Repository::class); - $config->shouldReceive('array') + $config = Double::for(Repository::class); + $config->expects('array') ->with('app.aliases') - ->once() - ->andReturn([ + ->returns([ 'FooAlias' => 'FooClass', ]); - $manifest = m::mock(PackageManifest::class); - $manifest->shouldReceive('aliases') - ->once() - ->andReturn([ + $manifest = Double::for(PackageManifest::class); + $manifest->expects('aliases') + ->returns([ 'TestAlias' => 'TestClass', ]); diff --git a/tests/Foundation/Bootstrap/RegisterProvidersTest.php b/tests/Foundation/Bootstrap/RegisterProvidersTest.php index 03b3519246..38a607750c 100644 --- a/tests/Foundation/Bootstrap/RegisterProvidersTest.php +++ b/tests/Foundation/Bootstrap/RegisterProvidersTest.php @@ -10,30 +10,32 @@ use Hypervel\Foundation\PackageManifest; use Hypervel\Support\ServiceProvider; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; class RegisterProvidersTest extends TestCase { + use VerifiesDoubles; + public function testRegisterProviders(): void { $mergedProviders = null; - $config = m::mock(Repository::class); - $config->shouldReceive('array') - ->twice() + $config = Double::for(Repository::class); + $config->expects('array') + ->times(2) ->with('app.providers') - ->andReturnUsing(function () use (&$mergedProviders) { + ->resolves(function () use (&$mergedProviders) { return $mergedProviders ?? [TestTwoServiceProvider::class]; }); - $config->shouldReceive('set') - ->with('app.providers', m::type('array')) - ->once() - ->andReturnUsing(function (string $key, array $value) use (&$mergedProviders) { + $config->expects('set') + ->with('app.providers', Argument::type('array')) + ->resolves(function (string $key, array $value) use (&$mergedProviders) { $mergedProviders = $value; }); - $manifest = m::mock(PackageManifest::class); - $manifest->shouldReceive('providers') - ->once() - ->andReturn([ + $manifest = Double::for(PackageManifest::class); + $manifest->expects('providers') + ->returns([ TestOneServiceProvider::class, ]); diff --git a/tests/Foundation/Configuration/MiddlewareTest.php b/tests/Foundation/Configuration/MiddlewareTest.php index 4f4e15dd2f..63d33c1062 100644 --- a/tests/Foundation/Configuration/MiddlewareTest.php +++ b/tests/Foundation/Configuration/MiddlewareTest.php @@ -19,15 +19,19 @@ use Hypervel\Http\Middleware\TrustHosts; use Hypervel\Http\Middleware\TrustProxies; use Hypervel\Http\Request; +use Hypervel\Routing\Router; use Hypervel\Session\Middleware\AuthenticateSession; use Hypervel\Session\Middleware\StartSession; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionClass; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; class MiddlewareTest extends TestCase { + use VerifiesDoubles; + public function testConvertEmptyStringsToNull(): void { $configuration = new Middleware; @@ -595,8 +599,8 @@ public function testStatefulApiAddsEnsureFrontendRequestsAreStateful(): void public function testDefaultMiddlewarePriority(): void { $kernel = new \Hypervel\Foundation\Http\Kernel( - m::mock(Application::class), - m::mock(\Hypervel\Routing\Router::class) + Double::for(Application::class, override: true)->instance(), + Double::for(Router::class) ); $reflection = new ReflectionClass($kernel); @@ -621,8 +625,8 @@ public function testDefaultMiddlewarePriority(): void public function testWithMiddlewareAppliesPriorityToKernel(): void { $kernel = new \Hypervel\Foundation\Http\Kernel( - m::mock(Application::class), - m::mock(\Hypervel\Routing\Router::class)->shouldIgnoreMissing() + Double::for(Application::class, override: true)->instance(), + Double::for(Router::class) ); $middleware = new Middleware; @@ -647,8 +651,8 @@ public function testWithMiddlewareAppliesPriorityToKernel(): void public function testWithMiddlewareAppliesAppendsToPriority(): void { $kernel = new \Hypervel\Foundation\Http\Kernel( - m::mock(Application::class), - m::mock(\Hypervel\Routing\Router::class)->shouldIgnoreMissing() + Double::for(Application::class, override: true)->instance(), + Double::for(Router::class) ); $middleware = new Middleware; @@ -674,8 +678,8 @@ public function testWithMiddlewareAppliesAppendsToPriority(): void public function testWithMiddlewareAppliesPrependsToPriority(): void { $kernel = new \Hypervel\Foundation\Http\Kernel( - m::mock(Application::class), - m::mock(\Hypervel\Routing\Router::class)->shouldIgnoreMissing() + Double::for(Application::class, override: true)->instance(), + Double::for(Router::class) ); $middleware = new Middleware; @@ -701,8 +705,8 @@ public function testWithMiddlewareAppliesPrependsToPriority(): void public function testWithMiddlewareAppliesGlobalGroupsAndAliasesToKernel(): void { $kernel = new \Hypervel\Foundation\Http\Kernel( - m::mock(Application::class), - m::mock(\Hypervel\Routing\Router::class)->shouldIgnoreMissing() + Double::for(Application::class, override: true)->instance(), + Double::for(Router::class) ); $middleware = new Middleware; diff --git a/tests/Foundation/Console/AboutCommandTest.php b/tests/Foundation/Console/AboutCommandTest.php index f6a9dddb45..e9a40f1d93 100644 --- a/tests/Foundation/Console/AboutCommandTest.php +++ b/tests/Foundation/Console/AboutCommandTest.php @@ -8,11 +8,14 @@ use Hypervel\Foundation\Console\AboutCommand; use Hypervel\Support\Composer; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; class AboutCommandTest extends TestCase { + use VerifiesDoubles; + /** * @param Closure(bool):mixed $format */ @@ -45,7 +48,7 @@ public static function jsonDataProvider(): iterable public function testItReportsNoPhpFilesWhenGlobCannotEnumerateThePath(): void { - $command = new TestableAboutCommand(m::mock(Composer::class)); + $command = new TestableAboutCommand(Double::for(Composer::class)); $this->assertFalse($command->hasPhpFiles(str_repeat('a', PHP_MAXPATHLEN + 1))); } diff --git a/tests/Foundation/Console/KernelEventReroutingTest.php b/tests/Foundation/Console/KernelEventReroutingTest.php index 64a63ea2b8..5610ef6e57 100644 --- a/tests/Foundation/Console/KernelEventReroutingTest.php +++ b/tests/Foundation/Console/KernelEventReroutingTest.php @@ -11,7 +11,8 @@ use Hypervel\Contracts\Events\Dispatcher; use Hypervel\Foundation\Console\Kernel; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; use Symfony\Component\Console\Command\Command as SymfonyCommand; use Symfony\Component\Console\ConsoleEvents; @@ -23,6 +24,8 @@ class KernelEventReroutingTest extends TestCase { + use VerifiesDoubles; + public function testRerouteSymfonyCommandEventsWiresDispatcherToExistingArtisan(): void { $kernel = $this->app->make(KernelContract::class); @@ -81,10 +84,10 @@ public function testRerouteSymfonyCommandEventsWiresDispatcherBeforeArtisanCreat public function testReroutedEventsAreNotDispatchedWithoutListeners(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners')->once()->with(CommandStarting::class)->andReturnFalse(); - $events->shouldReceive('hasListeners')->once()->with(CommandFinished::class)->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners')->with(CommandStarting::class)->returns(false); + $events->expects('hasListeners')->with(CommandFinished::class)->returns(false); + $events->expects('dispatch')->never(); $kernel = new Kernel($this->app, $events); $kernel->rerouteSymfonyCommandEvents(); diff --git a/tests/Foundation/Console/KernelTerminateTest.php b/tests/Foundation/Console/KernelTerminateTest.php index 77c4cdefd2..a55a84bf24 100644 --- a/tests/Foundation/Console/KernelTerminateTest.php +++ b/tests/Foundation/Console/KernelTerminateTest.php @@ -11,7 +11,8 @@ use Hypervel\Foundation\Events\Terminating; use Hypervel\Support\CarbonImmutable; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -21,6 +22,8 @@ class KernelTerminateTest extends TestCase { + use VerifiesDoubles; + public function testTerminateDispatchesTerminatingEventAndAppTerminateInOrder(): void { $called = []; @@ -53,17 +56,14 @@ public function testTerminateDispatchesTerminatingEventEvenWithoutHandle(): void public function testTerminateDoesNotConstructOrDispatchAnEventWithoutListeners(): void { - $events = m::mock(Dispatcher::class); - $events->shouldReceive('hasListeners') - ->once() + $events = Double::for(Dispatcher::class); + $events->expects('hasListeners') ->with(Terminating::class) - ->andReturnFalse(); - $events->shouldNotReceive('dispatch'); + ->returns(false); + $events->expects('dispatch')->never(); $kernel = new ConsoleKernel($this->app, $events); $kernel->terminate(new StringInput(''), 0); - - $this->addToAssertionCount(1); } public function testCommandStartedAtIsNullBeforeHandle(): void diff --git a/tests/Foundation/Console/KernelTest.php b/tests/Foundation/Console/KernelTest.php index 0c813ecf74..0b792f87ba 100644 --- a/tests/Foundation/Console/KernelTest.php +++ b/tests/Foundation/Console/KernelTest.php @@ -22,7 +22,9 @@ use Hypervel\Foundation\Events\Terminating; use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use ReflectionMethod; use ReflectionProperty; use RuntimeException; @@ -38,6 +40,8 @@ class KernelTest extends TestCase { + use VerifiesDoubles; + protected function useTokyoApplicationTimezone(ApplicationContract $app): void { $app->make('config')->set('app.timezone', 'Asia/Tokyo'); @@ -45,9 +49,9 @@ protected function useTokyoApplicationTimezone(ApplicationContract $app): void public function testHandleCatchesExceptionsAndReturnsOne(): void { - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once(); - $handler->shouldReceive('renderForConsole')->once(); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report'); + $handler->expects('renderForConsole'); $this->app->instance(ExceptionHandlerContract::class, $handler); $kernel = new class($this->app, $this->app->make('events')) extends Kernel { @@ -73,9 +77,9 @@ public function testHandleRetainsTheOriginalExceptionWhenReportingFails(): void $original = new RuntimeException('Bootstrap failed'); $reportingFailure = new RuntimeException('Reporting failed'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->with($original, [])->andThrow($reportingFailure); - $handler->shouldNotReceive('renderForConsole'); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report')->with($original, [])->throws($reportingFailure); + $handler->expects('renderForConsole')->never(); $this->app->instance(ExceptionHandlerContract::class, $handler); $kernel = new class($this->app, $this->app->make('events'), $original) extends Kernel { @@ -107,8 +111,9 @@ public function bootstrap(): void public function testHandlePreservesCancellationWithoutReportingOrRenderingIt(): void { $cancellation = new CanceledException('canceled'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldNotReceive('report', 'renderForConsole'); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report')->never(); + $handler->expects('renderForConsole')->never(); $this->app->instance(ExceptionHandlerContract::class, $handler); $kernel = new class($this->app, $this->app->make('events'), $cancellation) extends Kernel { @@ -143,15 +148,12 @@ public function testBootstrapWithoutBootingProvidersSkipsBootProviders(): void $kernel = $this->app->make(KernelContract::class); // Replace the app with a spy that captures what bootstrappers are used. - $app = m::mock($this->app)->makePartial(); - $app->shouldReceive('bootstrapWith')->once()->with(m::on(function (array $bootstrappers) use (&$bootstrappedWith) { - $bootstrappedWith = $bootstrappers; - return true; - })); + $app = Double::for($this->app, override: true)->passthru(); + $app->expects('bootstrapWith')->with(Argument::capture($bootstrappedWith)); // Use reflection to replace the app on the kernel. $reflection = new ReflectionProperty($kernel, 'app'); - $reflection->setValue($kernel, $app); + $reflection->setValue($kernel, $app->instance()); $kernel->bootstrapWithoutBootingProviders(); @@ -365,8 +367,8 @@ public function testReportExceptionDelegatesToExceptionHandler(): void { $exception = new RuntimeException('Test exception'); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->with($exception, []); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report')->with($exception, []); $this->app->instance(ExceptionHandlerContract::class, $handler); $kernel = new Kernel($this->app, $this->app->make('events')); @@ -380,8 +382,8 @@ public function testRenderExceptionDelegatesToExceptionHandler(): void $exception = new RuntimeException('Test exception'); $output = new BufferedOutput; - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('renderForConsole')->once()->with($output, $exception); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('renderForConsole')->with($output, $exception); $this->app->instance(ExceptionHandlerContract::class, $handler); $kernel = new Kernel($this->app, $this->app->make('events')); @@ -397,8 +399,8 @@ public function testRenderThrowableUsesConsoleErrorOutput(): void $errorOutput = new BufferedOutput; $output->setErrorOutput($errorOutput); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('renderForConsole')->once()->with($errorOutput, $exception); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('renderForConsole')->with($errorOutput, $exception); $this->app->instance(ExceptionHandlerContract::class, $handler); $kernel = new Kernel($this->app, $this->app->make('events')); @@ -411,13 +413,13 @@ public function testHandleWithNullOutputPreservesOriginalThrowable(): void { $reportedException = null; - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->andReturnUsing(function (RuntimeException $exception) use (&$reportedException): void { + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report')->resolves(function (RuntimeException $exception) use (&$reportedException): void { $reportedException = $exception; }); - $handler->shouldReceive('renderForConsole')->once()->with( - m::on(fn (OutputInterface $output): bool => ! $output instanceof ConsoleOutputInterface), - m::on(function (RuntimeException $exception) use (&$reportedException): bool { + $handler->expects('renderForConsole')->with( + Argument::satisfies(fn (OutputInterface $output): bool => ! $output instanceof ConsoleOutputInterface), + Argument::satisfies(function (RuntimeException $exception) use (&$reportedException): bool { return $exception === $reportedException && $exception->getMessage() === 'Bootstrap failed'; }), ); diff --git a/tests/Foundation/Console/VendorPublishCommandTest.php b/tests/Foundation/Console/VendorPublishCommandTest.php index fbcddf4536..12c1ea351e 100644 --- a/tests/Foundation/Console/VendorPublishCommandTest.php +++ b/tests/Foundation/Console/VendorPublishCommandTest.php @@ -13,7 +13,8 @@ use Hypervel\Support\ServiceProvider; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Symfony\Component\Console\Application as ConsoleApplication; @@ -21,6 +22,8 @@ class VendorPublishCommandTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $filesystem; protected string $sourceDir; @@ -135,8 +138,8 @@ public function testSkippedFileUsesConfiguredPathWhenDestinationDisappears(): vo file_put_contents($source, ' $destination]; - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('exists')->once()->with($destination)->andReturnTrue(); + $files = Double::for(new Filesystem)->passthru(); + $files->expects('exists')->with($destination)->returns(true); $tester = $this->commandTester($files); $this->assertSame(0, $tester->execute(['--provider' => TestPublishProvider::class])); @@ -541,8 +544,8 @@ public function testCopyFailureDoesNotReportStatusOrDispatchPublishedEvent(): vo file_put_contents($source, ' $destination]; - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('copy')->once()->with($source, $destination)->andReturnFalse(); + $files = Double::for(new Filesystem)->passthru(); + $files->expects('copy')->with($source, $destination)->returns(false); $tester = $this->commandTester($files); try { diff --git a/tests/Foundation/Console/ViewCacheCommandTest.php b/tests/Foundation/Console/ViewCacheCommandTest.php index 919db7da6f..64c6d1f7a1 100644 --- a/tests/Foundation/Console/ViewCacheCommandTest.php +++ b/tests/Foundation/Console/ViewCacheCommandTest.php @@ -11,10 +11,13 @@ use Hypervel\Tests\TestCase; use Hypervel\View\Factory; use Hypervel\View\ViewFinderInterface; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ViewCacheCommandTest extends TestCase { + use VerifiesDoubles; + protected Filesystem $files; protected string $tempDir; @@ -42,8 +45,10 @@ public function testPathsCollapseNestedRootsWithoutConflatingPrefixSiblings(): v $nested = $views . '/nested'; $viewsAdmin = $this->tempDir . '/views-admin'; $missing = $this->tempDir . '/missing'; + $package = $this->tempDir . '/package'; $this->files->ensureDirectoryExists($nested); $this->files->ensureDirectoryExists($viewsAdmin); + $this->files->ensureDirectoryExists($package); $command = $this->commandWithPaths([ $views, @@ -52,9 +57,9 @@ public function testPathsCollapseNestedRootsWithoutConflatingPrefixSiblings(): v $viewsAdmin, $missing . DIRECTORY_SEPARATOR, $missing, - ]); + ], ['package' => [$package]]); - $this->assertSame([$views, $viewsAdmin, $missing], $command->viewPaths()); + $this->assertSame([$views, $viewsAdmin, $missing, $package], $command->viewPaths()); } public function testPathsRetainFilesystemRoot(): void @@ -66,20 +71,23 @@ public function testPathsRetainFilesystemRoot(): void $this->assertSame([DIRECTORY_SEPARATOR], $command->viewPaths()); } - protected function commandWithPaths(array $paths): TestViewCacheCommand + /** + * Create a command with the given view roots and namespace hints. + */ + protected function commandWithPaths(array $paths, array $hints = []): TestViewCacheCommand { - $finder = m::mock(ViewFinderInterface::class); - $finder->shouldReceive('getPaths')->once()->andReturn($paths); - $finder->shouldReceive('getHints')->once()->andReturn([]); + $finder = Double::for(ViewFinderInterface::class); + $finder->expects('getPaths')->returns($paths); + $finder->expects('getHints')->returns($hints); - $factory = m::mock(Factory::class); - $factory->shouldReceive('getFinder')->once()->andReturn($finder); + $factory = Double::for(Factory::class); + $factory->expects('getFinder')->returns($finder); - $application = m::mock(Application::class); - $application->shouldReceive('make')->once()->with('view')->andReturn($factory); + $application = Double::for(Application::class, override: true); + $application->expects('make')->with('view')->returns($factory); $command = new TestViewCacheCommand; - $command->setHypervel($application); + $command->setHypervel($application->instance()); return $command; } diff --git a/tests/Foundation/DeferredCallbacksTest.php b/tests/Foundation/DeferredCallbacksTest.php index e74cbd8707..7d302595aa 100644 --- a/tests/Foundation/DeferredCallbacksTest.php +++ b/tests/Foundation/DeferredCallbacksTest.php @@ -14,12 +14,15 @@ use Hypervel\Support\Defer\DeferredCallbackCollection; use Hypervel\Support\Facades\Route; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\DataProvider; use Swoole\Coroutine\CanceledException; class DeferredCallbacksTest extends TestCase { + use VerifiesDoubles; + /** * Set up the test environment. */ @@ -111,8 +114,8 @@ public function testJobLifecycleOwnsCallbacksRegisteredByNestedCommand(): void $this->assertSame([], DeferredCallbacksTestState::$calls); - $job = m::mock(Job::class); - $job->shouldReceive('hasFailed')->andReturnFalse(); + $job = Double::for(Job::class); + $job->allows('hasFailed')->returns(false); $this->app->make(Dispatcher::class)->dispatch( new JobAttempted('database', $job, null) @@ -132,7 +135,7 @@ public function testCanceledJobAttemptSkipsEveryDeferredCallback(): void })->always(); $this->app->make(Dispatcher::class)->dispatch( - new JobAttempted('database', m::mock(Job::class), new CanceledException, canceled: true) + new JobAttempted('database', Double::for(Job::class), new CanceledException, canceled: true) ); $this->assertSame([], DeferredCallbacksTestState::$calls); @@ -140,8 +143,8 @@ public function testCanceledJobAttemptSkipsEveryDeferredCallback(): void public function testJobWithoutDeferredCallbacksDoesNotResolveTheCollection(): void { - $job = m::mock(Job::class); - $job->shouldNotReceive('hasFailed'); + $job = Double::for(Job::class); + $job->expects('hasFailed')->never(); $this->app->make(Dispatcher::class)->dispatch( new JobAttempted('database', $job, null) @@ -157,8 +160,8 @@ public function testJobAttemptedRunsDeferredCallbacksForSuccessfulJobs(string $c DeferredCallbacksTestState::record('job'); }); - $job = m::mock(Job::class); - $job->shouldReceive('hasFailed')->andReturnFalse(); + $job = Double::for(Job::class); + $job->allows('hasFailed')->returns(false); $this->app->make(Dispatcher::class)->dispatch( new JobAttempted($connection, $job, null) @@ -190,8 +193,8 @@ public function testJobAttemptedSkipsFailedJobsAndSyncConnectionsUnlessAlwaysTru DeferredCallbacksTestState::record('always'); }, always: true); - $failedJob = m::mock(Job::class); - $failedJob->shouldReceive('hasFailed')->andReturnTrue(); + $failedJob = Double::for(Job::class); + $failedJob->allows('hasFailed')->returns(true); $this->app->make(Dispatcher::class)->dispatch( new JobAttempted('database', $failedJob, null) @@ -205,8 +208,8 @@ public function testJobAttemptedSkipsFailedJobsAndSyncConnectionsUnlessAlwaysTru DeferredCallbacksTestState::record('sync'); }); - $syncJob = m::mock(Job::class); - $syncJob->shouldReceive('hasFailed')->never(); + $syncJob = Double::for(Job::class); + $syncJob->expects('hasFailed')->never(); $this->app->make(Dispatcher::class)->dispatch( new JobAttempted('sync', $syncJob, null) diff --git a/tests/Foundation/Exceptions/Renderer/ExceptionTest.php b/tests/Foundation/Exceptions/Renderer/ExceptionTest.php index 45dde4a7ae..83edc91dec 100644 --- a/tests/Foundation/Exceptions/Renderer/ExceptionTest.php +++ b/tests/Foundation/Exceptions/Renderer/ExceptionTest.php @@ -10,17 +10,20 @@ use Hypervel\Foundation\Exceptions\Renderer\Listener; use Hypervel\Http\Request; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\ErrorHandler\Exception\FlattenException; class ExceptionTest extends TestCase { + use VerifiesDoubles; + public function testApplicationQueriesPreserveBindingText(): void { - $connection = m::mock(Connection::class); - $connection->shouldReceive('getName')->once()->andReturn(null); - $connection->shouldReceive('prepareBindings')->once()->andReturnUsing(fn (array $bindings): array => $bindings); + $connection = Double::for(Connection::class); + $connection->expects('getName')->returns(null); + $connection->expects('prepareBindings')->resolves(fn (array $bindings): array => $bindings); $listener = new Listener; $listener->onQueryExecuted(new QueryExecuted( diff --git a/tests/Foundation/Exceptions/Renderer/FrameTest.php b/tests/Foundation/Exceptions/Renderer/FrameTest.php index 8ad33849a9..9c4d0b85e8 100644 --- a/tests/Foundation/Exceptions/Renderer/FrameTest.php +++ b/tests/Foundation/Exceptions/Renderer/FrameTest.php @@ -9,7 +9,6 @@ use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Di\Fixtures\ProxySources; use Hypervel\Tests\TestCase; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use Symfony\Component\ErrorHandler\Exception\FlattenException; @@ -137,7 +136,7 @@ public function testGeneratedProxyFramesAreClassifiedByTheirSourceFile(): void (new Filesystem)->put($proxyFile, ' __FILE__], function () use ($proxyFile): void { - $frame = new Frame(m::mock(FlattenException::class), [], ['file' => $proxyFile, 'line' => 10], $this->directory); + $frame = new Frame(new FlattenException, [], ['file' => $proxyFile, 'line' => 10], $this->directory); $this->assertTrue($frame->isFromVendor()); $this->assertSame(basename($proxyFile), $frame->file()); diff --git a/tests/Foundation/Exceptions/Renderer/ListenerContextIsolationTest.php b/tests/Foundation/Exceptions/Renderer/ListenerContextIsolationTest.php index 346b84fcf4..32b56a8546 100644 --- a/tests/Foundation/Exceptions/Renderer/ListenerContextIsolationTest.php +++ b/tests/Foundation/Exceptions/Renderer/ListenerContextIsolationTest.php @@ -8,12 +8,15 @@ use Hypervel\Database\Events\QueryExecuted; use Hypervel\Foundation\Exceptions\Renderer\Listener; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use function Hypervel\Coroutine\parallel; class ListenerContextIsolationTest extends TestCase { + use VerifiesDoubles; + public function testQueriesAreIsolatedBetweenCoroutines(): void { $results = parallel([ @@ -36,9 +39,9 @@ public function testQueriesAreIsolatedBetweenCoroutines(): void private function recordQueries(string $connectionName, array $queries): array { $listener = new Listener; - $connection = m::mock(Connection::class); - $connection->shouldReceive('getName')->andReturn($connectionName); - $connection->shouldReceive('prepareBindings')->andReturn([]); + $connection = Double::for(Connection::class); + $connection->allows('getName')->returns($connectionName); + $connection->allows('prepareBindings')->returns([]); foreach ($queries as $index => $query) { $listener->onQueryExecuted( @@ -46,6 +49,9 @@ private function recordQueries(string $connectionName, array $queries): array ); } + // Interleave the stored queries before reading them back. + usleep(5000); + return [ 'count' => count($listener->queries()), 'sqls' => array_column($listener->queries(), 'sql'), diff --git a/tests/Foundation/FoundationApplicationTest.php b/tests/Foundation/FoundationApplicationTest.php index 9842f3aff0..e7ea7ef888 100644 --- a/tests/Foundation/FoundationApplicationTest.php +++ b/tests/Foundation/FoundationApplicationTest.php @@ -24,8 +24,9 @@ use Hypervel\Support\Testing\Fakes\EventFake; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; use Psr\Log\LoggerInterface; use RuntimeException; @@ -36,6 +37,8 @@ class FoundationApplicationTest extends TestCase { + use VerifiesDoubles; + protected ?string $namespaceApplicationPath = null; protected ?string $cacheApplicationPath = null; @@ -58,9 +61,9 @@ protected function tearDown(): void public function testSetLocaleSetsLocaleAndFiresLocaleChangedEvent(): void { $events = new EventFake(new EventDispatcher); - $translator = m::mock(TranslatorContract::class); - $translator->expects('getLocale')->andReturn('bar')->ordered(); - $translator->expects('setLocale')->with('foo')->ordered()->andReturnUsing(function () use ($events): void { + $translator = Double::for(TranslatorContract::class); + $translator->expects('getLocale')->returns('bar')->ordered(); + $translator->expects('setLocale')->with('foo')->ordered()->resolves(function () use ($events): void { $events->assertNothingDispatched(); }); $config = new Repository(['app' => ['locale' => 'en']]); @@ -83,12 +86,12 @@ public function testSetLocaleSetsLocaleAndFiresLocaleChangedEvent(): void public function testSetLocaleDoesNotDispatchWhenLocaleEventHasNoListeners(): void { - $translator = m::mock(TranslatorContract::class); - $translator->expects('getLocale')->andReturn('bar'); + $translator = Double::for(TranslatorContract::class); + $translator->expects('getLocale')->returns('bar'); $translator->expects('setLocale')->with('foo'); - $events = m::mock(DispatcherContract::class); - $events->expects('hasListeners')->with(LocaleUpdated::class)->andReturn(false); - $events->shouldReceive('dispatch')->never(); + $events = Double::for(DispatcherContract::class); + $events->expects('hasListeners')->with(LocaleUpdated::class)->returns(false); + $events->expects('dispatch')->never(); $app = new Application; $app->singleton('translator', fn (): TranslatorContract => $translator); @@ -99,7 +102,7 @@ public function testSetLocaleDoesNotDispatchWhenLocaleEventHasNoListeners(): voi public function testSetFallbackLocaleSetsTranslatorFallback(): void { - $translator = m::mock(TranslatorContract::class); + $translator = Double::for(TranslatorContract::class); $translator->expects('setFallback')->with('fr'); $config = new Repository(['app' => ['fallback_locale' => 'en']]); @@ -124,8 +127,8 @@ public function testLoggerInterfaceResolvesAfterFacadesAreRegisteredBeforeConfig ], ])); - $manifest = m::mock(PackageManifest::class); - $manifest->expects('aliases')->andReturn([]); + $manifest = Double::for(PackageManifest::class); + $manifest->expects('aliases')->returns([]); $app->singleton(PackageManifest::class, fn (): PackageManifest => $manifest); (new RegisterFacades)->bootstrap($app); @@ -139,8 +142,8 @@ public function testLoggerInterfaceResolvesAfterFacadesAreRegisteredBeforeConfig public function testGetLocaleReadsFromTranslator(): void { - $translator = m::mock(TranslatorContract::class); - $translator->expects('getLocale')->andReturn('en'); + $translator = Double::for(TranslatorContract::class); + $translator->expects('getLocale')->returns('en'); $app = new Application; $app->singleton('translator', fn (): TranslatorContract => $translator); @@ -150,8 +153,8 @@ public function testGetLocaleReadsFromTranslator(): void public function testGetFallbackLocaleReadsFromTranslator(): void { - $translator = m::mock(TranslatorContract::class); - $translator->expects('getFallback')->andReturn('en'); + $translator = Double::for(TranslatorContract::class); + $translator->expects('getFallback')->returns('en'); $app = new Application; $app->singleton('translator', fn (): TranslatorContract => $translator); @@ -537,7 +540,7 @@ public function testBootResolvesTheBoundHttpKernelBeforeBootingCallbacks(): void $application->singleton(HttpKernelContract::class, function () use (&$events): HttpKernelContract { $events[] = 'kernel'; - return m::mock(HttpKernelContract::class); + return Double::for(HttpKernelContract::class); }); $application->booting(function () use (&$events): void { $events[] = 'booting'; diff --git a/tests/Foundation/FoundationFileBasedMaintenanceModeTest.php b/tests/Foundation/FoundationFileBasedMaintenanceModeTest.php index dd254a7641..ba91e9cea9 100644 --- a/tests/Foundation/FoundationFileBasedMaintenanceModeTest.php +++ b/tests/Foundation/FoundationFileBasedMaintenanceModeTest.php @@ -10,12 +10,15 @@ use Hypervel\Foundation\WorkerCachedMaintenanceMode; use Hypervel\Support\Json; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use RuntimeException; class FoundationFileBasedMaintenanceModeTest extends TestCase { + use VerifiesDoubles; + protected function tearDown(): void { @unlink(storage_path('framework/down')); @@ -73,10 +76,10 @@ public function testDataReturnsEmptyPayloadWhenFileDoesNotExist(): void public function testCachedActivityReturnsFalseWhenFileDisappearsDuringRead(): void { $path = storage_path('framework/down'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->with($path)->andReturn(true, false); - $files->shouldReceive('get')->once()->with($path) - ->andThrow(new FileNotFoundException('removed')); + $files = Double::for(Filesystem::class); + $files->allows('exists')->with($path)->returns(true, false); + $files->expects('get')->with($path) + ->throws(new FileNotFoundException('removed')); $mode = new WorkerCachedMaintenanceMode(new FileBasedMaintenanceMode($files)); @@ -88,9 +91,9 @@ public function testDataRethrowsReadFailureWhenFileStillExists(): void { $path = storage_path('framework/down'); $exception = new FileNotFoundException('unreadable'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->once()->with($path)->andReturnTrue(); - $files->shouldReceive('get')->once()->with($path)->andThrow($exception); + $files = Double::for(Filesystem::class); + $files->expects('exists')->with($path)->returns(true); + $files->expects('get')->with($path)->throws($exception); try { (new FileBasedMaintenanceMode($files))->data(); @@ -127,11 +130,10 @@ public function testActivatePreservesPreviousPayloadWhenPublicationFails(): void $path = storage_path('framework/down'); file_put_contents($path, '{"status":503}'); - $files = m::mock(Filesystem::class)->makePartial(); - $files->shouldReceive('replace') - ->once() + $files = Double::for(new Filesystem)->passthru(); + $files->expects('replace') ->with($path, "{\n \"status\": 418\n}") - ->andThrow($exception = new RuntimeException('publication failed')); + ->throws($exception = new RuntimeException('publication failed')); try { (new FileBasedMaintenanceMode($files))->activate(['status' => 418]); @@ -207,9 +209,9 @@ public function testActivateRejectsOneLevelOverTheMaximumNestingDepth(): void public function testDeactivateFailsWhenDeleteReturnsFalseAndFileRemains(): void { $path = storage_path('framework/down'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->twice()->with($path)->andReturnTrue(); - $files->shouldReceive('delete')->once()->with($path)->andReturnFalse(); + $files = Double::for(Filesystem::class); + $files->expects('exists')->times(2)->with($path)->returns(true); + $files->expects('delete')->with($path)->returns(false); $this->expectException(RuntimeException::class); $this->expectExceptionMessageIs("Unable to remove the maintenance mode file [{$path}]."); @@ -220,9 +222,9 @@ public function testDeactivateFailsWhenDeleteReturnsFalseAndFileRemains(): void public function testDeactivateSucceedsWhenAnotherOwnerRemovesTheFile(): void { $path = storage_path('framework/down'); - $files = m::mock(Filesystem::class); - $files->shouldReceive('exists')->twice()->with($path)->andReturn(true, false); - $files->shouldReceive('delete')->once()->with($path)->andReturnFalse(); + $files = Double::for(Filesystem::class); + $files->expects('exists')->times(2)->with($path)->returns(true, false); + $files->expects('delete')->with($path)->returns(false); (new FileBasedMaintenanceMode($files))->deactivate(); diff --git a/tests/Foundation/FoundationHelpersTest.php b/tests/Foundation/FoundationHelpersTest.php index f165b03c34..45fd7e9e2a 100644 --- a/tests/Foundation/FoundationHelpersTest.php +++ b/tests/Foundation/FoundationHelpersTest.php @@ -21,7 +21,9 @@ use Hypervel\Support\Facades\Date; use Hypervel\Support\Facades\Event; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use Psr\Log\LoggerInterface; use stdClass; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; @@ -47,6 +49,8 @@ enum UnitEnum class FoundationHelpersTest extends TestCase { + use VerifiesDoubles; + public function testAppPathUsesTheConfiguredApplicationDirectory(): void { $this->assertSame($this->app->basePath('app'), app_path()); @@ -247,7 +251,7 @@ public function testOldReturnsNonStringInput(): void public function testInfoWritesToTheLogger(): void { - $logger = m::mock(LoggerInterface::class); + $logger = Double::for(LoggerInterface::class); $logger->expects('info')->with('User login attempt failed.', ['id' => 1]); $this->app->instance(LoggerInterface::class, $logger); @@ -257,12 +261,8 @@ public function testInfoWritesToTheLogger(): void public function testInfoAddsTheCallerLocationToTheContext(): void { $loggedContext = null; - $logger = m::mock(LoggerInterface::class); - $logger->expects('info')->withArgs(function (string $message, array $context) use (&$loggedContext): bool { - $loggedContext = $context; - - return $message === 'Cache warmed.'; - }); + $logger = Double::for(LoggerInterface::class); + $logger->expects('info')->with('Cache warmed.', Argument::capture($loggedContext)); $this->app->instance(LoggerInterface::class, $logger); info('Cache warmed.', ['id' => 1], callerLocation: true); @@ -273,9 +273,9 @@ public function testInfoAddsTheCallerLocationToTheContext(): void public function testLogsResolvesAChannelNamedZero(): void { - $manager = m::mock(LogManager::class); - $logger = m::mock(LoggerInterface::class); - $manager->expects('driver')->with('0')->andReturn($logger); + $manager = Double::for(LogManager::class); + $logger = Double::for(LoggerInterface::class); + $manager->expects('driver')->with('0')->returns($logger); $this->app->instance('log', $manager); $this->assertSame($logger, logs('0')); diff --git a/tests/Foundation/FoundationViteTest.php b/tests/Foundation/FoundationViteTest.php index 02deff2541..a368cf848a 100644 --- a/tests/Foundation/FoundationViteTest.php +++ b/tests/Foundation/FoundationViteTest.php @@ -12,12 +12,15 @@ use Hypervel\Support\Str; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use JsonException; -use Mockery as m; use PHPUnit\Framework\Attributes\TestWith; class FoundationViteTest extends TestCase { + use VerifiesDoubles; + protected string $tempDir; protected Filesystem $filesystem; @@ -678,9 +681,9 @@ public function testItCanGenerateIndividualAssetUrlInHotMode(): void public function testItThrowsWhenHotFileDisappearsBeforeItCanBeRead(bool $existsBeforeRead): void { $this->withUnreadableViteStream(function (string $path) use ($existsBeforeRead): void { - $vite = m::mock(Vite::class . '[isRunningHot]'); + $vite = Double::for(new Vite)->passthru(); $vite->useHotFile($path . '/hot'); - $vite->expects('isRunningHot')->twice()->andReturn(true, $existsBeforeRead); + $vite->expects('isRunningHot')->times(2)->returns(true, $existsBeforeRead); $this->expectException(ViteException::class); $this->expectExceptionMessageIsOrContains('Unable to read the Vite hot file'); diff --git a/tests/Foundation/Http/KernelTest.php b/tests/Foundation/Http/KernelTest.php index 8dc37d1a63..238ddf26d3 100644 --- a/tests/Foundation/Http/KernelTest.php +++ b/tests/Foundation/Http/KernelTest.php @@ -18,7 +18,8 @@ use Hypervel\Routing\Router; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; use RuntimeException; use Swoole\Coroutine\CanceledException; @@ -28,6 +29,8 @@ class KernelTest extends TestCase { + use VerifiesDoubles; + public function testGetMiddlewareGroups(): void { $kernel = $this->getKernel(); @@ -417,12 +420,12 @@ public function testHandleReportsAndRendersRouterFailures(): void $failure = new RuntimeException('stream failed'); $request = Request::create('/'); $replacement = new Response('replacement', 500); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldReceive('report')->once()->with($failure, []); - $handler->shouldReceive('render')->once()->with($request, $failure)->andReturn($replacement); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($failure, []); + $handler->expects('render')->with($request, $failure)->returns($replacement); $app->instance(ExceptionHandler::class, $handler); - $router = m::mock(Router::class); - $router->shouldReceive('dispatch')->once()->andThrow($failure); + $router = Double::for(Router::class); + $router->expects('dispatch')->throws($failure); $kernel = new Kernel($app, $router); $this->assertSame($replacement, $kernel->handle($request)); @@ -436,12 +439,12 @@ public function testHandleRetainsTheRouterFailureWhenExceptionReportingFails(): $app->bootstrapWith([]); $original = new RuntimeException('router failed'); $reportingFailure = new RuntimeException('reporting failed'); - $handler = m::mock(ExceptionHandler::class); - $handler->expects('report')->with($original, [])->andThrow($reportingFailure); - $handler->shouldNotReceive('render'); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->with($original, [])->throws($reportingFailure); + $handler->expects('render')->never(); $app->instance(ExceptionHandler::class, $handler); - $router = m::mock(Router::class); - $router->expects('dispatch')->andThrow($original); + $router = Double::for(Router::class); + $router->expects('dispatch')->throws($original); $kernel = new Kernel($app, $router); try { @@ -464,11 +467,12 @@ public function testHandlePreservesRouterCancellationWithoutReportingOrDispatchi $events->listen(RequestHandled::class, function () use (&$handled): void { $handled = true; }); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report', 'render'); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->never(); + $handler->expects('render')->never(); $app->instance(ExceptionHandler::class, $handler); - $router = m::mock(Router::class); - $router->expects('dispatch')->andThrow($cancellation); + $router = Double::for(Router::class); + $router->expects('dispatch')->throws($cancellation); $kernel = new Kernel($app, $router); try { @@ -489,11 +493,12 @@ public function testHandlePreservesCancellationFromTheHandledEventWithoutReporti $app->bootstrapWith([]); $cancellation = new CanceledException('canceled'); $events->listen(RequestHandled::class, fn () => throw $cancellation); - $handler = m::mock(ExceptionHandler::class); - $handler->shouldNotReceive('report', 'render'); + $handler = Double::for(ExceptionHandler::class); + $handler->expects('report')->never(); + $handler->expects('render')->never(); $app->instance(ExceptionHandler::class, $handler); - $router = m::mock(Router::class); - $router->expects('dispatch')->andReturn(new Response); + $router = Double::for(Router::class); + $router->expects('dispatch')->returns(new Response); $kernel = new Kernel($app, $router); try { @@ -512,8 +517,8 @@ public function testTerminationIsExhaustiveAndPreservesTheFirstFailure(): void $app->instance('events', $events); $app->instance('config', new Repository(['app' => ['timezone' => 'UTC']])); $app->bootstrapWith([]); - $router = m::mock(Router::class); - $router->shouldReceive('dispatch')->once()->andReturn(new Response); + $router = Double::for(Router::class); + $router->expects('dispatch')->returns(new Response); $kernel = new Kernel($app, $router); $request = Request::create('/'); $response = $kernel->handle($request); @@ -596,8 +601,8 @@ public function testTerminationCancellationStopsLaterStagesAndClearsTheRequestSt $app->instance('events', $events); $app->instance('config', new Repository(['app' => ['timezone' => 'UTC']])); $app->bootstrapWith([]); - $router = m::mock(Router::class); - $router->expects('dispatch')->andReturn(new Response); + $router = Double::for(Router::class); + $router->expects('dispatch')->returns(new Response); $kernel = new Kernel($app, $router); $request = Request::create('/'); $response = $kernel->handle($request); @@ -648,8 +653,8 @@ public function testMiddlewareCancellationSupersedesAnEarlierOrdinaryTermination $app->instance('events', $events); $app->instance('config', new Repository(['app' => ['timezone' => 'UTC']])); $app->bootstrapWith([]); - $router = m::mock(Router::class); - $router->expects('dispatch')->andReturn(new Response); + $router = Double::for(Router::class); + $router->expects('dispatch')->returns(new Response); $kernel = new Kernel($app, $router); $request = Request::create('/'); $response = $kernel->handle($request); @@ -709,8 +714,8 @@ public function testDurationHandlerCancellationSupersedesAnEarlierOrdinaryTermin $app->instance('events', $events); $app->instance('config', new Repository(['app' => ['timezone' => 'UTC']])); $app->bootstrapWith([]); - $router = m::mock(Router::class); - $router->expects('dispatch')->andReturn(new Response); + $router = Double::for(Router::class); + $router->expects('dispatch')->returns(new Response); $kernel = new Kernel($app, $router); $request = Request::create('/'); $response = $kernel->handle($request); @@ -750,8 +755,8 @@ public function testDurationHandlerReceivesConvertedImmutableStartTimeFromContex $app->instance('config', new Repository(['app' => ['timezone' => 'America/New_York']])); $app->bootstrapWith([]); - $router = m::mock(Router::class); - $router->shouldReceive('dispatch')->once()->andReturn(new Response); + $router = Double::for(Router::class); + $router->expects('dispatch')->returns(new Response); $kernel = new Kernel($app, $router); $request = Request::create('/'); @@ -785,8 +790,8 @@ public function testProductionRequestStartTimeIsMaterializedLazily(): void $app->instance('config', new Repository(['app' => ['timezone' => 'UTC']])); $app->bootstrapWith([]); - $router = m::mock(Router::class); - $router->shouldReceive('dispatch')->once()->andReturn(new Response); + $router = Double::for(Router::class); + $router->expects('dispatch')->returns(new Response); $kernel = new class($app, $router) extends Kernel { public function rawRequestStartedAt(): mixed @@ -827,8 +832,8 @@ public function handle(Request $request, Closure $next): Response } }; }); - $router = m::mock(Router::class); - $router->shouldReceive('dispatch')->twice()->andReturn(new Response); + $router = Double::for(Router::class); + $router->expects('dispatch')->times(2)->returns(new Response); $kernel = new class($app, $router) extends Kernel { public function reusablePipeline(): ?Closure { @@ -850,7 +855,7 @@ public function reusablePipeline(): ?Closure public function testSetApplicationClearsApplicationSpecificMiddlewareCaches(): void { - $kernel = new class(new Application, m::mock(Router::class)) extends Kernel { + $kernel = new class(new Application, Double::for(Router::class)) extends Kernel { public function primeMiddlewareCaches(): void { $this->terminableMiddleware = ['test-middleware' => false]; @@ -883,8 +888,8 @@ public function testRequestStartedAtIsIsolatedBetweenConcurrentCoroutines(): voi $app->instance('config', new Repository(['app' => ['timezone' => 'UTC']])); $app->bootstrapWith([]); - $router = m::mock(Router::class); - $router->shouldReceive('dispatch')->andReturn(new Response); + $router = Double::for(Router::class); + $router->allows('dispatch')->returns(new Response); $kernel = new Kernel($app, $router); @@ -928,7 +933,7 @@ protected function getKernel(): Kernel { return new Kernel( new Application, - m::mock(Router::class), + Double::for(Router::class), ); } } diff --git a/tests/Foundation/Http/WebSocketKernelTest.php b/tests/Foundation/Http/WebSocketKernelTest.php index f5328ea291..82eda38d4f 100644 --- a/tests/Foundation/Http/WebSocketKernelTest.php +++ b/tests/Foundation/Http/WebSocketKernelTest.php @@ -11,24 +11,27 @@ use Hypervel\Foundation\Http\WebSocketKernel; use Hypervel\Http\Request; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; use Symfony\Component\HttpFoundation\Response; use Throwable; class WebSocketKernelTest extends TestCase { + use VerifiesDoubles; + public function testHandleExceptionRetainsTheOriginalExceptionWhenReportingFails(): void { $original = new RuntimeException('WebSocket request failed'); $reportingFailure = new RuntimeException('Reporting failed'); $app = new Application; - $app->instance(StdoutLoggerInterface::class, m::mock(StdoutLoggerInterface::class)); + $app->instance(StdoutLoggerInterface::class, Double::for(StdoutLoggerInterface::class)); - $handler = m::mock(ExceptionHandlerContract::class); - $handler->shouldReceive('report')->once()->with($original)->andThrow($reportingFailure); - $handler->shouldNotReceive('render'); + $handler = Double::for(ExceptionHandlerContract::class); + $handler->expects('report')->with($original)->throws($reportingFailure); + $handler->expects('render')->never(); $app->instance(ExceptionHandlerContract::class, $handler); RequestContext::set(Request::create('/')); @@ -50,7 +53,7 @@ public function testHandleExceptionRetainsTheOriginalExceptionWhenResolvingTheHa $resolutionFailure = new RuntimeException('Handler resolution failed'); $app = new Application; - $app->instance(StdoutLoggerInterface::class, m::mock(StdoutLoggerInterface::class)); + $app->instance(StdoutLoggerInterface::class, Double::for(StdoutLoggerInterface::class)); $app->bind(ExceptionHandlerContract::class, static fn () => throw $resolutionFailure); $kernel = new ExposedWebSocketKernel($app); diff --git a/tests/Foundation/Listeners/ReloadDotenvAndConfigTest.php b/tests/Foundation/Listeners/ReloadDotenvAndConfigTest.php index 0f99bd96e2..cdbf3c316b 100644 --- a/tests/Foundation/Listeners/ReloadDotenvAndConfigTest.php +++ b/tests/Foundation/Listeners/ReloadDotenvAndConfigTest.php @@ -16,10 +16,13 @@ use Hypervel\Support\ServiceProvider; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class ReloadDotenvAndConfigTest extends TestCase { + use VerifiesDoubles; + protected ?string $originalAppName = null; protected function setUp(): void @@ -27,15 +30,10 @@ protected function setUp(): void parent::setUp(); $this->originalAppName = getenv('APP_NAME') ?: null; - - DotenvManager::flushState(); - Env::flushState(); } protected function tearDown(): void { - DotenvManager::flushState(); - Env::flushState(); $this->restoreAppName(); parent::tearDown(); @@ -52,7 +50,7 @@ public function testReloadsUsingApplicationEnvironmentFile(): void // Switch to .env.testing (simulates LoadEnvironmentVariables having selected it). $app->loadEnvironmentFrom('.env.testing'); - $event = m::mock(BeforeWorkerStart::class); + $event = Double::for(BeforeWorkerStart::class); $listener = $app->make(ReloadDotenvAndConfig::class); $listener->handle($event); @@ -70,7 +68,7 @@ public function testMissingEnvironmentFileClearsPreviouslyLoadedValues(): void DotenvManager::load([$app->environmentPath()]); $this->assertSame('Hypervel', Env::get('APP_NAME')); - $event = m::mock(BeforeWorkerStart::class); + $event = Double::for(BeforeWorkerStart::class); $listener = $app->make(ReloadDotenvAndConfig::class); $listener->handle($event); @@ -97,14 +95,14 @@ public function testWorkerReloadUsesCurrentCacheFileInsteadOfPreviousBootstrapSt $filesystem->put($app->getCachedConfigPath(), 'make(ReloadDotenvAndConfig::class); - $listener->handle(m::mock(BeforeWorkerStart::class)); + $listener->handle(Double::for(BeforeWorkerStart::class)); $this->assertNull(Env::get('DOCTOR_WORKER_VALUE')); $this->assertSame('cached', $app->make(Repository::class)->get('worker.value')); $this->assertTrue($app->configurationIsCached()); $filesystem->delete($app->getCachedConfigPath()); - $listener->handle(m::mock(BeforeWorkerStart::class)); + $listener->handle(Double::for(BeforeWorkerStart::class)); $this->assertSame('from-file', Env::get('DOCTOR_WORKER_VALUE')); $this->assertSame('from-file', $app->make(Repository::class)->get('worker.value')); @@ -121,7 +119,7 @@ public function testReloadPreservesRepositoryIdentityAndMutationsMadeBeforeListe $originalConfig->set('app.name', 'Reloaded Hypervel'); - $app->make(ReloadDotenvAndConfig::class)->handle(m::mock(BeforeWorkerStart::class)); + $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class)); $reloadedConfig = $app->make(Repository::class); @@ -140,7 +138,7 @@ public function testReloadReplaysOverlappingMutationsInTheirOriginalOrder(): voi $config->set('app.name', 'Second'); $config->set('app', ['name' => 'Last']); - $app->make(ReloadDotenvAndConfig::class)->handle(m::mock(BeforeWorkerStart::class)); + $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class)); $this->assertSame(['name' => 'Last'], $config->get('app')); } @@ -153,7 +151,7 @@ public function testReloadPreservesUntouchedSiblingsWhenReplayingAChildMutation( $config->set('app.name', 'Reloaded Hypervel'); - $app->make(ReloadDotenvAndConfig::class)->handle(m::mock(BeforeWorkerStart::class)); + $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class)); $this->assertSame('Reloaded Hypervel', $config->get('app.name')); $this->assertSame($environment, $config->get('app.env')); @@ -166,10 +164,10 @@ public function testTrackerSealsAfterReplayAndDoesNotRecordLaterMutations(): voi $listener = $app->make(ReloadDotenvAndConfig::class); $config->set('app.name', 'Boot Mutation'); - $listener->handle(m::mock(BeforeWorkerStart::class)); + $listener->handle(Double::for(BeforeWorkerStart::class)); $config->set('app.name', 'Post Start Mutation'); - $listener->handle(m::mock(BeforeWorkerStart::class)); + $listener->handle(Double::for(BeforeWorkerStart::class)); $this->assertSame('Boot Mutation', $config->get('app.name')); } @@ -181,9 +179,9 @@ public function testTrackerSealsWhenThereAreNoBootMutations(): void $listener = $app->make(ReloadDotenvAndConfig::class); $originalName = $config->get('app.name'); - $listener->handle(m::mock(BeforeWorkerStart::class)); + $listener->handle(Double::for(BeforeWorkerStart::class)); $config->set('app.name', 'Post Start Mutation'); - $listener->handle(m::mock(BeforeWorkerStart::class)); + $listener->handle(Double::for(BeforeWorkerStart::class)); $this->assertSame($originalName, $config->get('app.name')); } @@ -228,7 +226,7 @@ public function register(): void $this->assertSame('bar', $config->get('custom.foo')); $app->loadEnvironmentFrom('.env.testing'); - $app->make(ReloadDotenvAndConfig::class)->handle(m::mock(BeforeWorkerStart::class)); + $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class)); $this->assertSame('testing_value', $config->get('worker_package.environment')); $this->assertSame('testing_value', $config->get('custom.environment')); diff --git a/tests/Foundation/PendingChainTest.php b/tests/Foundation/PendingChainTest.php index e92ac5c7de..e354e6ac92 100644 --- a/tests/Foundation/PendingChainTest.php +++ b/tests/Foundation/PendingChainTest.php @@ -12,10 +12,13 @@ use Hypervel\Queue\Attributes\Delay; use Hypervel\Queue\Attributes\Queue as QueueAttribute; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; class PendingChainTest extends TestCase { + use VerifiesDoubles; + public function testEnumConnectionAndQueueIdentifiersAreNormalized(): void { $chain = new PendingChain(new class {}, []); @@ -30,8 +33,8 @@ public function testEnumConnectionAndQueueIdentifiersAreNormalized(): void public function testDispatchPreservesZeroIdentifiersOnTheChainAndFirstJob(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->twice()->andReturnArg(0); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->times(2)->resolves(fn (object $job): object => $job); Container::getInstance()->instance(Dispatcher::class, $dispatcher); $fromChain = (new PendingChain(new PendingChainTestJob, [])) @@ -53,8 +56,8 @@ public function testDispatchPreservesZeroIdentifiersOnTheChainAndFirstJob(): voi public function testDispatchUsesChainIdentifiersForEmptyFirstJobIdentifiers(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once()->andReturnArg(0); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->resolves(fn (object $job): object => $job); Container::getInstance()->instance(Dispatcher::class, $dispatcher); $firstJob = (new PendingChainTestJob)->onConnection('')->onQueue(''); @@ -70,8 +73,8 @@ public function testDispatchUsesChainIdentifiersForEmptyFirstJobIdentifiers(): v public function testDispatchIgnoresEmptyChainIdentifiers(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once()->andReturnArg(0); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->resolves(fn (object $job): object => $job); Container::getInstance()->instance(Dispatcher::class, $dispatcher); $firstJob = (new PendingChainTestJob) @@ -91,8 +94,8 @@ public function testDispatchIgnoresEmptyChainIdentifiers(): void public function testDispatchKeepsFirstJobAttributesOverChainDefaults(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->once()->andReturnArg(0); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->resolves(fn (object $job): object => $job); Container::getInstance()->instance(Dispatcher::class, $dispatcher); $dispatched = (new PendingChain(new PendingChainAttributedJob, [])) @@ -110,8 +113,8 @@ public function testDispatchKeepsFirstJobAttributesOverChainDefaults(): void public function testDispatchAppliesChainDelayOnlyWithoutAFirstJobDelay(): void { - $dispatcher = m::mock(Dispatcher::class); - $dispatcher->shouldReceive('dispatch')->twice()->andReturnArg(0); + $dispatcher = Double::for(Dispatcher::class); + $dispatcher->expects('dispatch')->times(2)->resolves(fn (object $job): object => $job); Container::getInstance()->instance(Dispatcher::class, $dispatcher); $delayed = (new PendingChain(new PendingChainTestJob, []))->delay(10)->dispatch(); diff --git a/tests/Foundation/Testing/BootTraitsTest.php b/tests/Foundation/Testing/BootTraitsTest.php index 9de03338c5..282a511112 100644 --- a/tests/Foundation/Testing/BootTraitsTest.php +++ b/tests/Foundation/Testing/BootTraitsTest.php @@ -14,7 +14,6 @@ use Hypervel\Foundation\Testing\RefreshDatabaseState; use Hypervel\Foundation\Testing\TestCase as FoundationTestCase; use Hypervel\Tests\TestCase; -use Mockery as m; use ReflectionMethod; class BootTraitsTest extends TestCase @@ -78,20 +77,14 @@ public function testMissingTruncatedDatabaseInvalidatesStateBeforeEagerRefresh() ], ], ])); - $testCase = m::mock(TestCaseWithComposedDatabaseResets::class, ['foo']) - ->makePartial()->shouldAllowMockingProtectedMethods(); - $testCase->expects('refreshDatabase')->ordered()->andReturnUsing(function (): void { - $this->assertFalse(RefreshDatabaseState::$migrated); - RefreshDatabaseState::$migrated = true; - }); - $testCase->expects('truncateDatabaseTables')->ordered()->andReturnUsing(function (): void { - $this->assertTrue(RefreshDatabaseState::$migrated); - }); + $testCase = new TestCaseWithComposedDatabaseResets('foo'); RefreshDatabaseState::$migrated = true; RefreshDatabaseState::$inMemoryConnections = []; try { $testCase->prepare($app); + + $this->assertSame([['refresh', false], ['truncate', true]], $testCase->migrationStates); } finally { RefreshDatabaseState::$migrated = false; RefreshDatabaseState::$inMemoryConnections = []; @@ -106,6 +99,25 @@ class TestCaseWithComposedDatabaseResets extends FoundationTestCase protected array $connectionsToTruncate = ['secondary']; + public array $migrationStates = []; + + /** + * Record the migration state before refreshing it. + */ + public function refreshDatabase(): void + { + $this->migrationStates[] = ['refresh', RefreshDatabaseState::$migrated]; + RefreshDatabaseState::$migrated = true; + } + + /** + * Record the migration state when truncation starts. + */ + protected function truncateDatabaseTables(): void + { + $this->migrationStates[] = ['truncate', RefreshDatabaseState::$migrated]; + } + /** * Run Foundation's database setup without booting a Testbench application. */ diff --git a/tests/Foundation/Testing/Concerns/ExternalServiceOptInTest.php b/tests/Foundation/Testing/Concerns/ExternalServiceOptInTest.php index 844f3abe95..cef8e27664 100644 --- a/tests/Foundation/Testing/Concerns/ExternalServiceOptInTest.php +++ b/tests/Foundation/Testing/Concerns/ExternalServiceOptInTest.php @@ -17,18 +17,21 @@ use Hypervel\Foundation\Testing\Concerns\InteractsWithTypesense; use Hypervel\Support\Env; use Hypervel\Tests\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Meilisearch\Client as MeilisearchClient; use Meilisearch\Contracts\IndexesResults; use Meilisearch\Contracts\TasksResults; use Meilisearch\Endpoints\Indexes; use Meilisearch\Exceptions\TimeOutException; -use Mockery as m; use PHPUnit\Framework\Attributes\DataProvider; use RuntimeException; use Throwable; class ExternalServiceOptInTest extends TestCase { + use VerifiesDoubles; + /** * External-service host keys mutated by these tests. * @@ -178,16 +181,14 @@ public function testMeilisearchPreservesExplicitPrefixBeforeInitializingClient() public function testMeilisearchWaitAcceptsSuccessfulTasks(): void { - $client = m::mock(MeilisearchClient::class); - $client->shouldReceive('getTasks') - ->once() - ->andReturn(new TasksResults([ + $client = Double::for(MeilisearchClient::class); + $client->expects('getTasks') + ->returns(new TasksResults([ 'results' => [['uid' => 17, 'indexUid' => 'test_users', 'status' => 'enqueued']], ])); - $client->shouldReceive('waitForTask') - ->once() + $client->expects('waitForTask') ->with(17, 5000) - ->andReturn(['uid' => 17, 'status' => 'succeeded']); + ->returns(['uid' => 17, 'status' => 'succeeded']); $harness = new MeilisearchOptInHarness; $harness->usePrefix('test_'); @@ -197,16 +198,14 @@ public function testMeilisearchWaitAcceptsSuccessfulTasks(): void public function testMeilisearchWaitRejectsFailedTasks(): void { - $client = m::mock(MeilisearchClient::class); - $client->shouldReceive('getTasks') - ->once() - ->andReturn(new TasksResults([ + $client = Double::for(MeilisearchClient::class); + $client->expects('getTasks') + ->returns(new TasksResults([ 'results' => [['uid' => 17, 'indexUid' => 'test_users', 'status' => 'processing']], ])); - $client->shouldReceive('waitForTask') - ->once() + $client->expects('waitForTask') ->with(17, 5000) - ->andReturn([ + ->returns([ 'uid' => 17, 'status' => 'failed', 'error' => ['message' => 'Document identifier is invalid.'], @@ -225,16 +224,14 @@ public function testMeilisearchWaitRejectsFailedTasks(): void public function testMeilisearchWaitPropagatesTimeouts(): void { $timeout = new TimeOutException; - $client = m::mock(MeilisearchClient::class); - $client->shouldReceive('getTasks') - ->once() - ->andReturn(new TasksResults([ + $client = Double::for(MeilisearchClient::class); + $client->expects('getTasks') + ->returns(new TasksResults([ 'results' => [['uid' => 17, 'indexUid' => 'test_users', 'status' => 'enqueued']], ])); - $client->shouldReceive('waitForTask') - ->once() + $client->expects('waitForTask') ->with(17, 5000) - ->andThrow($timeout); + ->throws($timeout); $harness = new MeilisearchOptInHarness; $harness->usePrefix('test_'); @@ -247,44 +244,38 @@ public function testMeilisearchWaitPropagatesTimeouts(): void public function testMeilisearchWaitIgnoresPendingTasksForOtherPrefixes(): void { - $client = m::mock(MeilisearchClient::class); - $client->shouldReceive('getTasks') - ->once() - ->andReturn(new TasksResults([ + $client = Double::for(MeilisearchClient::class); + $client->expects('getTasks') + ->returns(new TasksResults([ 'results' => [['uid' => 17, 'indexUid' => 'other_users', 'status' => 'enqueued']], ])); - $client->shouldNotReceive('waitForTask'); + $client->expects('waitForTask')->never(); $harness = new MeilisearchOptInHarness; $harness->usePrefix('test_'); $harness->useClient($client); $harness->waitForTasks(); - - $this->assertTrue(true); } public function testMeilisearchCleanupWaitsForExactDeletionTasks(): void { - $index = m::mock(Indexes::class); - $index->shouldReceive('getUid')->andReturn('test_users'); + $index = Double::for(Indexes::class); + $index->allows('getUid')->returns('test_users'); - $client = m::mock(MeilisearchClient::class); - $client->shouldReceive('getIndexes') - ->once() - ->andReturn(new IndexesResults([ + $client = Double::for(MeilisearchClient::class); + $client->expects('getIndexes') + ->returns(new IndexesResults([ 'results' => [$index], 'offset' => 0, 'limit' => 20, 'total' => 1, ])); - $client->shouldReceive('deleteIndex') - ->once() + $client->expects('deleteIndex') ->with('test_users') - ->andReturn(['taskUid' => 29]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskUid' => 29]); + $client->expects('waitForTask') ->with(29, 5000) - ->andReturn(['uid' => 29, 'status' => 'succeeded']); + ->returns(['uid' => 29, 'status' => 'succeeded']); $harness = new MeilisearchOptInHarness; $harness->usePrefix('test_'); @@ -294,26 +285,23 @@ public function testMeilisearchCleanupWaitsForExactDeletionTasks(): void public function testMeilisearchCleanupPropagatesDeletionTaskFailures(): void { - $index = m::mock(Indexes::class); - $index->shouldReceive('getUid')->andReturn('test_users'); + $index = Double::for(Indexes::class); + $index->allows('getUid')->returns('test_users'); - $client = m::mock(MeilisearchClient::class); - $client->shouldReceive('getIndexes') - ->once() - ->andReturn(new IndexesResults([ + $client = Double::for(MeilisearchClient::class); + $client->expects('getIndexes') + ->returns(new IndexesResults([ 'results' => [$index], 'offset' => 0, 'limit' => 20, 'total' => 1, ])); - $client->shouldReceive('deleteIndex') - ->once() + $client->expects('deleteIndex') ->with('test_users') - ->andReturn(['taskUid' => 29]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskUid' => 29]); + $client->expects('waitForTask') ->with(29, 5000) - ->andReturn([ + ->returns([ 'uid' => 29, 'status' => 'failed', 'error' => ['message' => 'Index deletion failed.'], @@ -420,9 +408,9 @@ public function testAlgoliaAssignsADefaultPrefixAndRestoresTheExactHttpClient(): $expectedPrefix = $testToken === '' ? 'test_' : "test_{$testToken}_"; $originalClient = Algolia::getHttpClient(); - $previousClient = m::mock(HttpClientInterface::class); - $testClient = m::mock(HttpClientInterface::class); - $testClient->shouldReceive('sendRequest')->times(3)->andReturn( + $previousClient = Double::for(HttpClientInterface::class); + $testClient = Double::for(HttpClientInterface::class); + $testClient->expects('sendRequest')->times(3)->returns( new Response(200, ['content-type' => 'application/json'], '{"items":[]}') ); @@ -451,8 +439,8 @@ public function testAlgoliaPreservesAnExplicitPrefix(): void $this->setExternalServiceEnvironmentValue('ALGOLIA_SECRET', 'secret'); $originalClient = Algolia::getHttpClient(); - $testClient = m::mock(HttpClientInterface::class); - $testClient->shouldReceive('sendRequest')->times(3)->andReturn( + $testClient = Double::for(HttpClientInterface::class); + $testClient->expects('sendRequest')->times(3)->returns( new Response(200, ['content-type' => 'application/json'], '{"items":[]}') ); @@ -472,21 +460,18 @@ public function testAlgoliaPreservesAnExplicitPrefix(): void public function testAlgoliaCleanupWaitsForExactDeletionTasks(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('listIndices') - ->once() - ->andReturn(['items' => [ + $client = Double::for(AlgoliaSearchClient::class); + $client->expects('listIndices') + ->returns(['items' => [ ['name' => 'test_users'], ['name' => 'production_users'], ]]); - $client->shouldReceive('deleteIndex') - ->once() + $client->expects('deleteIndex') ->with('test_users') - ->andReturn(['taskID' => 31]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskID' => 31]); + $client->expects('waitForTask') ->with('test_users', 31) - ->andReturn(['status' => 'published']); + ->returns(['status' => 'published']); $harness = new AlgoliaOptInHarness; $harness->usePrefix('test_'); @@ -497,18 +482,15 @@ public function testAlgoliaCleanupWaitsForExactDeletionTasks(): void #[DataProvider('incompleteAlgoliaDeletionTasks')] public function testAlgoliaCleanupRejectsIncompleteDeletionTasks(?array $task): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('listIndices') - ->once() - ->andReturn(['items' => [['name' => 'test_users']]]); - $client->shouldReceive('deleteIndex') - ->once() + $client = Double::for(AlgoliaSearchClient::class); + $client->expects('listIndices') + ->returns(['items' => [['name' => 'test_users']]]); + $client->expects('deleteIndex') ->with('test_users') - ->andReturn(['taskID' => 31]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskID' => 31]); + $client->expects('waitForTask') ->with('test_users', 31) - ->andReturn($task); + ->returns($task); $harness = new AlgoliaOptInHarness; $harness->usePrefix('test_'); @@ -535,29 +517,24 @@ public static function incompleteAlgoliaDeletionTasks(): array public function testAlgoliaCleanupWaitsForRemainingTasksBeforeRejectingAnIncompleteResult(): void { - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('listIndices') - ->once() - ->andReturn(['items' => [ + $client = Double::for(AlgoliaSearchClient::class); + $client->expects('listIndices') + ->returns(['items' => [ ['name' => 'test_users'], ['name' => 'test_orders'], ]]); - $client->shouldReceive('deleteIndex') - ->once() + $client->expects('deleteIndex') ->with('test_users') - ->andReturn(['taskID' => 31]); - $client->shouldReceive('deleteIndex') - ->once() + ->returns(['taskID' => 31]); + $client->expects('deleteIndex') ->with('test_orders') - ->andReturn(['taskID' => 32]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskID' => 32]); + $client->expects('waitForTask') ->with('test_users', 31) - ->andReturn(null); - $client->shouldReceive('waitForTask') - ->once() + ->returns(null); + $client->expects('waitForTask') ->with('test_orders', 32) - ->andReturn(['status' => 'published']); + ->returns(['status' => 'published']); $harness = new AlgoliaOptInHarness; $harness->usePrefix('test_'); @@ -572,26 +549,22 @@ public function testAlgoliaCleanupWaitsForRemainingTasksBeforeRejectingAnIncompl public function testAlgoliaCleanupPropagatesDeletionTaskFailures(): void { $failure = new RuntimeException('Index deletion failed.'); - $client = m::mock(AlgoliaSearchClient::class); - $client->shouldReceive('listIndices') - ->once() - ->andReturn(['items' => [ + $client = Double::for(AlgoliaSearchClient::class); + $client->expects('listIndices') + ->returns(['items' => [ ['name' => 'test_users'], ['name' => 'test_orders'], ]]); - $client->shouldReceive('deleteIndex') - ->once() + $client->expects('deleteIndex') ->with('test_users') - ->andReturn(['taskID' => 31]); - $client->shouldReceive('deleteIndex') - ->once() + ->returns(['taskID' => 31]); + $client->expects('deleteIndex') ->with('test_orders') - ->andReturn(['taskID' => 32]); - $client->shouldReceive('waitForTask') - ->once() + ->returns(['taskID' => 32]); + $client->expects('waitForTask') ->with('test_users', 31) - ->andThrow($failure); - $client->shouldNotReceive('waitForTask') + ->throws($failure); + $client->expects('waitForTask')->never() ->with('test_orders', 32); $harness = new AlgoliaOptInHarness; @@ -609,10 +582,10 @@ public function testAlgoliaRestoresTheExactHttpClientWhenSetupFails(): void $this->setExternalServiceEnvironmentValue('ALGOLIA_SECRET', 'secret'); $originalClient = Algolia::getHttpClient(); - $previousClient = m::mock(HttpClientInterface::class); + $previousClient = Double::for(HttpClientInterface::class); $failure = new RuntimeException('Algolia probe failed'); - $testClient = m::mock(HttpClientInterface::class); - $testClient->shouldReceive('sendRequest')->andThrow($failure); + $testClient = Double::for(HttpClientInterface::class); + $testClient->allows('sendRequest')->throws($failure); Algolia::setHttpClient($previousClient); diff --git a/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php b/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php index fea3ed62ff..2d8adf4160 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php @@ -7,20 +7,22 @@ use Hypervel\Foundation\Vite; use Hypervel\Support\Defer\DeferredCallbackCollection; use Hypervel\Testbench\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use Mockery\MockInterface; class InteractsWithContainerTest extends TestCase { + use VerifiesDoubles; + public function testSwap(): void { $this->app->instance(InstanceStub::class, new InstanceStub); $this->assertSame('foo', $this->app->make(InstanceStub::class)->execute()); - $stub = m::mock(InstanceStub::class); - $stub->expects('execute') - ->andReturn('bar'); + $stub = Double::for(InstanceStub::class); + $stub->expects('execute')->returns('bar'); $this->swap(InstanceStub::class, $stub); diff --git a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php index ca4b20edbd..cbf21aee42 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php @@ -13,13 +13,15 @@ use Hypervel\Support\Facades\DB; use Hypervel\Testbench\TestCase; use InvalidArgumentException; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDOException; use PHPUnit\Framework\Attributes\DataProvider; class InteractsWithParallelDatabaseTest extends TestCase { use InteractsWithParallelDatabase; + use VerifiesDoubles; public function testParallelTestDatabaseAppendsTokenToName(): void { @@ -390,25 +392,23 @@ public function testEnsureParallelDatabaseExistsRecoversFromTheCurrentSuffixedDa [], new PDOException('Database does not exist.') ); - $schemaBuilder = m::mock(SchemaBuilder::class); - $schemaBuilder->shouldReceive('hasTable') - ->once() + $schemaBuilder = Double::for(SchemaBuilder::class); + $schemaBuilder->expects('hasTable') ->with('__parallel_check') - ->andThrow($queryException); - $schemaBuilder->shouldReceive('createDatabase') - ->once() + ->throws($queryException); + $schemaBuilder->expects('createDatabase') ->with('analytics_test_data_test_7') - ->andReturn(true); - $databaseConnection = m::mock(Connection::class); - $databaseConnection->shouldReceive('getSchemaBuilder') - ->twice() - ->andReturn($schemaBuilder); + ->returns(true); + $databaseConnection = Double::for(Connection::class); + $databaseConnection->expects('getSchemaBuilder') + ->times(2) + ->returns($schemaBuilder); $connectionCalls = 0; - $databaseManager = m::mock(DatabaseManager::class); - $databaseManager->shouldReceive('connection') - ->twice() + $databaseManager = Double::for(DatabaseManager::class); + $databaseManager->expects('connection') + ->times(2) ->with($connection) - ->andReturnUsing(function () use ( + ->resolves(function () use ( &$connectionCalls, $config, $configurationPath, @@ -425,7 +425,7 @@ public function testEnsureParallelDatabaseExistsRecoversFromTheCurrentSuffixedDa return $databaseConnection; }); - $databaseManager->shouldReceive('purge')->twice()->with($connection); + $databaseManager->expects('purge')->times(2)->with($connection); $this->app->instance('db', $databaseManager); DB::clearResolvedInstance(); diff --git a/tests/Foundation/Testing/Concerns/InteractsWithRedisParallelTest.php b/tests/Foundation/Testing/Concerns/InteractsWithRedisParallelTest.php index 2b154dc5ac..c1407569ad 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithRedisParallelTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithRedisParallelTest.php @@ -14,11 +14,14 @@ use Hypervel\Support\Env; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use RuntimeException; class InteractsWithRedisParallelTest extends TestCase { + use VerifiesDoubles; + /** * Redis-related environment keys mutated by these tests. * @@ -473,7 +476,7 @@ public function testSetupRejectsUrlConfiguredConnections(): void public function testTeardownClosesPoolsAndPropagatesAFlushFailure(): void { - $pools = m::mock(PoolManager::class); + $pools = Double::for(PoolManager::class); $pools->expects('purgeAll'); $this->app->instance(PoolManager::class, $pools); $harness = $this->harness(); diff --git a/tests/Foundation/Testing/Concerns/InteractsWithTestCaseLifecycleTest.php b/tests/Foundation/Testing/Concerns/InteractsWithTestCaseLifecycleTest.php index f0a206177d..a647be860b 100644 --- a/tests/Foundation/Testing/Concerns/InteractsWithTestCaseLifecycleTest.php +++ b/tests/Foundation/Testing/Concerns/InteractsWithTestCaseLifecycleTest.php @@ -14,12 +14,15 @@ use Hypervel\Support\Facades\ParallelTesting; use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting as ParallelTestingService; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use ReflectionProperty; use RuntimeException; class InteractsWithTestCaseLifecycleTest extends TestCase { + use VerifiesDoubles; + public function testLazyDatabaseTraitIsBootedOnceThroughRefreshDatabaseDependency(): void { $testCase = new FoundationLazyDatabaseTraitsTestCaseFixture('testPlaceholder'); @@ -50,8 +53,8 @@ public function testFoundationTeardownAttemptsEveryPhaseAndPreservesTheEarliestF $parallelTesting = $this->app->make(ParallelTestingService::class); try { - $pooledConnection = m::mock(PoolConnection::class); - $pooledConnection->shouldReceive('discard')->once()->andReturnUsing( + $pooledConnection = Double::for(PoolConnection::class); + $pooledConnection->expects('discard')->resolves( function () use (&$steps, $databaseException): never { $steps[] = 'database'; @@ -62,8 +65,8 @@ function () use (&$steps, $databaseException): never { (new ReflectionProperty(DatabaseConnectionResolver::class, 'pooledConnections')) ->setValue(null, ['default' => $pooledConnection]); - $poolManager = m::mock(PoolManager::class); - $poolManager->shouldReceive('purgeAll')->once()->andReturnUsing( + $poolManager = Double::for(PoolManager::class); + $poolManager->expects('purgeAll')->resolves( function () use (&$steps, $poolException): never { $steps[] = 'pool'; @@ -71,10 +74,10 @@ function () use (&$steps, $poolException): never { } ); - $app = m::mock(ApplicationContract::class); - $app->shouldReceive('resolved')->once()->with(PoolManager::class)->andReturnTrue(); - $app->shouldReceive('make')->once()->with(PoolManager::class)->andReturn($poolManager); - $app->shouldReceive('flush')->once()->andReturnUsing( + $app = Double::for(ApplicationContract::class, override: true); + $app->expects('resolved')->with(PoolManager::class)->returns(true); + $app->expects('make')->with(PoolManager::class)->returns($poolManager); + $app->expects('flush')->resolves( function () use (&$steps, $applicationException): never { $steps[] = 'application'; @@ -82,8 +85,8 @@ function () use (&$steps, $applicationException): never { } ); - $parallelTestingMock = m::mock(ParallelTestingService::class); - $parallelTestingMock->shouldReceive('callTearDownTestCaseCallbacks')->once()->andReturnUsing( + $parallelTestingMock = Double::for(ParallelTestingService::class); + $parallelTestingMock->expects('callTearDownTestCaseCallbacks')->resolves( function () use (&$steps, $parallelException): never { $steps[] = 'parallel'; @@ -93,7 +96,7 @@ function () use (&$steps, $parallelException): never { ParallelTesting::swap($parallelTestingMock); $testCase = new FoundationLifecycleTestCaseFixture('testPlaceholder'); - $testCase->useApplication($app); + $testCase->useApplication($app->instance()); $testCase->registerAfterApplicationCreatedCallback(static function (): void { }); $testCase->registerBeforeApplicationDestroyedCallback( diff --git a/tests/Foundation/Testing/DatabaseConnectionResolverTest.php b/tests/Foundation/Testing/DatabaseConnectionResolverTest.php index ecd6d5f2ee..e2839ebae0 100644 --- a/tests/Foundation/Testing/DatabaseConnectionResolverTest.php +++ b/tests/Foundation/Testing/DatabaseConnectionResolverTest.php @@ -15,8 +15,9 @@ use Hypervel\Testbench\Attributes\DefineEnvironment; use Hypervel\Testbench\Attributes\WithConfig; use Hypervel\Testbench\TestCase; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use LogicException; -use Mockery as m; use PDO; use ReflectionProperty; use RuntimeException; @@ -24,6 +25,8 @@ #[WithConfig('database.default', 'testing')] class DatabaseConnectionResolverTest extends TestCase { + use VerifiesDoubles; + /** * Use coroutine-owned SQLite sessions for restoration tests. */ @@ -132,8 +135,8 @@ public function testPurgeDisconnectsSharedResolverOwnedConnectionOnce(): void { $manager = $this->app->make('db'); $connection = $manager->connection('testing::read'); - $transactions = m::mock(DatabaseTransactionsManager::class); - $transactions->shouldReceive('rollback')->with('testing', 0)->once(); + $transactions = Double::for(DatabaseTransactionsManager::class); + $transactions->expects('rollback')->with('testing', 0); $connection->setTransactionManager($transactions); $manager->purge('testing::read'); @@ -217,17 +220,17 @@ public function testResetCachedConnectionsCompletesEveryDiscardBeforeRethrowing( { DatabaseConnectionResolver::flushCachedConnections(); - $firstConnection = m::mock(Connection::class); - $firstConnection->shouldReceive('resetForPool')->once(); - $firstConnection->shouldReceive('isReusable')->once()->andReturnFalse(); - $secondConnection = m::mock(Connection::class); - $secondConnection->shouldReceive('resetForPool')->once(); - $secondConnection->shouldReceive('isReusable')->once()->andReturnFalse(); + $firstConnection = Double::for(Connection::class); + $firstConnection->expects('resetForPool'); + $firstConnection->expects('isReusable')->returns(false); + $secondConnection = Double::for(Connection::class); + $secondConnection->expects('resetForPool'); + $secondConnection->expects('isReusable')->returns(false); $failure = new RuntimeException('discard failed'); - $firstPooledConnection = m::mock(PooledConnection::class); - $firstPooledConnection->shouldReceive('discard')->once()->andThrow($failure); - $secondPooledConnection = m::mock(PooledConnection::class); - $secondPooledConnection->shouldReceive('discard')->once(); + $firstPooledConnection = Double::for(PooledConnection::class); + $firstPooledConnection->expects('discard')->throws($failure); + $secondPooledConnection = Double::for(PooledConnection::class); + $secondPooledConnection->expects('discard'); (new ReflectionProperty(DatabaseConnectionResolver::class, 'connections'))->setValue([ 'first' => $firstConnection, diff --git a/tests/Foundation/Testing/DatabaseTransactionsManagerTest.php b/tests/Foundation/Testing/DatabaseTransactionsManagerTest.php index e008e17ed2..9d6227dac6 100644 --- a/tests/Foundation/Testing/DatabaseTransactionsManagerTest.php +++ b/tests/Foundation/Testing/DatabaseTransactionsManagerTest.php @@ -9,11 +9,14 @@ use Hypervel\Database\SQLiteConnection; use Hypervel\Foundation\Testing\DatabaseTransactionsManager; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; class DatabaseTransactionsManagerTest extends TestCase { + use VerifiesDoubles; + public function testItExecutesCallbacksImmediatelyIfThereIsOnlyOneTransaction(): void { $testObject = new TestingDatabaseTransactionsManagerTestObject; @@ -141,10 +144,10 @@ public function testPooledChildTransactionsDoNotCountAsTheirParentsWrapper(): vo public function testRoleWrappersExcludeOnlyTheirResolvedOwnersTransaction(): void { $manager = new DatabaseTransactionsManager(['foo::write']); - $database = m::mock(DatabaseManager::class); + $database = Double::for(DatabaseManager::class); $writer = new SQLiteConnection(new PDO('sqlite::memory:'), config: ['name' => 'foo']); $writer->setReadWriteType('write'); - $database->shouldReceive('connection')->once()->with('foo::write')->andReturn($writer); + $database->expects('connection')->with('foo::write')->returns($writer); $manager->beginTransactions($database); $this->assertFalse($writer->hasApplicableTransaction()); @@ -175,11 +178,11 @@ public function testRoleWrappersExcludeOnlyTheirResolvedOwnersTransaction(): voi */ protected function beginWrappingTransactions(DatabaseTransactionsManager $manager, array $names = [null]): void { - $database = m::mock(DatabaseManager::class); + $database = Double::for(DatabaseManager::class); foreach ($names as $name) { $connection = new SQLiteConnection(new PDO('sqlite::memory:'), config: ['name' => $name ?? 'foo']); - $database->shouldReceive('connection')->once()->with($name)->andReturn($connection); + $database->expects('connection')->with($name)->returns($connection); } $manager->beginTransactions($database); diff --git a/tests/Foundation/Testing/DatabaseTransactionsTest.php b/tests/Foundation/Testing/DatabaseTransactionsTest.php index 0bc5186144..33e39571ea 100644 --- a/tests/Foundation/Testing/DatabaseTransactionsTest.php +++ b/tests/Foundation/Testing/DatabaseTransactionsTest.php @@ -11,22 +11,25 @@ use Hypervel\Database\SQLiteConnection; use Hypervel\Foundation\Testing\DatabaseTransactions; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PDO; use RuntimeException; class DatabaseTransactionsTest extends TestCase { + use VerifiesDoubles; + public function testBeginTransactionRestoresTheDispatcherWhenItFails(): void { $failure = new RuntimeException('Transaction begin failed.'); - $dispatcher = m::mock(Dispatcher::class); - $connection = m::mock(Connection::class); - $connection->shouldReceive('setTransactionManager')->once(); - $connection->shouldReceive('getEventDispatcher')->once()->andReturn($dispatcher); - $connection->shouldReceive('unsetEventDispatcher')->once()->ordered(); - $connection->shouldReceive('beginTransaction')->once()->andThrow($failure)->ordered(); - $connection->shouldReceive('setEventDispatcher')->once()->with($dispatcher)->ordered(); + $dispatcher = Double::for(Dispatcher::class); + $connection = Double::for(Connection::class); + $connection->expects('setTransactionManager'); + $connection->expects('getEventDispatcher')->returns($dispatcher); + $connection->expects('unsetEventDispatcher')->ordered(); + $connection->expects('beginTransaction')->throws($failure)->ordered(); + $connection->expects('setEventDispatcher')->with($dispatcher)->ordered(); $testCase = $this->createTestCase($connection); try { @@ -56,13 +59,13 @@ public function testTestTransactionIsRolledBackWhenTheTestLeavesATransactionOpen public function testRollbackRestoresTheDispatcherWhenItFails(): void { $failure = new RuntimeException('Transaction rollback failed.'); - $dispatcher = m::mock(Dispatcher::class); - $connection = m::mock(Connection::class); - $connection->shouldReceive('getEventDispatcher')->once()->andReturn($dispatcher); - $connection->shouldReceive('unsetEventDispatcher')->once()->ordered(); - $connection->shouldReceive('forgetRecordModificationState')->once()->ordered(); - $connection->shouldReceive('rollBack')->once()->andThrow($failure)->ordered(); - $connection->shouldReceive('setEventDispatcher')->once()->with($dispatcher)->ordered(); + $dispatcher = Double::for(Dispatcher::class); + $connection = Double::for(Connection::class); + $connection->expects('getEventDispatcher')->returns($dispatcher); + $connection->expects('unsetEventDispatcher')->ordered(); + $connection->expects('forgetRecordModificationState')->ordered(); + $connection->expects('rollBack')->throws($failure)->ordered(); + $connection->expects('setEventDispatcher')->with($dispatcher)->ordered(); $testCase = $this->createTestCase($connection); try { @@ -78,8 +81,8 @@ public function testRollbackRestoresTheDispatcherWhenItFails(): void */ private function createTestCase(Connection $connection): DatabaseTransactionsTestCase { - $database = m::mock(DatabaseManager::class); - $database->shouldReceive('connection')->once()->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); $app = new Container; $app->instance('db', $database); diff --git a/tests/Foundation/Testing/RefreshDatabaseTest.php b/tests/Foundation/Testing/RefreshDatabaseTest.php index b9a95a305d..5027489c4b 100644 --- a/tests/Foundation/Testing/RefreshDatabaseTest.php +++ b/tests/Foundation/Testing/RefreshDatabaseTest.php @@ -18,8 +18,10 @@ use Hypervel\Testbench\TestCase; use Hypervel\Testing\ParallelTesting; use Hypervel\Tests\Foundation\Testing\Fixtures\ConsoleKernelSpy; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; +use JMac\Testing\Matching\Argument; use LogicException; -use Mockery as m; use PDO; use RuntimeException; @@ -27,6 +29,7 @@ class RefreshDatabaseTest extends TestCase { use RefreshDatabase; use InteractsWithConsole; + use VerifiesDoubles; protected bool $runTestsInCoroutine = false; @@ -218,9 +221,9 @@ public function testRefreshTestDatabaseRestoresMockConsoleOutputAfterMigrationFa { $this->mockConsoleOutput = true; - $kernel = m::mock(KernelContract::class); + $kernel = Double::for(KernelContract::class); $kernel->expects('call') - ->andThrow(new RuntimeException('Migration failed.')); + ->throws(new RuntimeException('Migration failed.')); $this->app = new Application; $this->app->singleton('config', fn () => new Repository([ @@ -249,30 +252,30 @@ public function testRefreshDatabaseDoesNotPublishMigratedWhenTheAfterHookFails() $this->runTestsInCoroutine = false; $this->afterRefreshingDatabaseException = new RuntimeException('After refresh failed.'); - $kernel = m::mock(KernelContract::class); + $kernel = Double::for(KernelContract::class); $kernel->expects('call') - ->with('migrate:fresh', m::type('array')) - ->andReturn(0); + ->with('migrate:fresh', Argument::type('array')) + ->returns(0); $kernel->expects('setArtisan')->with(null); - $pdo = m::mock(PDO::class); - $eventDispatcher = m::mock(Dispatcher::class); - $connection = m::mock(PdoConnection::class); - $connection->expects('getPdo')->andReturn($pdo); - $connection->expects('getNameWithReadWriteType')->andReturn('default'); + $pdo = Double::for(PDO::class); + $eventDispatcher = Double::for(Dispatcher::class); + $connection = Double::for(PdoConnection::class); + $connection->expects('getPdo')->returns($pdo); + $connection->expects('getNameWithReadWriteType')->returns('default'); $connection->expects('setTransactionManager'); - $connection->expects('getEventDispatcher')->twice()->andReturn($eventDispatcher); - $connection->expects('unsetEventDispatcher')->twice(); - $connection->expects('beginTransaction')->andReturnUsing( + $connection->expects('getEventDispatcher')->times(2)->returns($eventDispatcher); + $connection->expects('unsetEventDispatcher')->times(2); + $connection->expects('beginTransaction')->resolves( fn () => $this->app->make('db.transactions')->begin('default', 1) ); - $connection->expects('inTransaction')->andReturnTrue(); + $connection->expects('inTransaction')->returns(true); $connection->expects('forgetRecordModificationState'); $connection->expects('rollBack'); - $connection->expects('setEventDispatcher')->twice()->with($eventDispatcher); + $connection->expects('setEventDispatcher')->times(2)->with($eventDispatcher); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->times(3)->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->times(3)->with(null)->returns($connection); $this->app = new Application; $this->app->singleton('config', fn () => new Repository([ @@ -304,21 +307,21 @@ public function testRefreshDatabaseCachesPdoBeforeMarkingTheDatabaseAsMigrated() $this->migrateRefresh = false; $this->runTestsInCoroutine = true; - $pdo = m::mock(PDO::class); - $connection = m::mock(PdoConnection::class); - $connection->expects('getPdo')->andReturnUsing(function () use ($pdo): PDO { + $pdo = Double::for(PDO::class); + $connection = Double::for(PdoConnection::class); + $connection->expects('getPdo')->resolves(function () use ($pdo): PDO { $this->assertFalse(RefreshDatabaseState::$migrated); return $pdo; }); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); - $kernel = m::mock(KernelContract::class); + $kernel = Double::for(KernelContract::class); $kernel->expects('call') - ->with('migrate:fresh', m::type('array')) - ->andReturn(0); + ->with('migrate:fresh', Argument::type('array')) + ->returns(0); $kernel->expects('setArtisan')->with(null); $this->app = new Application; @@ -344,14 +347,14 @@ public function testRefreshDatabaseCachesPdoBeforeMarkingTheDatabaseAsMigrated() public function testRestoreInMemoryDatabaseUsesResolvedDefaultConnectionName(): void { - $pdo = m::mock(PDO::class); - $eventDispatcher = m::mock(Dispatcher::class); - $connection = m::mock(PdoConnection::class); - $connection->expects('setPdo')->with($pdo)->andReturnSelf(); - $connection->expects('setEventDispatcher')->with($eventDispatcher)->andReturnSelf(); + $pdo = Double::for(PDO::class); + $eventDispatcher = Double::for(Dispatcher::class); + $connection = Double::for(PdoConnection::class); + $connection->expects('setPdo')->with($pdo); + $connection->expects('setEventDispatcher')->with($eventDispatcher); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); RefreshDatabaseState::$inMemoryConnections = ['default' => $pdo]; @@ -409,18 +412,18 @@ public function testRefreshTestDatabaseCachesOnlyNamedInMemoryConnections(): voi $this->migrateRefresh = false; $this->runTestsInCoroutine = true; - $memoryPdo = m::mock(PDO::class); - $memoryConnection = m::mock(PdoConnection::class); - $memoryConnection->expects('getPdo')->andReturn($memoryPdo); + $memoryPdo = Double::for(PDO::class); + $memoryConnection = Double::for(PdoConnection::class); + $memoryConnection->expects('getPdo')->returns($memoryPdo); - $database = m::mock(DatabaseManager::class); - $database->shouldNotReceive('connection')->with('file'); - $database->expects('connection')->with('memory')->andReturn($memoryConnection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->never()->with('file'); + $database->expects('connection')->with('memory')->returns($memoryConnection); - $kernel = m::mock(KernelContract::class); + $kernel = Double::for(KernelContract::class); $kernel->expects('call') - ->with('migrate:fresh', m::type('array')) - ->andReturn(0); + ->with('migrate:fresh', Argument::type('array')) + ->returns(0); $kernel->expects('setArtisan')->with(null); $this->connectionsToTransact = ['file', 'memory']; @@ -457,15 +460,15 @@ public function testRefreshTestDatabaseRequiresPdoForInMemoryConnection(): void $this->migrateRefresh = false; $this->runTestsInCoroutine = true; - $connection = m::mock(Connection::class); + $connection = Double::for(Connection::class); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); - $kernel = m::mock(KernelContract::class); + $kernel = Double::for(KernelContract::class); $kernel->expects('call') - ->with('migrate:fresh', m::type('array')) - ->andReturn(0); + ->with('migrate:fresh', Argument::type('array')) + ->returns(0); $kernel->expects('setArtisan')->with(null); $this->app = new Application; @@ -488,10 +491,10 @@ public function testRefreshTestDatabaseRequiresPdoForInMemoryConnection(): void public function testRestoreInMemoryDatabaseRequiresPdoConnection(): void { - $pdo = m::mock(PDO::class); - $connection = m::mock(Connection::class); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $pdo = Double::for(PDO::class); + $connection = Double::for(Connection::class); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); RefreshDatabaseState::$inMemoryConnections = ['default' => $pdo]; $this->app = new Application; @@ -518,17 +521,17 @@ public function testRefreshDatabaseRemigratesWhenAnInMemoryPdoCacheIsMissing(): $this->migrateRefresh = false; $this->runTestsInCoroutine = true; - $pdo = m::mock(PDO::class); - $connection = m::mock(PdoConnection::class); - $connection->expects('getPdo')->andReturn($pdo); + $pdo = Double::for(PDO::class); + $connection = Double::for(PdoConnection::class); + $connection->expects('getPdo')->returns($pdo); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); - $kernel = m::mock(KernelContract::class); + $kernel = Double::for(KernelContract::class); $kernel->expects('call') - ->with('migrate:fresh', m::type('array')) - ->andReturn(0); + ->with('migrate:fresh', Argument::type('array')) + ->returns(0); $kernel->expects('setArtisan')->with(null); $this->app = new Application; @@ -551,7 +554,7 @@ public function testRefreshDatabaseRemigratesWhenAnInMemoryPdoCacheIsMissing(): public function testRefreshTestDatabaseSkipsMigrationWhenTheSchemaAndPdoCacheAreReady(): void { - $pdo = m::mock(PDO::class); + $pdo = Double::for(PDO::class); RefreshDatabaseState::$migrated = true; RefreshDatabaseState::$inMemoryConnections = ['default' => $pdo]; $this->migrateRefresh = false; @@ -576,23 +579,23 @@ public function testRefreshTestDatabaseSkipsMigrationWhenTheSchemaAndPdoCacheAre public function testMigrateRefreshReplacesTheCachedInMemoryPdo(): void { - $oldPdo = m::mock(PDO::class); - $freshPdo = m::mock(PDO::class); + $oldPdo = Double::for(PDO::class); + $freshPdo = Double::for(PDO::class); RefreshDatabaseState::$migrated = true; RefreshDatabaseState::$inMemoryConnections = ['default' => $oldPdo]; $this->migrateRefresh = true; $this->runTestsInCoroutine = true; - $connection = m::mock(PdoConnection::class); - $connection->expects('getPdo')->andReturn($freshPdo); + $connection = Double::for(PdoConnection::class); + $connection->expects('getPdo')->returns($freshPdo); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); - $kernel = m::mock(KernelContract::class); + $kernel = Double::for(KernelContract::class); $kernel->expects('call') - ->with('migrate:fresh', m::type('array')) - ->andReturn(0); + ->with('migrate:fresh', Argument::type('array')) + ->returns(0); $kernel->expects('setArtisan')->with(null); $this->app = new Application; @@ -616,16 +619,16 @@ public function testMigrateRefreshReplacesTheCachedInMemoryPdo(): void public function testBeginTransactionRestoresTheDispatcherWhenItFails(): void { $failure = new RuntimeException('Transaction begin failed.'); - $dispatcher = m::mock(Dispatcher::class); - $connection = m::mock(Connection::class); + $dispatcher = Double::for(Dispatcher::class); + $connection = Double::for(Connection::class); $connection->expects('setTransactionManager'); - $connection->expects('getEventDispatcher')->andReturn($dispatcher); + $connection->expects('getEventDispatcher')->returns($dispatcher); $connection->expects('unsetEventDispatcher')->ordered(); - $connection->expects('beginTransaction')->andThrow($failure)->ordered(); + $connection->expects('beginTransaction')->throws($failure)->ordered(); $connection->expects('setEventDispatcher')->with($dispatcher)->ordered(); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); $this->app->instance('db', $database); try { @@ -640,17 +643,17 @@ public function testRollbackRestoresTheDispatcherAndKeepsMigrationBookkeepingWhe { RefreshDatabaseState::$migrated = true; $failure = new RuntimeException('Transaction rollback failed.'); - $dispatcher = m::mock(Dispatcher::class); - $connection = m::mock(PdoConnection::class); - $connection->expects('getEventDispatcher')->andReturn($dispatcher); + $dispatcher = Double::for(Dispatcher::class); + $connection = Double::for(PdoConnection::class); + $connection->expects('getEventDispatcher')->returns($dispatcher); $connection->expects('unsetEventDispatcher')->ordered(); - $connection->expects('inTransaction')->andReturnFalse()->ordered(); + $connection->expects('inTransaction')->returns(false)->ordered(); $connection->expects('forgetRecordModificationState')->ordered(); - $connection->expects('rollBack')->andThrow($failure)->ordered(); + $connection->expects('rollBack')->throws($failure)->ordered(); $connection->expects('setEventDispatcher')->with($dispatcher)->ordered(); - $database = m::mock(DatabaseManager::class); - $database->expects('connection')->with(null)->andReturn($connection); + $database = Double::for(DatabaseManager::class); + $database->expects('connection')->with(null)->returns($connection); $this->app->instance('db', $database); try { @@ -668,32 +671,32 @@ public function testRollbackRestoresTheDispatcherAndKeepsMigrationBookkeepingWhe */ protected function getMockedDatabase(): DatabaseManager { - $connection = m::mock(Connection::class); - $connection->expects('getNameWithReadWriteType')->andReturn('default'); - $eventDispatcher = m::mock(Dispatcher::class); + $connection = Double::for(Connection::class); + $connection->expects('getNameWithReadWriteType')->returns('default'); + $eventDispatcher = Double::for(Dispatcher::class); $connection->expects('getEventDispatcher') - ->twice() - ->andReturn($eventDispatcher); + ->times(2) + ->returns($eventDispatcher); $connection->expects('unsetEventDispatcher') - ->twice(); - $connection->expects('beginTransaction')->andReturnUsing( + ->times(2); + $connection->expects('beginTransaction')->resolves( fn () => $this->app->make('db.transactions')->begin('default', 1) ); $connection->expects('forgetRecordModificationState'); $connection->expects('rollback'); $connection->expects('setEventDispatcher') - ->twice() + ->times(2) ->with($eventDispatcher); $connection->expects('setTransactionManager'); $connection->expects('inTransaction') - ->andReturnTrue(); + ->returns(true); - $database = m::mock(DatabaseManager::class); + $database = Double::for(DatabaseManager::class); $database->expects('connection') - ->twice() + ->times(2) ->with(null) - ->andReturn($connection); + ->returns($connection); return $database; } diff --git a/tests/Foundation/WorkerCachedMaintenanceModeTest.php b/tests/Foundation/WorkerCachedMaintenanceModeTest.php index d356a9a7db..5367ef928a 100644 --- a/tests/Foundation/WorkerCachedMaintenanceModeTest.php +++ b/tests/Foundation/WorkerCachedMaintenanceModeTest.php @@ -9,16 +9,19 @@ use Hypervel\Foundation\WorkerCachedMaintenanceMode; use Hypervel\Support\CarbonImmutable; use Hypervel\Tests\TestCase; -use Mockery as m; +use JMac\Testing\Double; +use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles; use PHPUnit\Framework\Attributes\TestWith; class WorkerCachedMaintenanceModeTest extends TestCase { + use VerifiesDoubles; + public function testActiveCallsDriverOnlyOnceAndCachesResult(): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->once()->andReturn(true); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->returns(true); + $driver->expects('data')->returns(['status' => 503]); $cached = new WorkerCachedMaintenanceMode($driver); @@ -29,9 +32,9 @@ public function testActiveCallsDriverOnlyOnceAndCachesResult(): void public function testDataReturnsCachedPayloadWithoutRereadingDriver(): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->once()->andReturn(true); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503, 'retry' => 60]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->returns(true); + $driver->expects('data')->returns(['status' => 503, 'retry' => 60]); $cached = new WorkerCachedMaintenanceMode($driver); @@ -41,9 +44,9 @@ public function testDataReturnsCachedPayloadWithoutRereadingDriver(): void public function testActiveAndDataAreLoadedAtomically(): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->once()->andReturn(true); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->returns(true); + $driver->expects('data')->returns(['status' => 503]); $cached = new WorkerCachedMaintenanceMode($driver); @@ -57,9 +60,9 @@ public function testActiveAndDataAreLoadedAtomically(): void #[TestWith([true])] public function testEmptyPayloadRechecksActivityBeforeCachingTheSnapshot(bool $remainsActive): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(true, $remainsActive); - $driver->shouldReceive('data')->once()->andReturn([]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(true, $remainsActive); + $driver->expects('data')->returns([]); $cached = new WorkerCachedMaintenanceMode($driver); @@ -73,9 +76,9 @@ public function testSnapshotIsReusedWithinRefreshInterval(): void { CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00')); - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->once()->andReturn(false); - $driver->shouldNotReceive('data'); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->returns(false); + $driver->expects('data')->never(); $cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: 5); @@ -90,9 +93,9 @@ public function testSnapshotRefreshesAfterInterval(): void { CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00')); - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(false, true); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(false, true); + $driver->expects('data')->returns(['status' => 503]); $cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: 5); @@ -107,9 +110,9 @@ public function testSnapshotRefreshesAtExactIntervalBoundary(): void { CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00')); - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(false, true); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(false, true); + $driver->expects('data')->returns(['status' => 503]); $cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: 5); @@ -124,8 +127,8 @@ public function testSnapshotDoesNotRefreshBeforeIntervalAcrossFractionalSeconds( { CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00.900000')); - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->once()->andReturn(false); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->returns(false); $cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: 5); @@ -142,9 +145,9 @@ public function testActivePayloadRefreshesAfterInterval(): void { CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00')); - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(true, true); - $driver->shouldReceive('data')->twice()->andReturn(['status' => 503], ['status' => 418]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(true, true); + $driver->expects('data')->times(2)->returns(['status' => 503], ['status' => 418]); $cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: 5); @@ -159,9 +162,9 @@ public function testZeroRefreshIntervalDisablesTimeRefresh(): void { CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00')); - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->once()->andReturn(false); - $driver->shouldNotReceive('data'); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->returns(false); + $driver->expects('data')->never(); $cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: 0); @@ -176,9 +179,9 @@ public function testNegativeRefreshIntervalDisablesTimeRefresh(): void { CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00')); - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->once()->andReturn(false); - $driver->shouldNotReceive('data'); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->returns(false); + $driver->expects('data')->never(); $cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: -1); @@ -191,9 +194,9 @@ public function testNegativeRefreshIntervalDisablesTimeRefresh(): void public function testFlushCacheResetsSnapshot(): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(true, false); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(true, false); + $driver->expects('data')->returns(['status' => 503]); $cached = new WorkerCachedMaintenanceMode($driver); @@ -208,9 +211,9 @@ public function testFlushCacheForcesRefreshWithinInterval(): void { CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00')); - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(false, true); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(false, true); + $driver->expects('data')->returns(['status' => 503]); $cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: 60); @@ -224,10 +227,10 @@ public function testFlushCacheForcesRefreshWithinInterval(): void public function testActivateDelegatesToDriverAndFlushesCache(): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(false, true); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); - $driver->shouldReceive('activate')->once()->with(['status' => 503]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(false, true); + $driver->expects('data')->returns(['status' => 503]); + $driver->expects('activate')->with(['status' => 503]); $cached = new WorkerCachedMaintenanceMode($driver); @@ -240,10 +243,10 @@ public function testActivateDelegatesToDriverAndFlushesCache(): void public function testDeactivateDelegatesToDriverAndFlushesCache(): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(true, false); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); - $driver->shouldReceive('deactivate')->once(); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(true, false); + $driver->expects('data')->returns(['status' => 503]); + $driver->expects('deactivate'); $cached = new WorkerCachedMaintenanceMode($driver); @@ -256,9 +259,9 @@ public function testDeactivateDelegatesToDriverAndFlushesCache(): void public function testWhenNotActiveDataReturnsEmptyArrayWithoutCallingDriverData(): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->once()->andReturn(false); - $driver->shouldNotReceive('data'); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->returns(false); + $driver->expects('data')->never(); $cached = new WorkerCachedMaintenanceMode($driver); @@ -267,9 +270,9 @@ public function testWhenNotActiveDataReturnsEmptyArrayWithoutCallingDriverData() public function testAfterFlushAndRereadDecoratorReflectsUpdatedState(): void { - $driver = m::mock(MaintenanceModeContract::class); - $driver->shouldReceive('active')->twice()->andReturn(true, false); - $driver->shouldReceive('data')->once()->andReturn(['status' => 503]); + $driver = Double::for(MaintenanceModeContract::class); + $driver->expects('active')->times(2)->returns(true, false); + $driver->expects('data')->returns(['status' => 503]); $cached = new WorkerCachedMaintenanceMode($driver); From 4d4ad4a29bc16904b6e97afcd2a517d0fb1b7e0b Mon Sep 17 00:00:00 2001 From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:36:24 +0000 Subject: [PATCH 4/4] Preserve cache tests against unexpected writes and pruning Make the disabled-pruning query builder and stack cache layer doubles strict so unconfigured reads, writes and deletions fail as they did before the Double conversion. Apply the same protection to tagged cache layers while retaining explicit negative assertions and real-store compensation coverage. All three affected test files pass. Full formatting and the final targeted formatting check pass. No production behavior or dependency requirements change. --- tests/Cache/CacheDatabaseLockTest.php | 1 + tests/Cache/CacheStackStoreTagsTest.php | 60 ++++++------ tests/Cache/CacheStackStoreTest.php | 124 ++++++++++++------------ 3 files changed, 93 insertions(+), 92 deletions(-) diff --git a/tests/Cache/CacheDatabaseLockTest.php b/tests/Cache/CacheDatabaseLockTest.php index 404a6b3251..59ca834121 100644 --- a/tests/Cache/CacheDatabaseLockTest.php +++ b/tests/Cache/CacheDatabaseLockTest.php @@ -250,6 +250,7 @@ public function testLockCanBeAcquiredWithoutAutomaticPruning(?array $lottery): v { [$lock, $table] = $this->getLock(lockLottery: $lottery); + $table->strict(); $table->expects('insertOrIgnore')->returns(1); $this->assertTrue($lock->acquire()); diff --git a/tests/Cache/CacheStackStoreTagsTest.php b/tests/Cache/CacheStackStoreTagsTest.php index 1d683f6189..9e8ad4a34b 100644 --- a/tests/Cache/CacheStackStoreTagsTest.php +++ b/tests/Cache/CacheStackStoreTagsTest.php @@ -97,7 +97,7 @@ public function testStringKeyedLayersUseZeroBasedIndexesInCompositionErrors(): v public function testInvalidNestedStackDoesNotCallGetTagMode(): void { - $taggable = Double::for(TaggableStore::class); + $taggable = Double::for(TaggableStore::class)->strict(); $taggable->expects('supportsTags')->returns(false); $taggable->expects('getTagMode')->never(); @@ -108,7 +108,7 @@ public function testInvalidNestedStackDoesNotCallGetTagMode(): void public function testValidationRunsOnce(): void { - $taggable = Double::for(TaggableStore::class); + $taggable = Double::for(TaggableStore::class)->strict(); $taggable->expects('supportsTags')->returns(true); $taggable->expects('getTagMode')->returns(TagMode::Any); @@ -123,7 +123,7 @@ public function testTaggedPutWritesPlainUpperLayersAndTaggedLowerLayersWithTtlCl { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $plain->expects('put') ->with('key', Argument::satisfies(fn (array $record): bool => $record['value'] === 'value' && isset($record['expiration'])), 3) @@ -145,7 +145,7 @@ public function testTaggedForeverHonorsLayerTtlClamp(): void { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $plain->expects('put')->with('key', ['value' => 'value'], 3)->returns(true); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); @@ -162,7 +162,7 @@ public function testTaggedForeverHonorsLayerTtlClamp(): void public function testTaggedPutClampsTtlOnTaggableLayer(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); $taggedCache->expects('put') @@ -179,7 +179,7 @@ public function testTaggedPutClampsTtlOnTaggableLayer(): void public function testTaggedForeverClampsToPutOnTaggableLayerWithTtlOverride(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); $taggedCache->expects('put')->with('key', ['value' => 'value'], 3)->returns(true); @@ -196,7 +196,7 @@ public function testTaggedWriteRollsBackWrittenLayersOnFailure(): void { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $plain->expects('put')->returns(true); $plain->expects('forget')->with('key')->returns(true); @@ -215,7 +215,7 @@ public function testTaggedWriteRollsBackWrittenLayersWhenLowerLayerThrows(): voi { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $exception = new RuntimeException('write failed'); $plain->expects('put')->returns(true); @@ -251,7 +251,7 @@ public function testTaggedWriteRollsBackWrittenLayersWhenLowerLayerThrows(): voi public function testTaggedIncrementWritesThroughTaggedPath(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('get')->with('counter')->returns(['value' => 1]); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); @@ -286,7 +286,7 @@ public function testTaggedIncrementDoesNotTreatFailedRepairAsMissingAndPreserves { $plain = $this->nonTaggableStore(); $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $record = ['value' => 5]; $incrementedRecord = ['value' => 6]; @@ -308,7 +308,7 @@ public function testTaggedIncrementDoesNotTreatFailedRepairAsMissingAndPreserves public function testTaggedRememberReadsPlainAndWritesTaggedOnMiss(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('get')->with('0')->returns(null); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); @@ -361,7 +361,7 @@ public function testTaggedRememberHandlesIncompleteClassBeforeDispatchingHitEven public function testTaggedRememberMissDispatchesRepositoryReadAndWriteEvents(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('get')->with('key')->returns(null); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); @@ -388,7 +388,7 @@ public function testTaggedRememberMissDispatchesRepositoryReadAndWriteEvents(): public function testTaggedPutDispatchesRepositoryWriteFailureEvents(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); $taggedCache->expects('put')->with('key', Argument::type('array'), 60)->returns(false); @@ -411,7 +411,7 @@ public function testTaggedPutDispatchesRepositoryWriteFailureEvents(): void public function testStackAnyModeTaggedCacheSkipsEventDispatchSeamWithoutListenersAndEntersItWithListeners(): void { $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('get')->times(2)->returns(null); $taggable->expects('tags')->times(2)->with(['tag'])->returns($taggedCache); $taggedCache->expects('put')->times(2)->with(Argument::type('string'), Argument::type('array'), 60)->returns(true); @@ -506,7 +506,7 @@ public function testTaggedPutDispatchesRepositoryWriteFailureEventWhenTheStoreTh { $exception = new RuntimeException('write failed'); $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); $taggedCache->expects('put')->with('key', Argument::type('array'), 60)->throws($exception); $taggable->expects('forget')->with('key')->returns(true); @@ -537,7 +537,7 @@ public function testTaggedPutDoesNotDispatchFailureEventWhenTheStoreIsCanceled(b $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); $taggedCache->expects('put')->with('key', Argument::type('array'), 60)->throws($cancellation); $taggable->expects('forget')->with('key')->returns(true); @@ -561,7 +561,7 @@ public function testTaggedForeverDispatchesRepositoryWriteFailureEventWhenTheSto { $exception = new RuntimeException('forever write failed'); $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); $taggedCache->expects('forever')->with('key', ['value' => 'value'])->throws($exception); $taggable->expects('forget')->with('key')->returns(true); @@ -593,7 +593,7 @@ public function testTaggedForeverDoesNotDispatchFailureEventWhenTheStoreIsCancel $cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation); } $taggable = $this->anyModeTaggableStore(); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); $taggedCache->expects('forever')->with('key', ['value' => 'value'])->throws($cancellation); $taggable->expects('forget')->with('key')->returns(true); @@ -707,7 +707,7 @@ public function testClearFlushesTaggableLayersOnly(): void { $taggable = $this->anyModeTaggableStore(); $tagSet = Double::for(TagSet::class); - $taggedCache = Double::for(TaggedCache::class); + $taggedCache = Double::for(TaggedCache::class)->strict(); $taggable->expects('tags')->with(['tag'])->returns($taggedCache); $taggedCache->expects('getTags')->returns($tagSet); @@ -724,8 +724,8 @@ public function testClearFlushesEveryTaggableLayerAndAggregatesFalseResults(): v { $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = Double::for(TaggedCache::class); - $secondTaggedCache = Double::for(TaggedCache::class); + $firstTaggedCache = Double::for(TaggedCache::class)->strict(); + $secondTaggedCache = Double::for(TaggedCache::class)->strict(); $firstTagSet = Double::for(TagSet::class); $secondTagSet = Double::for(TagSet::class); @@ -746,8 +746,8 @@ public function testTagSetFlushAttemptsEveryLayerAndPreservesTheFirstException() $firstException = new RuntimeException('first tag flush failed'); $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = Double::for(TaggedCache::class); - $secondTaggedCache = Double::for(TaggedCache::class); + $firstTaggedCache = Double::for(TaggedCache::class)->strict(); + $secondTaggedCache = Double::for(TaggedCache::class)->strict(); $firstTagSet = Double::for(TagSet::class); $secondTagSet = Double::for(TagSet::class); @@ -776,7 +776,7 @@ public function testTagSetFlushStopsImmediatelyOnCancellation(bool $cleanupThrow } $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = Double::for(TaggedCache::class); + $firstTaggedCache = Double::for(TaggedCache::class)->strict(); $firstTagSet = Double::for(TagSet::class); $firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache); @@ -797,8 +797,8 @@ public function testClearDispatchesFailureEventWithExactTagSetException(): void $exception = new RuntimeException('tag flush failed'); $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = Double::for(TaggedCache::class); - $secondTaggedCache = Double::for(TaggedCache::class); + $firstTaggedCache = Double::for(TaggedCache::class)->strict(); + $secondTaggedCache = Double::for(TaggedCache::class)->strict(); $firstTagSet = Double::for(TagSet::class); $secondTagSet = Double::for(TagSet::class); $firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache); @@ -833,7 +833,7 @@ public function testClearCancellationSkipsFailureEventAndRemainingTaggableLayers } $firstTaggable = $this->anyModeTaggableStore(); $secondTaggable = $this->anyModeTaggableStore(); - $firstTaggedCache = Double::for(TaggedCache::class); + $firstTaggedCache = Double::for(TaggedCache::class)->strict(); $firstTagSet = Double::for(TagSet::class); $firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache); $firstTaggedCache->expects('getTags')->returns($firstTagSet); @@ -859,7 +859,7 @@ public function testClearCancellationSkipsFailureEventAndRemainingTaggableLayers */ private function anyModeTaggableStore(): TaggableStore&DoubleInterface { - $store = Double::for(TaggableStore::class); + $store = Double::for(TaggableStore::class)->strict(); $store->allows('supportsTags')->returns(true); $store->allows('getTagMode')->returns(TagMode::Any); @@ -871,7 +871,7 @@ private function anyModeTaggableStore(): TaggableStore&DoubleInterface */ private function allModeTaggableStore(): TaggableStore&DoubleInterface { - $store = Double::for(TaggableStore::class); + $store = Double::for(TaggableStore::class)->strict(); $store->allows('supportsTags')->returns(true); $store->allows('getTagMode')->returns(TagMode::All); @@ -883,7 +883,7 @@ private function allModeTaggableStore(): TaggableStore&DoubleInterface */ private function nonTaggableStore(): Store&DoubleInterface { - return Double::for(Store::class); + return Double::for(Store::class)->strict(); } /** diff --git a/tests/Cache/CacheStackStoreTest.php b/tests/Cache/CacheStackStoreTest.php index b42df6259a..7f29d964b5 100644 --- a/tests/Cache/CacheStackStoreTest.php +++ b/tests/Cache/CacheStackStoreTest.php @@ -66,8 +66,8 @@ public function testRetrieveItemFromStoreStacked(): void public function testAuthoritativeReadUsesBottomLayerWithoutRepairingUpperLayer(): void { - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $bottom->expects('get')->with('key')->returns(['value' => 'fresh']); $top->expects('get')->never(); $top->expects('put')->never(); @@ -114,7 +114,7 @@ public function testFlexibleSkipsRefreshWhenBottomMarkerIsNewerThanUpperLayer(): #[DataProvider('authoritativeRecordProvider')] public function testAuthoritativeReadHandlesSingleLayerRecords(mixed $record, mixed $expected): void { - $store = Double::for(ArrayStore::class); + $store = Double::for(ArrayStore::class)->strict(); $store->expects('get')->with('key')->returns($record); $this->assertSame($expected, (new StackStore([$store]))->getAuthoritativeRaw('key')); @@ -133,9 +133,9 @@ public static function authoritativeRecordProvider(): array public function testAuthoritativeReadRecursesThroughBottomStack(): void { - $outerTop = Double::for(ArrayStore::class); - $innerTop = Double::for(ArrayStore::class); - $innerBottom = Double::for(ArrayStore::class); + $outerTop = Double::for(ArrayStore::class)->strict(); + $innerTop = Double::for(ArrayStore::class)->strict(); + $innerBottom = Double::for(ArrayStore::class)->strict(); $innerBottom->expects('get')->with('key')->returns([ 'value' => ['value' => 'fresh'], ]); @@ -152,8 +152,8 @@ public function testAuthoritativeReadRecursesThroughBottomStack(): void public function testAuthoritativeReadRecursesThroughBottomFailoverStore(): void { - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $bottom->expects('get')->with('key')->returns(['value' => 'fresh']); $top->expects('get')->never(); @@ -208,9 +208,9 @@ public function testReadRepairExceptionPropagates(): void public function testThreeLayerReadContinuesRepairAfterInnerFailure(): void { - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $record = ['value' => 'bar']; $top->expects('get')->with('foo')->returns(null); @@ -356,9 +356,9 @@ public function testPutItemToStoreFailedAndRollback(): void public function testPutCompensatesEarlierLayerWhenLowerLayerThrows(): void { $sequence = []; - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $exception = new RuntimeException('write failed'); $top->expects('put')->returns(true); @@ -388,9 +388,9 @@ public function testPutCompensatesEarlierLayerWhenLowerLayerThrows(): void public function testPutCompensatesCompletedLayersInReverseOrder(): void { $sequence = []; - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $top->expects('put')->returns(true); $middle->expects('put')->returns(true); @@ -413,8 +413,8 @@ public function testPutCompensatesCompletedLayersInReverseOrder(): void public function testPutPreservesFalseResultWhenCompensationThrows(): void { - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $top->expects('put')->returns(true); $bottom->expects('put')->returns(false); @@ -425,8 +425,8 @@ public function testPutPreservesFalseResultWhenCompensationThrows(): void public function testPutPreservesWriteFailureWhenCompensationAlsoThrows(): void { - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $exception = new RuntimeException('write failed'); $top->expects('put')->returns(true); @@ -444,8 +444,8 @@ public function testPutPreservesWriteFailureWhenCompensationAlsoThrows(): void public function testPutCompensatesLayerWhoseWriteThrows(): void { - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $exception = new RuntimeException('write failed'); $top->expects('put')->throws($exception); @@ -523,8 +523,8 @@ public function put(string $key, mixed $value, int $seconds): bool public function testPutPreservesOriginalCancellationAndCompletesCompensation(bool $cleanupThrows): void { $sequence = []; - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $cancellation = new CanceledException('write canceled'); if ($cleanupThrows) { $cancellation = new RuntimeException('Write cleanup failed.', previous: $cancellation); @@ -559,8 +559,8 @@ public function testPutPreservesOriginalCancellationAndCompletesCompensation(boo public function testPutCleanupCancellationSupersedesOrdinaryWriteFailure(bool $cleanupThrows): void { $sequence = []; - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $cleanupCancellation = new CanceledException('cleanup canceled'); if ($cleanupThrows) { $cleanupCancellation = new RuntimeException('Release cleanup failed.', previous: $cleanupCancellation); @@ -593,8 +593,8 @@ public function testPutCleanupCancellationSupersedesOrdinaryWriteFailure(bool $c #[TestWith([true])] public function testPutCleanupCancellationSupersedesFalseWriteResult(bool $cleanupThrows): void { - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $cleanupCancellation = new CanceledException('cleanup canceled'); if ($cleanupThrows) { $cleanupCancellation = new RuntimeException('Release cleanup failed.', previous: $cleanupCancellation); @@ -628,9 +628,9 @@ public function testMany(): void public function testManyReadsEachLayerOnceAndRestoresLowerHitsWithBatchedWrites(): void { $sequence = []; - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $expiration = CarbonImmutable::now()->getTimestamp() + 100; $shorterExpiration = CarbonImmutable::now()->getTimestamp() + 50; $middleRecord = ['value' => 'middle', 'expiration' => $expiration]; @@ -694,9 +694,9 @@ public function testManyReadsEachLayerOnceAndRestoresLowerHitsWithBatchedWrites( public function testManyMeasuresRemainingTtlBeforeEachRestoreAndSkipsRecordsThatExpired(): void { - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $expiringRecord = ['value' => 'expiring', 'expiration' => CarbonImmutable::now()->getTimestamp() + 1]; $bottomRecord = ['value' => 'bottom', 'expiration' => CarbonImmutable::now()->getTimestamp() + 100]; $advance = static function (int $seconds, mixed $result): Closure { @@ -785,9 +785,9 @@ public function testPutManyReturnsTrueForEmptyInput(): void public function testPutManyFailureForgetsTheBatchFromTheFailedAndCompletedLayersDeepestFirst(): void { $sequence = []; - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $top->expects('putMany')->returns(true); $middle->expects('putMany')->returns(false); @@ -856,8 +856,8 @@ public function putMany(array $values, int $seconds): bool public function testPutManyCleanupContinuesAfterCancellationStopsAtOrdinaryFailureAndKeepsCancellation(bool $cleanupThrows): void { $sequence = []; - $top = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $cleanupCancellation = new CanceledException('cleanup canceled'); if ($cleanupThrows) { $cleanupCancellation = new RuntimeException('Release cleanup failed.', previous: $cleanupCancellation); @@ -905,7 +905,7 @@ public function testPutManyCleanupContinuesAfterCancellationStopsAtOrdinaryFailu #[DataProvider('proxyPutManyTtlProvider')] public function testProxyPutManyAppliesLayerTtl(?int $layerTtl, int $requestedTtl, int $expectedTtl): void { - $store = Double::for(ArrayStore::class); + $store = Double::for(ArrayStore::class)->strict(); $store->expects('putMany')->with(['key' => 'value'], $expectedTtl)->returns(true); $proxy = new StackStoreProxy($store, $layerTtl); @@ -925,7 +925,7 @@ public static function proxyPutManyTtlProvider(): array public function testProxyPutManyReturnsUnderlyingResult(): void { - $store = Double::for(ArrayStore::class); + $store = Double::for(ArrayStore::class)->strict(); $store->expects('putMany')->with(['key' => 'value'], 60)->returns(false); $this->assertFalse((new StackStoreProxy($store, 60))->putMany(['key' => 'value'], 90)); @@ -1068,9 +1068,9 @@ public function testForgetFailed(): void public function testForgetAttemptsEveryLayerAndPreservesTheEarliestFailure(): void { - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $exception = new RuntimeException('first failure'); $top->expects('forget')->with('foo')->throws($exception); @@ -1089,9 +1089,9 @@ public function testForgetAttemptsEveryLayerAndPreservesTheEarliestFailure(): vo #[TestWith([true])] public function testForgetCancellationSupersedesEarlierFailureAndStopsFurtherLayers(bool $cleanupThrows): void { - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $cancellation = new CanceledException('forget canceled'); if ($cleanupThrows) { $cancellation = new RuntimeException('Forget cleanup failed.', previous: $cancellation); @@ -1131,9 +1131,9 @@ public function testFlushFailed(): void public function testFlushAttemptsEveryLayerAndPreservesTheEarliestFailure(): void { - $top = Double::for(ArrayStore::class); - $middle = Double::for(ArrayStore::class); - $bottom = Double::for(ArrayStore::class); + $top = Double::for(ArrayStore::class)->strict(); + $middle = Double::for(ArrayStore::class)->strict(); + $bottom = Double::for(ArrayStore::class)->strict(); $exception = new RuntimeException('first failure'); $top->expects('flush')->with(Argument::none())->throws($exception); @@ -1150,9 +1150,9 @@ public function testFlushAttemptsEveryLayerAndPreservesTheEarliestFailure(): voi public function testThreeStores(): void { - $array = Double::for(ArrayStore::class); - $swoole = Double::for(SwooleStore::class); - $redis = Double::for(RedisStore::class); + $array = Double::for(ArrayStore::class)->strict(); + $swoole = Double::for(SwooleStore::class)->strict(); + $redis = Double::for(RedisStore::class)->strict(); $store = new StackStore([$array, $swoole, $redis]); @@ -1199,8 +1199,8 @@ public function testInvalidRecord(): void public function testProxyMaxTTL(): void { - $swoole = Double::for(SwooleStore::class); - $redis = Double::for(RedisStore::class); + $swoole = Double::for(SwooleStore::class)->strict(); + $redis = Double::for(RedisStore::class)->strict(); $key = 'foo'; $value = 'bar'; @@ -1222,8 +1222,8 @@ public function testProxyMaxTTL(): void public function testProxyMaxTTLWithForever(): void { - $swoole = Double::for(SwooleStore::class); - $redis = Double::for(RedisStore::class); + $swoole = Double::for(SwooleStore::class)->strict(); + $redis = Double::for(RedisStore::class)->strict(); $key = 'foo'; $value = 'bar'; @@ -1271,8 +1271,8 @@ public function testTouchProxyCapsMaxTTL(): void { CarbonImmutable::setTestNow(CarbonImmutable::now()); - $swoole = Double::for(SwooleStore::class); - $redis = Double::for(RedisStore::class); + $swoole = Double::for(SwooleStore::class)->strict(); + $redis = Double::for(RedisStore::class)->strict(); $key = 'foo'; $value = 'bar'; @@ -1296,8 +1296,8 @@ public function testTouchProxyCapsMaxTTL(): void */ private function createStores(): void { - $this->redis = Double::for(RedisStore::class); - $this->swoole = Double::for(SwooleStore::class); + $this->redis = Double::for(RedisStore::class)->strict(); + $this->swoole = Double::for(SwooleStore::class)->strict(); $this->store = new StackStore([$this->swoole, $this->redis]); } }