diff --git a/AGENTS.md b/AGENTS.md
index 196c708013..2e6e288931 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -596,7 +596,11 @@ A per-package base class is only justified when there is shared setUp logic —
Use Double for test doubles in new tests. When porting, convert direct Mockery mocks and spies to Double regardless of the upstream library; keep upstream PHPUnit doubles. Retain Mockery where required to use or test framework APIs backed by it, such as `$this->mock()`, facade expectations and `Sanctum::actingAs()`. Add `JMac\Testing\Integrations\PHPUnit\VerifiesDoubles` to each test class using Double; it owns verification and cleanup.
-Double is lenient by default. Use `expects('method')->never()` to forbid a call, or `unused()` after exercising the code to assert no calls occurred. `allows()->with(...)` neither requires a matching call nor rejects other arguments. `expects()->with(...)` requires the call and rejects unmatched arguments for that method. Use `strict()` when calls to unconfigured methods must fail.
+Double is lenient by default. Use `expects('method')->never()` to forbid a call, or `unused()` after exercising the code to assert no calls occurred. `allows()->with(...)` neither requires a matching call nor rejects other arguments. `expects()->with(...)` requires the call and rejects unmatched arguments for that method. Use `strict()` unless the test deliberately ignores unrelated calls; this applies equally to tests ported from upstream.
+
+`with()` compares objects, including doubles, using `==`. Use `Argument::same($object)` when the exact instance matters or to preserve Mockery’s default identity check.
+
+Keep matcher predicates free of side effects, including assertions. Use `Argument::capture()` to save an argument or `resolves()` to record a matched call.
Do not overlap `allows()` stubs with `expects()` constraints when enforcing maximum call counts or `never()`; a matching stub can absorb those calls regardless of registration order.
diff --git a/composer.json b/composer.json
index ff19c6d836..b21386286e 100644
--- a/composer.json
+++ b/composer.json
@@ -127,7 +127,7 @@
"fakerphp/faker": "^1.24",
"friendsofphp/php-cs-fixer": "^3.57.2",
"intervention/image": "^4.2",
- "jasonmccreary/double": "^1.1.1",
+ "jasonmccreary/double": "dev-master",
"league/flysystem-ftp": "^3.36",
"league/flysystem-google-cloud-storage": "^3.0",
"league/flysystem-sftp-v3": "^3.36",
diff --git a/src/auth/src/Access/Gate.php b/src/auth/src/Access/Gate.php
index ee92b1ed9b..2320ebabb6 100644
--- a/src/auth/src/Access/Gate.php
+++ b/src/auth/src/Access/Gate.php
@@ -633,9 +633,9 @@ public function getPolicyFor(object|string $class): mixed
$policyClass = $this->policyClassCache[$class] ?? null;
if ($policyClass === null) {
- // Only declared model names are cached. Other inputs may be user data, so their
- // policy guesses are normalized to avoid unbounded worker state. For those inputs,
- // register policies explicitly when relying on container configuration for PHP class aliases.
+ // Cache only declared model names. Normalize other guesses so the container doesn't
+ // cache a policy instance per user-supplied spelling. Register policies explicitly
+ // when those inputs rely on container configuration for PHP class aliases.
$isDeclaredClass = class_exists($class) && (new ReflectionClass($class))->getName() === $class;
$policyClass = $this->resolvePolicyClass($class, $isDeclaredClass);
diff --git a/src/database/src/ConnectionResolver.php b/src/database/src/ConnectionResolver.php
index 2c5d683204..ac9db229ff 100755
--- a/src/database/src/ConnectionResolver.php
+++ b/src/database/src/ConnectionResolver.php
@@ -258,11 +258,21 @@ public function connectionDateFormat(UnitEnum|string|null $name = null): string
*/
public static function releaseIdleConnections(): void
{
+ $failure = null;
+
foreach (CoroutineContext::getContainer() ?? [] as $value) {
if ($value instanceof ConnectionLease) {
- $value->releaseIfIdle();
+ try {
+ $value->releaseIfIdle();
+ } catch (Throwable $exception) {
+ $failure = Coroutine::preferCancellation($failure, $exception);
+ }
}
}
+
+ if ($failure !== null) {
+ throw $failure;
+ }
}
/**
diff --git a/tests/Ai/BroadcastBatchingTest.php b/tests/Ai/BroadcastBatchingTest.php
index 22fd1963f1..0a94d27aaa 100644
--- a/tests/Ai/BroadcastBatchingTest.php
+++ b/tests/Ai/BroadcastBatchingTest.php
@@ -241,7 +241,7 @@ 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 = Double::for(ConnectionLease::class);
+ $lease = Double::for(ConnectionLease::class)->strict();
$lease->expects('releaseIfIdle')->throws($failure);
$waiting = new Channel(1);
$senderCanceled = false;
diff --git a/tests/Ai/ConcurrentToolsTest.php b/tests/Ai/ConcurrentToolsTest.php
index ad7e0d57da..9aff7098af 100644
--- a/tests/Ai/ConcurrentToolsTest.php
+++ b/tests/Ai/ConcurrentToolsTest.php
@@ -74,7 +74,7 @@ public function testOptedInToolsAreBoundedOrderedAndUseTheCapturedContext(bool $
Coroutine::afterCreated(static function (): void {
CoroutineContext::set('tool-test.account', 'startup');
});
- $providerGateway = Double::for(Gateway::class);
+ $providerGateway = Double::for(Gateway::class)->strict();
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;
@@ -82,7 +82,7 @@ public function testOptedInToolsAreBoundedOrderedAndUseTheCapturedContext(bool $
$accounts = [];
$requestIds = [];
$resolvedProviders = [];
- $tool = Double::for(NamedTool::class);
+ $tool = Double::for(NamedTool::class)->strict();
$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());
@@ -100,7 +100,7 @@ public function testOptedInToolsAreBoundedOrderedAndUseTheCapturedContext(bool $
}
});
$calls = [new ToolCall('first', 'tool', []), new ToolCall('second', 'tool', []), new ToolCall('third', 'tool', [])];
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$provider->allows('name')->returns('provider');
$results = [];
$gateway = $this->gateway($streaming, $calls, $results);
@@ -134,9 +134,9 @@ public static function deliveryModes(): array
public function testInvalidConcurrencyFailsClearlyThroughTheLoop(): void
{
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$provider->allows('name')->returns('provider');
- $gateway = Double::for(StepTextGateway::class);
+ $gateway = Double::for(StepTextGateway::class)->strict();
$gateway->expects('generateTextStep')->returns(new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta));
$this->expectException(InvalidArgumentException::class);
@@ -164,7 +164,7 @@ public function testToolFailureCancelsAndJoinsTheOtherTools(bool $canceled, bool
$active = 0;
$resumed = false;
- $tool = Double::for(NamedTool::class);
+ $tool = Double::for(NamedTool::class)->strict();
$tool->allows('name')->returns('tool');
$tool->expects('handle')->times(2)->resolves(function (Request $request) use ($failure, &$active, &$resumed): string {
++$active;
@@ -184,14 +184,14 @@ public function testToolFailureCancelsAndJoinsTheOtherTools(bool $canceled, bool
--$active;
}
});
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$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', Double::for(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)->strict(), $provider, 'model', $events));
} catch (Throwable $exception) {
$caught = $exception;
}
@@ -213,7 +213,7 @@ public function testAbandoningLiveSubAgentOutputCancelsAndJoinsItsProducers(): v
$active = 0;
$resumed = false;
$waiting = new Channel(1);
- $agent = Double::for(Agent::class, CanActAsTool::class);
+ $agent = Double::for(Agent::class, CanActAsTool::class)->strict();
$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 {
@@ -228,7 +228,7 @@ public function testAbandoningLiveSubAgentOutputCancelsAndJoinsItsProducers(): v
}
});
});
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$provider->allows('name')->returns('provider');
$results = [];
$gateway = $this->gateway(true, [
@@ -270,7 +270,7 @@ public function testCancelingTheConsumerCancelsAndJoinsTheTools(bool $throwExcep
$resumed = false;
$caught = null;
$waiting = new Channel(1);
- $tool = Double::for(NamedTool::class);
+ $tool = Double::for(NamedTool::class)->strict();
$tool->allows('name')->returns('tool');
$tool->expects('handle')->times(2)->resolves(function () use ($waiting, &$active, &$resumed): string {
++$active;
@@ -284,7 +284,7 @@ public function testCancelingTheConsumerCancelsAndJoinsTheTools(bool $throwExcep
--$active;
}
});
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$provider->allows('name')->returns('provider');
$results = [];
$gateway = $this->gateway(true, [new ToolCall('first', 'tool', []), new ToolCall('second', 'tool', [])], $results, completes: false);
@@ -335,7 +335,7 @@ private function gateway(bool $streaming, array $calls, array &$results, bool $c
return new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta);
};
- $gateway = Double::for(StepTextGateway::class);
+ $gateway = Double::for(StepTextGateway::class)->strict();
if ($streaming) {
$gateway->expects('generateStreamStep')->times($completes ? 2 : 1)->resolves(static function (...$arguments) use ($response): Generator {
diff --git a/tests/Ai/CoroutineIsolationTest.php b/tests/Ai/CoroutineIsolationTest.php
index e30559c75f..72fa504084 100644
--- a/tests/Ai/CoroutineIsolationTest.php
+++ b/tests/Ai/CoroutineIsolationTest.php
@@ -186,7 +186,7 @@ function (): array {
public function testOverlappingCallbacksReserveSeparateSequenceEntries(): void
{
- $provider = Double::for(AudioProvider::class);
+ $provider = Double::for(AudioProvider::class)->strict();
$provider->allows('name')->returns('audio');
$gateway = new FakeAudioGateway([
function (): string {
@@ -209,7 +209,7 @@ public function testSharedGenerationLoopKeepsRepairSettingsLocalWhileApprovalChe
{
$repairStarted = new Channel(1);
$ordinaryStarted = new Channel(1);
- $tool = Double::for(ApprovableNamedTool::class);
+ $tool = Double::for(ApprovableNamedTool::class)->strict();
$tool->allows('name')->returns('known');
$tool->expects('shouldRequestApproval')->times(2)->resolves(static function (Request $request) use ($repairStarted, $ordinaryStarted): null {
if ($request['repair']) {
@@ -223,9 +223,9 @@ public function testSharedGenerationLoopKeepsRepairSettingsLocalWhileApprovalChe
return null;
});
$tool->expects('handle')->times(2)->returns('done');
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$provider->allows('name')->returns('provider');
- $gateway = Double::for(StepTextGateway::class);
+ $gateway = Double::for(StepTextGateway::class)->strict();
$steps = [];
$gateway->expects('generateTextStep')->times(4)->resolves(static function (...$arguments) use (&$steps): StepResponse {
$instructions = $arguments[2];
@@ -263,9 +263,9 @@ function () use ($repairStarted, $loop, $provider, $tool): TextResponse {
#[DataProvider('generatedResponses')]
public function testGeneratedResponseKeepsItsFilenameAcrossCoroutines(GeneratedImage|AudioResponse $response): void
{
- $disk = Double::for(Filesystem::class);
+ $disk = Double::for(Filesystem::class)->strict();
$disk->expects('put')->with(Argument::type('string'), 'generated bytes', [])->times(3)->returns(true);
- $filesystems = Double::for(FilesystemFactory::class);
+ $filesystems = Double::for(FilesystemFactory::class)->strict();
$filesystems->expects('disk')->with('generated')->times(3)->returns($disk);
Container::getInstance()->instance(FilesystemFactory::class, $filesystems);
@@ -430,15 +430,15 @@ protected function captureAccountContext(): Closure
*/
protected function manager(): AiManager
{
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$application->allows('make')->with('config')->returns(new Repository([
'ai' => [
'default' => 'configured',
'providers' => ['configured' => ['driver' => 'custom', 'key' => 'configured-key']],
],
]));
- $gateway = Double::for(Gateway::class);
- $events = Double::for(Dispatcher::class);
+ $gateway = Double::for(Gateway::class)->strict();
+ $events = Double::for(Dispatcher::class)->strict();
$manager = new AiManager($application->instance());
$manager->extend('custom', static fn (Application $application, array $config): Provider => new IsolationTestProvider($gateway, $config, $events));
diff --git a/tests/Ai/Feature/AgentProviderSelectionTest.php b/tests/Ai/Feature/AgentProviderSelectionTest.php
index 6cf86fb43d..850572cb87 100644
--- a/tests/Ai/Feature/AgentProviderSelectionTest.php
+++ b/tests/Ai/Feature/AgentProviderSelectionTest.php
@@ -216,7 +216,7 @@ protected function getProvidersAndModels(Provider|Lab|array|string|null $provide
#[DataProvider('generationMethods')]
public function testContractOnlyProvidersCanFailOverAndDispatchTheirIdentity(string $method): void
{
- $primary = Double::for(TextProvider::class);
+ $primary = Double::for(TextProvider::class)->strict();
$primary->expects($method)->throws(RateLimitedException::forProvider('contract'));
Ai::extend('contract', static fn (): TextProvider => $primary);
@@ -260,7 +260,7 @@ public static function generationMethods(): array
protected function provider(array $config): Provider&DoubleInterface
{
$provider = Double::for(ProviderSelectionTextProvider::class)->passthru();
- $provider->__construct(Double::for(Gateway::class), $config, $this->app->make(Dispatcher::class));
+ $provider->__construct(Double::for(Gateway::class)->strict(), $config, $this->app->make(Dispatcher::class));
$provider->allows('defaultTextModel')->returns('test-model');
return $provider;
diff --git a/tests/Ai/Feature/AiManagerTest.php b/tests/Ai/Feature/AiManagerTest.php
index 7b295f7341..04de9d3189 100644
--- a/tests/Ai/Feature/AiManagerTest.php
+++ b/tests/Ai/Feature/AiManagerTest.php
@@ -144,7 +144,7 @@ public function testDriverExtensionsSurviveBetweenQueueJobs(): void
public function testCustomDriversMayImplementProviderContractsWithoutExtendingTheBaseClass(): void
{
- $provider = Double::for(AudioProvider::class);
+ $provider = Double::for(AudioProvider::class)->strict();
$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 64461765e9..958e94c04f 100644
--- a/tests/Ai/Feature/BroadcastAgentTest.php
+++ b/tests/Ai/Feature/BroadcastAgentTest.php
@@ -172,7 +172,7 @@ public function testAnOversizedBroadcastFrameDoesNotAbortTheStreamAndThenStillRe
{
AssistantAgent::fake(['Hello world']);
- $pending = Double::for(AnonymousEvent::class);
+ $pending = Double::for(AnonymousEvent::class)->strict();
$pending->allows('as');
$pending->allows('with');
$pending->expects('sendNow')->times(minimum: 1)->throws(new BroadcastException('Payload too large'));
diff --git a/tests/Ai/Feature/EmbeddingsCacheTest.php b/tests/Ai/Feature/EmbeddingsCacheTest.php
index 7529314a2b..9f92d61153 100644
--- a/tests/Ai/Feature/EmbeddingsCacheTest.php
+++ b/tests/Ai/Feature/EmbeddingsCacheTest.php
@@ -342,7 +342,7 @@ public static function cacheModes(): array
public function testSameNameOnDemandProvidersRetainTheirOwnCacheIdentity(): void
{
- $gateway = Double::for(Gateway::class);
+ $gateway = Double::for(Gateway::class)->strict();
$gateway->expects('generateEmbeddings')->times(2)->resolves(
fn (EmbeddingProvider $provider): EmbeddingsResponse => new EmbeddingsResponse(
[[$provider->providerCredentials()['key'] === 'first-key' ? 1 : 2]],
@@ -378,7 +378,7 @@ public function testDisabledCachingDoesNotResolveCacheScope(): void
protected function useCustomProvider(Closure $generate): void
{
Ai::extend('cache-test', function (Application $app, array $config) use ($generate): EmbeddingProvider {
- $provider = Double::for(EmbeddingProvider::class);
+ $provider = Double::for(EmbeddingProvider::class)->strict();
$provider->allows('name')->returns('cache-test');
$provider->allows('driver')->returns('cache-test');
$provider->allows('providerCredentials')->returns(['key' => $config['key']]);
diff --git a/tests/Ai/Feature/FilesystemToolsTest.php b/tests/Ai/Feature/FilesystemToolsTest.php
index 80cfe69ef2..5b287c7019 100644
--- a/tests/Ai/Feature/FilesystemToolsTest.php
+++ b/tests/Ai/Feature/FilesystemToolsTest.php
@@ -76,7 +76,7 @@ public function testFilesystemCancellationIsNotConvertedToAToolResult(string $to
if ($cleanupThrows) {
$cancellation = new RuntimeException('Filesystem cleanup failed.', previous: $cancellation);
}
- $disk = Double::for(FilesystemAdapter::class);
+ $disk = Double::for(FilesystemAdapter::class)->strict();
$disk->allows('fileExists')->returns(true);
foreach (['size' => 10, 'lastModified' => 1, 'mimeType' => 'text/plain', 'getVisibility' => 'public'] as $operation => $value) {
if ($operation !== $method) {
@@ -155,7 +155,7 @@ public function testLookupFailuresForExistingFilesAreReportedInsteadOfDescribedA
{
Exceptions::fake();
$failure = UnableToRetrieveMetadata::fileSize('file.txt', 'Access denied.');
- $disk = Double::for(FilesystemAdapter::class);
+ $disk = Double::for(FilesystemAdapter::class)->strict();
$disk->expects('size')->with('file.txt')->throws($failure);
$disk->expects('fileExists')->with('file.txt')->returns(true);
@@ -239,7 +239,7 @@ public function testReadFileRejectsABinaryFile(): void
public function testReadFileReportsAnUnreadableFile(): void
{
- $disk = Double::for(FilesystemAdapter::class);
+ $disk = Double::for(FilesystemAdapter::class)->strict();
$disk->expects('size')->with('note.txt')->returns(10);
$disk->expects('get')->with('note.txt')->returns(null);
@@ -360,7 +360,7 @@ public function testDeleteFileDoesNotReportDirectoriesAsFiles(): void
public function testDeleteFileReportsDeleteFailures(): void
{
- $disk = Double::for(Filesystem::class);
+ $disk = Double::for(Filesystem::class)->strict();
$disk->expects('fileExists')->with('gone.txt')->returns(true);
$disk->expects('delete')->with('gone.txt')->returns(false);
@@ -399,7 +399,7 @@ public function testCopyFileDoesNotCopyDirectories(): void
public function testCopyFileReportsCopyFailures(): void
{
- $disk = Double::for(Filesystem::class);
+ $disk = Double::for(Filesystem::class)->strict();
$disk->expects('fileExists')->with('a.txt')->returns(true);
$disk->expects('copy')->with('a.txt', 'b.txt')->returns(false);
@@ -439,7 +439,7 @@ public function testMoveFileDoesNotMoveDirectories(): void
public function testMoveFileReportsMoveFailures(): void
{
- $disk = Double::for(Filesystem::class);
+ $disk = Double::for(Filesystem::class)->strict();
$disk->expects('fileExists')->with('a.txt')->returns(true);
$disk->expects('move')->with('a.txt', 'b.txt')->returns(false);
diff --git a/tests/Ai/Feature/Gateway/Concerns/CreatesClientTest.php b/tests/Ai/Feature/Gateway/Concerns/CreatesClientTest.php
index 98a2de8fee..3f217653ba 100644
--- a/tests/Ai/Feature/Gateway/Concerns/CreatesClientTest.php
+++ b/tests/Ai/Feature/Gateway/Concerns/CreatesClientTest.php
@@ -55,7 +55,7 @@ public function testSelectsRegisteredConnectionsWithoutRetainingDynamicProviderN
config(['ai.providers.added-later' => ['driver' => 'openai', 'key' => 'test-key']]);
foreach (['configured', 'on-demand', 'added-later'] as $name) {
- $provider = Double::for(Provider::class);
+ $provider = Double::for(Provider::class)->strict();
$provider->allows('name')->returns($name);
$client = $this->httpClient(provider: $provider);
@@ -80,7 +80,7 @@ public function testProviderCredentialsAndOptionsRemainOnEachRequest(): void
$requests = [];
foreach (['first', 'second'] as $index => $key) {
- $provider = Double::for(BaseProvider::class);
+ $provider = Double::for(BaseProvider::class)->strict();
$provider->allows('name')->returns('configured');
$provider->allows('providerCredentials')->returns(['key' => $key]);
$provider->allows('additionalConfiguration')->returns(['headers' => ['X-Request' => $key]]);
diff --git a/tests/Ai/Feature/PendingProviderTest.php b/tests/Ai/Feature/PendingProviderTest.php
index b3f0ea69e0..07e5e84f26 100644
--- a/tests/Ai/Feature/PendingProviderTest.php
+++ b/tests/Ai/Feature/PendingProviderTest.php
@@ -62,12 +62,12 @@ protected function defineEnvironment(Application $app): void
#[DataProvider('generations')]
public function testContractProviderFailoverRetainsTheOriginalNamedFallback(string $kind, string $contract, string $method, string $responseClass): void
{
- $response = Double::for($responseClass);
+ $response = Double::for($responseClass)->strict();
$exception = RateLimitedException::forProvider('first');
$providers = [];
foreach (['first', 'second'] as $name) {
- $provider = $name === 'first' ? Double::for($contract) : Double::for(PendingTestProvider::class);
+ $provider = $name === 'first' ? Double::for($contract)->strict() : Double::for(PendingTestProvider::class)->strict();
$provider->allows('name')->returns($name);
$provider->expects('withHeaders')->with(['X-Provider' => $name]);
@@ -92,7 +92,7 @@ public function testContractProviderFailoverRetainsTheOriginalNamedFallback(stri
$providers[$name] = $provider;
}
- $replacement = Double::for(PendingTestProvider::class);
+ $replacement = Double::for(PendingTestProvider::class)->strict();
Ai::extend('custom', fn (Application $app, array $config): Provider => $config['key'] === 'replacement'
? $replacement
: $providers[$config['name']]);
@@ -123,8 +123,8 @@ public function testContractProviderFailoverRetainsTheOriginalNamedFallback(stri
#[DataProvider('generations')]
public function testConfiguredDefaultsAcceptEnumsAndProviderLists(string $kind, string $contract, string $method, string $responseClass): void
{
- $response = Double::for($responseClass);
- $provider = Double::for($contract);
+ $response = Double::for($responseClass)->strict();
+ $provider = Double::for($contract)->strict();
$provider->expects('withHeaders')->times(2)->with([]);
$provider->expects($method)->times(2)->returns($response);
diff --git a/tests/Ai/Feature/RememberConversationTest.php b/tests/Ai/Feature/RememberConversationTest.php
index 6ae0fd2334..685862fbdc 100644
--- a/tests/Ai/Feature/RememberConversationTest.php
+++ b/tests/Ai/Feature/RememberConversationTest.php
@@ -83,7 +83,7 @@ public function continue(string $conversationId, ?object $as = null): static
};
$agent->continue($conversationId);
$agent->continuations = 0;
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$provider->allows('name')->returns('test');
$prompt = new AgentPrompt($agent, 'Hello', [], $provider, 'model');
$middleware = Double::for(new RememberConversation($store, $provider))->passthru();
@@ -105,7 +105,7 @@ public function testDirectProviderCapturesAContractOnlyAgentsSelectionAndHistory
config(['ai.providers.openai.key' => 'test-key']);
$participant = $originalParticipant = (object) ['id' => 1];
$conversationId = null;
- $agent = Double::for(Agent::class, RemembersConversations::class);
+ $agent = Double::for(Agent::class, RemembersConversations::class)->strict();
$agent->allows('currentConversation')->resolves(function () use (&$conversationId): ?string {
return $conversationId;
});
@@ -327,7 +327,7 @@ 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(Double::for(StepTextGateway::class));
+ $loop = new TextGenerationLoop(Double::for(StepTextGateway::class)->strict());
$titleRequests = 0;
$middleware = Double::for(new RememberConversation(new DatabaseConversationStore, $prompt->provider()))->passthru();
$middleware->allows('generateTitle')->resolves(function () use (&$titleRequests): string {
@@ -357,7 +357,7 @@ public static function titleModes(): array
public function testASequentialStoreCanChooseItsOwnIdWhenContinuingAnEmptyId(): void
{
- $store = Double::for(ConversationStore::class);
+ $store = Double::for(ConversationStore::class)->strict();
$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');
@@ -576,7 +576,7 @@ public function testFailedTurnPersistencePreservesCancellation(bool $streaming):
$prompt = $this->prompt();
$cancellation = new CanceledException;
$storageFailure = new RuntimeException('Conversation storage failed.');
- $store = Double::for(DatabaseConversationStore::class);
+ $store = Double::for(DatabaseConversationStore::class)->strict();
$store->expects('storeTurn')->throws($storageFailure);
$middleware = new RememberConversation($store, $prompt->provider());
$generate = function () use ($prompt, $cancellation): never {
@@ -949,7 +949,7 @@ public function testStorageFailurePreservesTitleCancellation(): void
$storageFailure = new RuntimeException('Conversation storage failed.');
$prompt->provider()->expects('prompt')->throws($cancellation);
$prompt->provider()->expects('cheapestTextModel')->returns('title-model');
- $store = Double::for(DatabaseConversationStore::class);
+ $store = Double::for(DatabaseConversationStore::class)->strict();
$store->expects('storeTurn')->throws($storageFailure);
$caught = null;
@@ -970,7 +970,7 @@ public function testStorageFailurePreservesTitleCancellation(): void
*/
private function prompt(?Decisions $decisions = null): AgentPrompt
{
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$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 32510a000d..97703a3f62 100644
--- a/tests/Ai/Feature/Storage/DatabaseConversationStoreTest.php
+++ b/tests/Ai/Feature/Storage/DatabaseConversationStoreTest.php
@@ -418,7 +418,7 @@ public function testItStoresAResponseBuiltWithoutStepsAsASingleStepOfLists(): vo
new ToolUsingAgent,
'Check my order status.',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -479,7 +479,7 @@ public function testItRoundTripsToolResultFailureStatusThroughStorage(): void
new ToolUsingAgent,
'Where is Berlin?',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -509,7 +509,7 @@ public function testItStoresAToolResultIdOnTheCallThatMadeIt(): void
new ToolUsingAgent,
'Write the file',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -587,7 +587,7 @@ public function testABareRejectionResumeDoesNotPersistABlankAssistantRow(): void
new ToolUsingAgent,
'',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
approvalDecisions: Decisions::from(['call-1' => Decision::reject()]),
);
@@ -622,7 +622,7 @@ public function testAResumeFoldsItsStepsTextAndUsageIntoThePausedRow(bool $strea
new ToolUsingAgent,
'',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
approvalDecisions: Decisions::from(['call-1' => true]),
);
@@ -678,7 +678,7 @@ public function testAStreamedTurnThatPausesTwiceKeepsTheTextOfEveryStep(): void
new ToolUsingAgent,
'',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
approvalDecisions: Decisions::from([$callId => true]),
);
@@ -718,7 +718,7 @@ public function testAStreamedResumeKeepsAContinuedStepInOneParagraph(): void
new ToolUsingAgent,
'',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
approvalDecisions: Decisions::from(['call-1' => true]),
);
@@ -745,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, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]));
+ $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class)->strict(), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]));
$meta = new Meta('anthropic', 'claude-sonnet-4-6', collect([new UrlCitation('https://hypervel.org/docs/mcp')]));
@@ -771,7 +771,7 @@ public function testAFoldThatRecordedNoResultDoesNotLeaveTheRowReportingAPending
assistantStep([['id' => 'call-1', 'name' => 'DeleteFile', 'arguments' => []]]),
], ['call-1' => 'Deletes a file']);
- $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]));
+ $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class)->strict(), '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, '', []),
@@ -794,7 +794,7 @@ public function testAResumeDoesNotFoldIntoASettledRowOnceANewerPlainTurnFollowsI
new ToolUsingAgent,
'',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
approvalDecisions: Decisions::from(['call-1' => true]),
);
@@ -920,7 +920,7 @@ public function testCompletingATurnStoresNoReplayBlocksAndDropsThoseOfThePausedR
),
], [], ['provider' => 'anthropic']);
- $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]));
+ $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class)->strict(), '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.']]),
@@ -947,7 +947,7 @@ public function testATurnThatPausesAgainKeepsTheReplayBlocksOfTheRowsItResumed()
),
], [], ['provider' => 'anthropic']);
- $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]));
+ $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class)->strict(), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]));
$response = (new AgentResponse('invocation-id', '', new TextUsage, new Meta('anthropic')))
->withSteps(collect([
@@ -980,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, '', [], Double::for(TextProvider::class), 'test-model', approvalDecisions: Decisions::from(['call-1' => true]));
+ $prompt = new AgentPrompt(new ToolUsingAgent, '', [], Double::for(TextProvider::class)->strict(), '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, '', []),
@@ -1084,7 +1084,7 @@ public function testItWritesTheStepsOfAPausedTurnWithTheirReplayBlocksAndKeepsRe
new ToolUsingAgent,
'Delete config/app.php.',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -1127,7 +1127,7 @@ public function testItWritesTheStepsAPausedStreamCarriedOnItsApprovalRequest():
new ToolUsingAgent,
'Delete config/app.php.',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -1160,7 +1160,7 @@ public function testItWritesTheStepsACompletedStreamCarriedOnItsStreamEnd(): voi
new ToolUsingAgent,
'Read config/app.php.',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -1652,7 +1652,7 @@ public function testItRecordsNoReasoningOnTheTurnStepsWhenTheModelDidNotReason()
new ToolUsingAgent,
'How cold is it?',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -1676,7 +1676,7 @@ public function testItRecordsTheSourcesAStreamedTurnCitedIntoTheMessageMeta(): v
new ToolUsingAgent,
'What does Hypervel MCP do?',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -1706,7 +1706,7 @@ public function testItStoresNoSourcesWhenAStreamedTurnCitedNothing(): void
new ToolUsingAgent,
'How cold is it?',
[],
- Double::for(TextProvider::class),
+ Double::for(TextProvider::class)->strict(),
'test-model',
);
@@ -1771,7 +1771,7 @@ public function testProviderReasoningStateIsKeptOnTheStepReplayBlocksRatherThanC
{
$store = new DatabaseConversationStore;
$conversationId = $store->storeConversation('user', 1, 'Reasoning conversation');
- $prompt = new AgentPrompt(new ToolUsingAgent, 'Look it up', [], Double::for(TextProvider::class), 'test-model');
+ $prompt = new AgentPrompt(new ToolUsingAgent, 'Look it up', [], Double::for(TextProvider::class)->strict(), 'test-model');
$reasoningItem = ['type' => 'reasoning', 'id' => 'rs_1', 'summary' => [], 'encrypted_content' => 'enc-blob-1'];
@@ -1825,7 +1825,7 @@ public function testProviderToolCallsAreStoredPerStepAndExposedOnTheStoredMessag
{
$store = new DatabaseConversationStore;
$conversationId = $store->storeConversation('user', 1, 'Search conversation');
- $prompt = new AgentPrompt(new ToolUsingAgent, 'Search', [], Double::for(TextProvider::class), 'test-model');
+ $prompt = new AgentPrompt(new ToolUsingAgent, 'Search', [], Double::for(TextProvider::class)->strict(), '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)']);
@@ -2365,7 +2365,7 @@ private function claimedPrompt(DatabaseConversationStore $store, string $convers
*/
private function prompt(?Decisions $decisions = null): AgentPrompt
{
- return new AgentPrompt(new AnonymousAgent('', [], []), 'Hello', [], Double::for(TextProvider::class), 'model', approvalDecisions: $decisions);
+ return new AgentPrompt(new AnonymousAgent('', [], []), 'Hello', [], Double::for(TextProvider::class)->strict(), 'model', approvalDecisions: $decisions);
}
/**
diff --git a/tests/Ai/Feature/StoreFakeTest.php b/tests/Ai/Feature/StoreFakeTest.php
index 6d7044bc0e..78070172ed 100644
--- a/tests/Ai/Feature/StoreFakeTest.php
+++ b/tests/Ai/Feature/StoreFakeTest.php
@@ -338,7 +338,7 @@ public function testCanAssertFileNotRemovedFromStore(): void
public function testFileOperationsUseTheCapturedProvider(): void
{
- $provider = Double::for(FileProvider::class, StoreProvider::class);
+ $provider = Double::for(FileProvider::class, StoreProvider::class)->strict();
$provider->allows('name')->returns('unregistered');
$file = Document::fromString('Hello, world!', 'text/plain');
$stored = new StoredFileResponse('file_123');
diff --git a/tests/Ai/Feature/ToolRequestValidationTest.php b/tests/Ai/Feature/ToolRequestValidationTest.php
index 3096db4441..67abdb17c5 100644
--- a/tests/Ai/Feature/ToolRequestValidationTest.php
+++ b/tests/Ai/Feature/ToolRequestValidationTest.php
@@ -94,8 +94,8 @@ public function schema(JsonSchema $schema): array
$context = new RunContext(
'inv_1',
- Double::for(Agent::class),
- Double::for(TextProvider::class),
+ Double::for(Agent::class)->strict(),
+ Double::for(TextProvider::class)->strict(),
'stub-model',
$events,
);
diff --git a/tests/Ai/McpClientTransportTest.php b/tests/Ai/McpClientTransportTest.php
index 08e0923c0a..58dc04a107 100644
--- a/tests/Ai/McpClientTransportTest.php
+++ b/tests/Ai/McpClientTransportTest.php
@@ -90,7 +90,7 @@ public function testCancelingTheAiOperationClosesItsPendingMcpResponses(): void
*/
private function generate(Client $client, bool $completes = true): TextResponse
{
- $gateway = Double::for(StepTextGateway::class);
+ $gateway = Double::for(StepTextGateway::class)->strict();
$gateway->expects('generateTextStep')->times($completes ? 2 : 1)->returns(
new StepResponse('', [
new ToolCall('first-call', 'mcp_tools_first', []),
@@ -98,7 +98,7 @@ private function generate(Client $client, bool $completes = true): TextResponse
], FinishReason::ToolCalls, new TextUsage, new Meta),
new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta),
);
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$provider->allows('name')->returns('local-test');
$tools = array_map(static fn (string $name): McpTool => new McpTool(Tool::from($client, [
'name' => $name,
diff --git a/tests/Ai/PartitionStoreTest.php b/tests/Ai/PartitionStoreTest.php
index bd183e63b0..fe3cdd720f 100644
--- a/tests/Ai/PartitionStoreTest.php
+++ b/tests/Ai/PartitionStoreTest.php
@@ -148,7 +148,7 @@ public function testATurnCannotAppendToAnotherPartitionsConversation(): void
*/
private function prompt(?Decisions $decisions = null): AgentPrompt
{
- return new AgentPrompt(new AnonymousAgent('', [], []), 'Hello', [], Double::for(TextProvider::class), 'model', approvalDecisions: $decisions);
+ return new AgentPrompt(new AnonymousAgent('', [], []), 'Hello', [], Double::for(TextProvider::class)->strict(), 'model', approvalDecisions: $decisions);
}
/**
diff --git a/tests/Ai/Unit/Gateway/InvokesToolsTest.php b/tests/Ai/Unit/Gateway/InvokesToolsTest.php
index f9fc26c24a..d1e7442e2b 100644
--- a/tests/Ai/Unit/Gateway/InvokesToolsTest.php
+++ b/tests/Ai/Unit/Gateway/InvokesToolsTest.php
@@ -83,8 +83,8 @@ function stubRunContext(Dispatcher $events, string $invocationId = 'inv_1'): Run
{
return new RunContext(
$invocationId,
- Double::for(Agent::class),
- Double::for(TextProvider::class),
+ Double::for(Agent::class)->strict(),
+ Double::for(TextProvider::class)->strict(),
'stub-model',
$events,
);
diff --git a/tests/Ai/Unit/Gateway/RunContextTest.php b/tests/Ai/Unit/Gateway/RunContextTest.php
index 01ca40b5db..df873ba361 100644
--- a/tests/Ai/Unit/Gateway/RunContextTest.php
+++ b/tests/Ai/Unit/Gateway/RunContextTest.php
@@ -36,10 +36,10 @@ public function testStepAndToolEventsRequireInterestedListeners(): void
$events->listen('*', function (string $name) use (&$observed): void {
$observed[] = $name;
});
- $context = new RunContext('invocation', Double::for(Agent::class), Double::for(TextProvider::class), 'model', $events);
+ $context = new RunContext('invocation', Double::for(Agent::class)->strict(), Double::for(TextProvider::class)->strict(), 'model', $events);
$step = new StepContext;
$response = new StepResponse('Answer', [], FinishReason::Stop, new TextUsage, new Meta);
- $tool = Double::for(Tool::class);
+ $tool = Double::for(Tool::class)->strict();
$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 0778a799b2..cda347d9a7 100644
--- a/tests/Ai/Unit/Gateway/TextGenerationLoopTest.php
+++ b/tests/Ai/Unit/Gateway/TextGenerationLoopTest.php
@@ -1152,7 +1152,7 @@ public function testItDropsProviderToolsTheProviderDoesNotSupportBeforeCallingTh
$regular = new TextGenerationLoopCountingTool;
$webSearch = new WebSearch;
- $provider = Double::for(TextProvider::class, SupportsWebSearch::class);
+ $provider = Double::for(TextProvider::class, SupportsWebSearch::class)->strict();
$provider->allows('name')->returns('fake');
(new TextGenerationLoop($gateway))->generate(
@@ -1406,7 +1406,7 @@ public function testPreliminarySnapshotsStayBoundedWhenTextAndReasoningAlternate
public function testASubAgentRunsSynchronouslyThroughTheNonStreamingLoop(): void
{
- $agent = Double::for(Agent::class, CanActAsTool::class);
+ $agent = Double::for(Agent::class, CanActAsTool::class)->strict();
$agent->allows('name')->returns('research_agent');
$agent->expects('prompt')->returns(new AgentResponse(
'sub-invocation',
@@ -1441,7 +1441,7 @@ public function testAStructuredSubAgentAnswersThroughARegularPromptInTheStreamed
{
$parent = null;
- $agent = Double::for(Agent::class, CanActAsTool::class, HasStructuredOutput::class);
+ $agent = Double::for(Agent::class, CanActAsTool::class, HasStructuredOutput::class)->strict();
$agent->allows('name')->returns('research_agent');
$agent->expects('stream')->never();
$agent->expects('prompt')->resolves(function () use (&$parent): StructuredAgentResponse {
@@ -1468,7 +1468,7 @@ public function testAStructuredSubAgentAnswersThroughARegularPromptInTheStreamed
textGenerationLoopSubAgentStream([new AgentTool($agent)], [$toolCall], context: new RunContext(
'invocation-1',
- Double::for(Agent::class),
+ Double::for(Agent::class)->strict(),
textGenerationLoopProvider(),
'model',
$dispatcher,
@@ -1481,7 +1481,7 @@ public function testAStructuredSubAgentAnswersThroughARegularPromptInTheStreamed
public function testASubAgentIsNotExecutedOnTheFinalStreamedStep(): void
{
- $agent = Double::for(Agent::class, CanActAsTool::class);
+ $agent = Double::for(Agent::class, CanActAsTool::class)->strict();
$agent->allows('name')->returns('research_agent');
$agent->expects('prompt')->never();
$agent->expects('stream')->never();
@@ -1529,7 +1529,7 @@ public function testToolInvocationEventsFireAroundASubAgentInTheStreamedLoop():
$events = textGenerationLoopSubAgentStream([$tool], [$toolCall], context: new RunContext(
'invocation-1',
- Double::for(Agent::class),
+ Double::for(Agent::class)->strict(),
$provider,
'model',
$dispatcher,
@@ -1560,7 +1560,7 @@ public function testASubAgentNamesTheToolCallItWasDelegatedFromForTheWholeOfItsR
textGenerationLoopSubAgentStream([$tool], [$toolCall], context: new RunContext(
'invocation-1',
- Double::for(Agent::class),
+ Double::for(Agent::class)->strict(),
$provider,
'model',
new Dispatcher,
@@ -1593,7 +1593,7 @@ public function testAGatedToolPausesTheStreamedLoopWhileASubAgentStillReportsIts
public function testEachResultIsPersistedBeforeTheNextToolRuns(): void
{
$provider = textGenerationLoopProvider();
- $store = Double::for(ClaimsPendingApprovals::class);
+ $store = Double::for(ClaimsPendingApprovals::class)->strict();
$claim = new ApprovalClaim('message', 'token');
$recorded = [];
$operations = [];
@@ -1615,9 +1615,9 @@ public function testEachResultIsPersistedBeforeTheNextToolRuns(): void
return 'done';
});
- $gateway = Double::for(StepTextGateway::class);
+ $gateway = Double::for(StepTextGateway::class)->strict();
$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');
+ $context = (new RunContext('invocation', Double::for(Agent::class)->strict(), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation');
(new TextGenerationLoop($gateway))->generate(
$provider,
@@ -1643,14 +1643,14 @@ public function testEachResultIsPersistedBeforeTheNextToolRuns(): void
public function testAnUnavailableClaimPreventsToolExecution(): void
{
$provider = textGenerationLoopProvider();
- $gateway = Double::for(StepTextGateway::class);
+ $gateway = Double::for(StepTextGateway::class)->strict();
$gateway->allows('generateTextStep')->returns(new StepResponse('Finished', [], FinishReason::Stop, new TextUsage, new Meta));
- $store = Double::for(ClaimsPendingApprovals::class);
+ $store = Double::for(ClaimsPendingApprovals::class)->strict();
$store->expects('claimPendingApprovals')->with('conversation', ['call'])->returns(null);
$store->expects('recordApprovalResult')->never();
$tool = $this->approvalTool();
$tool->expects('handle')->never();
- $context = (new RunContext('invocation', Double::for(Agent::class), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation');
+ $context = (new RunContext('invocation', Double::for(Agent::class)->strict(), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation');
$this->expectException(ApprovalMismatchException::class);
@@ -1670,9 +1670,9 @@ public function testAnUnavailableClaimPreventsToolExecution(): void
public function testCancellationIsNotRecordedAsACompletedToolFailure(bool $cleanupThrows): void
{
$provider = textGenerationLoopProvider();
- $gateway = Double::for(StepTextGateway::class);
+ $gateway = Double::for(StepTextGateway::class)->strict();
$gateway->expects('generateTextStep')->never();
- $store = Double::for(ClaimsPendingApprovals::class);
+ $store = Double::for(ClaimsPendingApprovals::class)->strict();
$claim = new ApprovalClaim('message', 'token');
$store->expects('claimPendingApprovals')->with('conversation', ['call', 'next'])->returns($claim);
$store->expects('recordApprovalResult')->never();
@@ -1682,7 +1682,7 @@ public function testCancellationIsNotRecordedAsACompletedToolFailure(bool $clean
}
$tool = $this->approvalTool();
$tool->expects('handle')->throws($exception);
- $context = (new RunContext('invocation', Double::for(Agent::class), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation');
+ $context = (new RunContext('invocation', Double::for(Agent::class)->strict(), $provider, 'model', new Dispatcher))->withApprovalStore($store, 'conversation');
try {
(new TextGenerationLoop($gateway))->generate(
@@ -1707,7 +1707,7 @@ public function testCancellationIsNotRecordedAsACompletedToolFailure(bool $clean
*/
private function approvalTool(): Tool&Approvable&DoubleInterface
{
- $tool = Double::for(ApprovableNamedTool::class);
+ $tool = Double::for(ApprovableNamedTool::class)->strict();
$tool->allows('name')->returns('tool');
$tool->allows('shouldRequestApproval')->returns(Approval::required());
@@ -1720,7 +1720,7 @@ private function approvalTool(): Tool&Approvable&DoubleInterface
*/
function textGenerationLoopProvider(): TextProvider
{
- $provider = Double::for(TextProvider::class);
+ $provider = Double::for(TextProvider::class)->strict();
$provider->allows('name')->returns('fake');
return $provider;
@@ -1731,7 +1731,7 @@ function textGenerationLoopProvider(): TextProvider
*/
function textGenerationLoopToolSearchProvider(): TextProvider
{
- $provider = Double::for(TextProvider::class, SupportsToolSearch::class);
+ $provider = Double::for(TextProvider::class, SupportsToolSearch::class)->strict();
$provider->allows('name')->returns('fake');
return $provider;
@@ -1932,7 +1932,7 @@ protected function approvalAwareToolResults(array $toolCalls, array $tools, bool
*/
function textGenerationLoopAgentTool(Closure|string $text = 'sub-agent result'): AgentTool
{
- $agent = Double::for(Agent::class, CanActAsTool::class);
+ $agent = Double::for(Agent::class, CanActAsTool::class)->strict();
$agent->allows('name')->returns('research_agent');
$agent->expects('prompt')->never();
$agent->expects('stream')->times(minimum: 1)->resolves(fn (): StreamableAgentResponse => new StreamableAgentResponse(
diff --git a/tests/Ai/Unit/Tools/AgentToolTest.php b/tests/Ai/Unit/Tools/AgentToolTest.php
index ccebbbd4ec..b60248323e 100644
--- a/tests/Ai/Unit/Tools/AgentToolTest.php
+++ b/tests/Ai/Unit/Tools/AgentToolTest.php
@@ -36,7 +36,7 @@ public function testAnAgentToolStreamsItsEventsByDefaultAndReturnsItsFinalText()
new StreamEnd('event-2', 'stop', new TextUsage, time()),
], new Meta('fake', 'model'));
- $agent = Double::for(Agent::class);
+ $agent = Double::for(Agent::class)->strict();
$agent->expects('stream')->with('Do the thing')->returns($stream);
$agent->expects('prompt')->never();
@@ -51,7 +51,7 @@ public function testAnAgentToolStreamsItsEventsByDefaultAndReturnsItsFinalText()
public function testAStructuredSubAgentAnswersThroughARegularPromptOnTheStreamingPath(): void
{
- $agent = Double::for(Agent::class, HasStructuredOutput::class);
+ $agent = Double::for(Agent::class, HasStructuredOutput::class)->strict();
$agent->expects('stream')->never();
$agent->expects('prompt')->returns(new StructuredAgentResponse(
'invocation-sub',
@@ -73,7 +73,7 @@ public function testAFailingSubAgentSurfacesItsErrorAsTheToolResultOnTheStreamin
Exceptions::fake();
$exception = new RuntimeException('provider exploded');
- $agent = Double::for(Agent::class);
+ $agent = Double::for(Agent::class)->strict();
$agent->expects('stream')->throws($exception);
$generator = (new AgentTool($agent))->stream(new Request(['task' => 'Do the thing']));
@@ -92,7 +92,7 @@ public function testAFailingPromptedSubAgentIsReportedOnceAndHidesItsErrorOutsid
Exceptions::fake();
$exception = new RuntimeException('provider exploded');
- $agent = $structuredStream ? Double::for(Agent::class, HasStructuredOutput::class) : Double::for(Agent::class);
+ $agent = $structuredStream ? Double::for(Agent::class, HasStructuredOutput::class)->strict() : Double::for(Agent::class)->strict();
$agent->expects('stream')->never();
$agent->expects('prompt')->throws($exception);
@@ -130,7 +130,7 @@ public function testCancellationEscapesTheSubAgent(bool $streaming, bool $cleanu
if ($cleanupThrows) {
$exception = new RuntimeException('Sub-agent cleanup failed.', previous: $exception);
}
- $agent = Double::for(Agent::class);
+ $agent = Double::for(Agent::class)->strict();
if ($streaming) {
$agent->expects('stream')->returns(new StreamableAgentResponse('invocation', function () use ($exception): Generator {
diff --git a/tests/ApiClient/ApiRequestTest.php b/tests/ApiClient/ApiRequestTest.php
index d4b86fd2dd..65c84dcccd 100644
--- a/tests/ApiClient/ApiRequestTest.php
+++ b/tests/ApiClient/ApiRequestTest.php
@@ -362,7 +362,7 @@ public function testWithUserAgent(): void
public function testCreateFromPreservesDataAndAttributes(): void
{
- $body = Double::for(StreamInterface::class);
+ $body = Double::for(StreamInterface::class)->strict();
$body->expects('__toString')->returns('[]');
$request = (new HttpRequest(new Psr7Request(
'POST',
diff --git a/tests/ApiClient/ApiResourceTest.php b/tests/ApiClient/ApiResourceTest.php
index 93d50d2f91..100b572d1d 100644
--- a/tests/ApiClient/ApiResourceTest.php
+++ b/tests/ApiClient/ApiResourceTest.php
@@ -30,8 +30,8 @@ protected function setUp(): void
{
parent::setUp();
- $this->response = Double::for(ApiResponse::class);
- $this->request = Double::for(ApiRequest::class);
+ $this->response = Double::for(ApiResponse::class)->strict();
+ $this->request = Double::for(ApiRequest::class)->strict();
$this->resource = new ApiResource($this->response, $this->request);
}
diff --git a/tests/Auth/AuthAccessGateTest.php b/tests/Auth/AuthAccessGateTest.php
index e62a4e7dc3..9d432a9f1c 100644
--- a/tests/Auth/AuthAccessGateTest.php
+++ b/tests/Auth/AuthAccessGateTest.php
@@ -1580,7 +1580,7 @@ public function testCanSetDenialResponse(): void
public function testGateEvaluationSkipsDispatchWhenThereAreNoListeners(): void
{
$container = new Container;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(GateEvaluated::class)->returns(false);
$events->expects('dispatch')->never();
$container->instance(Dispatcher::class, $events);
@@ -1594,7 +1594,7 @@ public function testGateEvaluationSkipsDispatchWhenThereAreNoListeners(): void
public function testGateEvaluationDispatchesWhenThereIsAListener(): void
{
$container = new Container;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(GateEvaluated::class)->returns(true);
$events->expects('dispatch')
->with(Argument::satisfies(fn (GateEvaluated $event): bool => $event->ability === 'allowed'));
diff --git a/tests/Auth/AuthDatabaseTokenRepositoryTest.php b/tests/Auth/AuthDatabaseTokenRepositoryTest.php
index def26ff07f..b8695ec850 100755
--- a/tests/Auth/AuthDatabaseTokenRepositoryTest.php
+++ b/tests/Auth/AuthDatabaseTokenRepositoryTest.php
@@ -131,24 +131,24 @@ public function testDeleteExpiredMethodDeletesExpiredTokens(): void
public function testResolverBackedRepositoryResolvesTheConfiguredConnectionForEveryOperation(): void
{
- $firstConnection = Double::for(Connection::class);
- $firstQuery = Double::for(Builder::class);
+ $firstConnection = Double::for(Connection::class)->strict();
+ $firstQuery = Double::for(Builder::class)->strict();
$firstConnection->expects('table')->with('table')->returns($firstQuery);
$firstQuery->expects('where')->with('created_at', '<', Argument::any());
$firstQuery->expects('delete');
- $secondConnection = Double::for(Connection::class);
- $secondQuery = Double::for(Builder::class);
+ $secondConnection = Double::for(Connection::class)->strict();
+ $secondQuery = Double::for(Builder::class)->strict();
$secondConnection->expects('table')->with('table')->returns($secondQuery);
$secondQuery->expects('where')->with('created_at', '<', Argument::any());
$secondQuery->expects('delete');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->times(2)->with('passwords')->returns($firstConnection, $secondConnection);
$repository = new DatabaseTokenRepository(
$resolver,
- Double::for(Hasher::class),
+ Double::for(Hasher::class)->strict(),
'table',
'key',
connectionName: 'passwords'
@@ -160,24 +160,24 @@ public function testResolverBackedRepositoryResolvesTheConfiguredConnectionForEv
public function testResolverBackedRepositoryUsesTheDefaultConnectionWhenNoNameIsConfigured(): void
{
- $connection = Double::for(Connection::class);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $connection = Double::for(Connection::class)->strict();
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with(null)->returns($connection);
- $repository = new DatabaseTokenRepository($resolver, Double::for(Hasher::class), 'table', 'key');
+ $repository = new DatabaseTokenRepository($resolver, Double::for(Hasher::class)->strict(), 'table', 'key');
$this->assertSame($connection, $repository->getConnection());
}
public function testResolverContractTakesPrecedenceForObjectsImplementingBothConnectionContracts(): void
{
- $resolvedConnection = Double::for(Connection::class);
- $connectionResolver = Double::for(ConnectionInterface::class, ConnectionResolverInterface::class);
+ $resolvedConnection = Double::for(Connection::class)->strict();
+ $connectionResolver = Double::for(ConnectionInterface::class, ConnectionResolverInterface::class)->strict();
$connectionResolver->expects('connection')->with('passwords')->returns($resolvedConnection);
$repository = new DatabaseTokenRepository(
$connectionResolver,
- Double::for(Hasher::class),
+ Double::for(Hasher::class)->strict(),
'table',
'key',
connectionName: 'passwords'
diff --git a/tests/Auth/AuthDatabaseUserProviderTest.php b/tests/Auth/AuthDatabaseUserProviderTest.php
index 464e0e1d73..885d8dd05f 100755
--- a/tests/Auth/AuthDatabaseUserProviderTest.php
+++ b/tests/Auth/AuthDatabaseUserProviderTest.php
@@ -46,20 +46,20 @@ public function testRetrieveByIDReturnsNullWhenUserIsNotFound(): void
public function testResolverBackedProviderResolvesTheConfiguredConnectionForEveryOperation(): void
{
- $firstConnection = Double::for(Connection::class);
- $firstQuery = Double::for(Builder::class);
+ $firstConnection = Double::for(Connection::class)->strict();
+ $firstQuery = Double::for(Builder::class)->strict();
$firstConnection->expects('table')->with('foo')->returns($firstQuery);
$firstQuery->expects('find')->with(1)->returns(['id' => 1, 'name' => 'First']);
- $secondConnection = Double::for(Connection::class);
- $secondQuery = Double::for(Builder::class);
+ $secondConnection = Double::for(Connection::class)->strict();
+ $secondQuery = Double::for(Builder::class)->strict();
$secondConnection->expects('table')->with('foo')->returns($secondQuery);
$secondQuery->expects('find')->with(2)->returns(['id' => 2, 'name' => 'Second']);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->times(2)->with('auth')->returns($firstConnection, $secondConnection);
- $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class), 'foo', 'auth');
+ $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class)->strict(), 'foo', 'auth');
$this->assertSame('First', $provider->retrieveById(1)?->name);
$this->assertSame('Second', $provider->retrieveById(2)?->name);
@@ -67,19 +67,19 @@ public function testResolverBackedProviderResolvesTheConfiguredConnectionForEver
public function testResolverBackedProviderDoesNotRetainConnectionsAcrossExecutions(): void
{
- $firstConnection = Double::for(Connection::class);
- $firstQuery = Double::for(Builder::class);
+ $firstConnection = Double::for(Connection::class)->strict();
+ $firstQuery = Double::for(Builder::class)->strict();
$firstConnection->expects('table')->with('foo')->returns($firstQuery);
$firstQuery->expects('find')->returns(['id' => 1, 'name' => 'First']);
- $secondConnection = Double::for(Connection::class);
- $secondQuery = Double::for(Builder::class);
+ $secondConnection = Double::for(Connection::class)->strict();
+ $secondQuery = Double::for(Builder::class)->strict();
$secondConnection->expects('table')->with('foo')->returns($secondQuery);
$secondQuery->expects('find')->returns(['id' => 2, 'name' => 'Second']);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->times(2)->with('auth')->returns($firstConnection, $secondConnection);
- $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class), 'foo', 'auth');
+ $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class)->strict(), 'foo', 'auth');
$names = parallel([
fn () => $provider->retrieveById(1)?->name,
@@ -92,31 +92,31 @@ public function testResolverBackedProviderDoesNotRetainConnectionsAcrossExecutio
public function testResolverBackedProviderUsesTheDefaultConnectionWhenNoNameIsConfigured(): void
{
- $connection = Double::for(Connection::class);
- $query = Double::for(Builder::class);
+ $connection = Double::for(Connection::class)->strict();
+ $query = Double::for(Builder::class)->strict();
$connection->expects('table')->with('foo')->returns($query);
$query->expects('find')->with(1)->returns(null);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with(null)->returns($connection);
- $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class), 'foo');
+ $provider = new DatabaseUserProvider($resolver, Double::for(Hasher::class)->strict(), 'foo');
$this->assertNull($provider->retrieveById(1));
}
public function testResolverContractTakesPrecedenceForObjectsImplementingBothConnectionContracts(): void
{
- $resolvedConnection = Double::for(Connection::class);
- $query = Double::for(Builder::class);
+ $resolvedConnection = Double::for(Connection::class)->strict();
+ $query = Double::for(Builder::class)->strict();
$resolvedConnection->expects('table')->with('foo')->returns($query);
$query->expects('find')->with(1)->returns(null);
- $connectionResolver = Double::for(ConnectionInterface::class, ConnectionResolverInterface::class);
+ $connectionResolver = Double::for(ConnectionInterface::class, ConnectionResolverInterface::class)->strict();
$connectionResolver->expects('connection')->with('auth')->returns($resolvedConnection);
$connectionResolver->expects('table')->never();
- $provider = new DatabaseUserProvider($connectionResolver, Double::for(Hasher::class), 'foo', 'auth');
+ $provider = new DatabaseUserProvider($connectionResolver, Double::for(Hasher::class)->strict(), 'foo', 'auth');
$this->assertNull($provider->retrieveById(1));
}
@@ -216,10 +216,10 @@ public function testCredentialValidationFails(): void
public function testCredentialValidationFailsGracefullyWithNullPassword(): void
{
$conn = new PdoConnection(new PDO('sqlite::memory:'));
- $hasher = Double::for(Hasher::class);
+ $hasher = Double::for(Hasher::class)->strict();
$hasher->expects('check')->never();
$provider = new DatabaseUserProvider($conn, $hasher, 'foo');
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthPassword')->returns(null);
$result = $provider->validateCredentials($user, ['password' => 'plain']);
diff --git a/tests/Auth/AuthEloquentUserProviderCacheTest.php b/tests/Auth/AuthEloquentUserProviderCacheTest.php
index 30f4798057..99cefb5a85 100644
--- a/tests/Auth/AuthEloquentUserProviderCacheTest.php
+++ b/tests/Auth/AuthEloquentUserProviderCacheTest.php
@@ -59,9 +59,10 @@ protected function setUp(): void
parent::setUp();
$container = Container::setInstance(new Container);
- $this->cacheManager = Double::for(CacheManager::class);
+ $this->cacheManager = Double::for(CacheManager::class)->strict();
+ // Cache tests ignore store validation unless they explicitly check it.
$this->storeValidator = Double::for(ModelCacheStoreValidator::class);
- $this->cacheCoordinator = Double::for(ModelCacheCoordinator::class);
+ $this->cacheCoordinator = Double::for(ModelCacheCoordinator::class)->strict();
$container->instance('cache', $this->cacheManager);
$container->instance(ModelCacheStoreValidator::class, $this->storeValidator);
$container->instance(ModelCacheCoordinator::class, $this->cacheCoordinator);
@@ -75,7 +76,7 @@ public function testRetrieveByIdWithoutCacheDoesNotTouchCache(): void
{
$this->cacheManager->expects('store')->never();
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider = $this->providerExpectingDbFetch($user, 42, useWritePdo: false);
$this->assertSame($user, $provider->retrieveById(42));
@@ -88,7 +89,7 @@ public function testRetrieveByIdWithoutCacheDoesNotTouchCache(): void
public function testRetrieveByIdCachesMissedLookup(): void
{
$repo = $this->stubCache(RedisStore::class);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$key = $this->buildDefaultKey(42);
$this->expectCoordinatorFill($repo, $key, $user, readSource: true, expectedWriter: $repo);
@@ -102,7 +103,7 @@ public function testRetrieveByIdCachesMissedLookup(): void
public function testRetrieveByIdReturnsCachedUser(): void
{
$repo = $this->stubCache(RedisStore::class);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$this->expectCoordinatorFill($repo, $this->buildDefaultKey(42), $user);
@@ -142,9 +143,9 @@ public function testRetrieveByCredentialsIsNeverCached(): void
$repo = $this->stubCache(RedisStore::class);
$this->cacheCoordinator->expects('fill')->never();
- $expectedUser = Double::for(Authenticatable::class);
- $model = Double::for(User::class);
- $builder = Double::for(Builder::class);
+ $expectedUser = Double::for(Authenticatable::class)->strict();
+ $model = Double::for(User::class)->strict();
+ $builder = Double::for(Builder::class)->strict();
$model->expects('newQuery')->returns($builder);
$builder->expects('where')->with('username', 'u');
$builder->expects('first')->returns($expectedUser);
@@ -161,10 +162,10 @@ public function testRetrieveByTokenIsNeverCached(): void
$repo = $this->stubCache(RedisStore::class);
$this->cacheCoordinator->expects('fill')->never();
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getRememberToken')->returns('tok');
- $model = Double::for(User::class);
- $builder = Double::for(Builder::class);
+ $model = Double::for(User::class)->strict();
+ $builder = Double::for(Builder::class)->strict();
$model->expects('newQuery')->returns($builder);
$model->expects('getAuthIdentifierName')->returns('id');
$builder->expects('where')->with('id', 1)->returns($builder);
@@ -186,7 +187,7 @@ public function testDefaultCacheKeyIncludesFqcnAndIdentifier(): void
$repo = $this->stubCache(RedisStore::class);
$expectedKey = self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':42';
- $this->expectCoordinatorFill($repo, $expectedKey, Double::for(Authenticatable::class));
+ $this->expectCoordinatorFill($repo, $expectedKey, Double::for(Authenticatable::class)->strict());
$provider = $this->providerWithoutDbFetch();
$provider->enableCache(null);
@@ -199,17 +200,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 = 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));
+ $repo1 = Double::for(CacheRepository::class)->strict();
+ $repo1->allows('getStore')->returns(Double::for(RedisStore::class)->strict());
+ $repo2 = Double::for(CacheRepository::class)->strict();
+ $repo2->allows('getStore')->returns(Double::for(RedisStore::class)->strict());
$this->cacheManager->allows('store')->with(null)
->returns($repo1, $repo2);
$expectedKey = self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':42';
- $this->expectCoordinatorFill($repo1, $expectedKey, Double::for(Authenticatable::class));
- $this->expectCoordinatorFill($repo2, $expectedKey, Double::for(Authenticatable::class));
+ $this->expectCoordinatorFill($repo1, $expectedKey, Double::for(Authenticatable::class)->strict());
+ $this->expectCoordinatorFill($repo2, $expectedKey, Double::for(Authenticatable::class)->strict());
$providerNull = $this->providerWithoutDbFetch();
$providerNull->enableCache(null, 300, null);
@@ -226,7 +227,7 @@ public function testCustomCacheKeyResolverIsUsed(): void
$repo = $this->stubCache(RedisStore::class);
$expectedKey = self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':tenant5:42';
- $this->expectCoordinatorFill($repo, $expectedKey, Double::for(Authenticatable::class));
+ $this->expectCoordinatorFill($repo, $expectedKey, Double::for(Authenticatable::class)->strict());
$provider = $this->providerWithoutDbFetch();
$provider->enableCache(null);
@@ -248,7 +249,7 @@ public function testCustomCacheKeyResolverReceivesLookupContext(): void
});
$repo = $this->stubCache(RedisStore::class);
- $this->expectCoordinatorFill($repo, $this->buildDefaultKey(42), Double::for(Authenticatable::class));
+ $this->expectCoordinatorFill($repo, $this->buildDefaultKey(42), Double::for(Authenticatable::class)->strict());
$provider = $this->providerWithoutDbFetch();
$provider->enableCache(null);
@@ -263,18 +264,17 @@ public function testCacheKeyAlwaysIncludesFqcnEvenWithCustomResolver(): void
EloquentUserProvider::resolveUserCacheKeyUsing(fn (mixed $id): string => "wrapper:{$id}");
$repo = $this->stubCache(RedisStore::class);
+ $user = Double::for(Authenticatable::class)->strict();
$this->expectCoordinatorFill(
$repo,
self::DEFAULT_KEY_PREFIX . ':' . self::MODEL . ':wrapper:42',
- Double::for(Authenticatable::class),
+ $user,
);
$provider = $this->providerWithoutDbFetch();
$provider->enableCache(null);
- $provider->retrieveById(42);
-
- $this->addToAssertionCount(1);
+ $this->assertSame($user, $provider->retrieveById(42));
}
public function testChangingTheModelUsesTheNewModelCacheKeyspace(): void
@@ -283,7 +283,7 @@ public function testChangingTheModelUsesTheNewModelCacheKeyspace(): void
$this->expectCoordinatorFill(
$repo,
self::DEFAULT_KEY_PREFIX . ':' . EloquentCacheProviderAlternateUserStub::class . ':42',
- Double::for(Authenticatable::class),
+ Double::for(Authenticatable::class)->strict(),
);
$provider = $this->providerWithoutDbFetch();
@@ -420,7 +420,7 @@ public function testEnableCacheLeavesProviderInDisabledStateWhenValidationFails(
->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']')
->throws(new InvalidArgumentException('does not support cache store'));
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider = $this->providerExpectingDbFetch($user, 42, useWritePdo: false);
try {
@@ -445,8 +445,8 @@ public function testEnableCacheLeavesProviderInDisabledStateWhenValidationFails(
public function testModelStoreValidationRunsBeforeAuthTagValidation(): void
{
$sequence = [];
- $store = Double::for(RedisStore::class);
- $repo = Double::for(CacheRepository::class);
+ $store = Double::for(RedisStore::class)->strict();
+ $repo = Double::for(CacheRepository::class)->strict();
$repo->allows('getStore')->returns($store);
$this->cacheManager->expects('store')->with(null)->returns($repo);
$this->storeValidator->expects('validate')
@@ -617,8 +617,8 @@ public static function nonTaggableWhitelistedStoreProvider(): iterable
public function testRetrieveByIdMissUsesTaggedRepoForPutWhenTagsConfigured(): void
{
$plainRepo = $this->stubCache(RedisStore::class);
- $taggedRepo = Double::for(TaggedCache::class);
- $user = Double::for(Authenticatable::class);
+ $taggedRepo = Double::for(TaggedCache::class)->strict();
+ $user = Double::for(Authenticatable::class)->strict();
$key = $this->buildDefaultKey(42);
$plainRepo->expects('tags')->with(['auth_users'])->returns($taggedRepo);
@@ -633,7 +633,7 @@ public function testRetrieveByIdMissUsesTaggedRepoForPutWhenTagsConfigured(): vo
public function testRetrieveByIdUsesTaggedRepoWhenTagsConfigured(): void
{
$plainRepo = $this->stubCache(RedisStore::class);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$plainRepo->expects('tags')->never();
$this->expectCoordinatorFill($plainRepo, $this->buildDefaultKey(42), $user);
@@ -663,8 +663,8 @@ public function testEffectiveTagsCombineStaticAndDynamic(): void
EloquentUserProvider::resolveUserCacheTagsUsing(fn (): array => ['scope:a']);
$plainRepo = $this->stubCache(RedisStore::class);
- $taggedRepo = Double::for(TaggedCache::class);
- $user = Double::for(Authenticatable::class);
+ $taggedRepo = Double::for(TaggedCache::class)->strict();
+ $user = Double::for(Authenticatable::class)->strict();
$key = $this->buildDefaultKey(42);
$plainRepo->expects('tags')->with(['auth_users', 'scope:a'])->returns($taggedRepo);
@@ -679,8 +679,8 @@ public function testEffectiveTagsCombineStaticAndDynamic(): void
public function testEffectiveTagsAreJustStaticWhenNoResolver(): void
{
$plainRepo = $this->stubCache(RedisStore::class);
- $taggedRepo = Double::for(TaggedCache::class);
- $user = Double::for(Authenticatable::class);
+ $taggedRepo = Double::for(TaggedCache::class)->strict();
+ $user = Double::for(Authenticatable::class)->strict();
$key = $this->buildDefaultKey(42);
$plainRepo->expects('tags')->with(['auth_users'])->returns($taggedRepo);
@@ -702,10 +702,10 @@ public function testDynamicResolverIsInvokedFreshlyOnEachPut(): void
});
$plainRepo = $this->stubCache(RedisStore::class);
- $taggedRepo1 = Double::for(TaggedCache::class);
- $taggedRepo2 = Double::for(TaggedCache::class);
- $user1 = Double::for(Authenticatable::class);
- $user2 = Double::for(Authenticatable::class);
+ $taggedRepo1 = Double::for(TaggedCache::class)->strict();
+ $taggedRepo2 = Double::for(TaggedCache::class)->strict();
+ $user1 = Double::for(Authenticatable::class)->strict();
+ $user2 = Double::for(Authenticatable::class)->strict();
$key1 = $this->buildDefaultKey(42);
$key2 = $this->buildDefaultKey(43);
@@ -715,8 +715,8 @@ public function testDynamicResolverIsInvokedFreshlyOnEachPut(): void
$this->expectCoordinatorFill($plainRepo, $key2, $user2, readSource: true, expectedWriter: $taggedRepo2);
// Set up two DB fetches with distinct models/IDs.
- $model1 = Double::for(User::class);
- $query1 = Double::for(QueryBuilder::class);
+ $model1 = Double::for(User::class)->strict();
+ $query1 = Double::for(QueryBuilder::class)->strict();
$builder1 = Double::for(new Builder($query1))->passthru();
$model1->expects('newQuery')->returns($builder1);
$model1->expects('getAuthIdentifierName')->returns('id');
@@ -724,8 +724,8 @@ public function testDynamicResolverIsInvokedFreshlyOnEachPut(): void
$builder1->expects('where')->with('id', 42)->returns($builder1);
$builder1->expects('first')->returns($user1);
- $model2 = Double::for(User::class);
- $query2 = Double::for(QueryBuilder::class);
+ $model2 = Double::for(User::class)->strict();
+ $query2 = Double::for(QueryBuilder::class)->strict();
$builder2 = Double::for(new Builder($query2))->passthru();
$model2->expects('newQuery')->returns($builder2);
$model2->expects('getAuthIdentifierName')->returns('id');
@@ -753,7 +753,7 @@ public function testDynamicResolverIgnoredWhenNoStaticTagsConfigured(): void
});
$plainRepo = $this->stubCache(RedisStore::class);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$key = $this->buildDefaultKey(42);
$this->expectCoordinatorFill($plainRepo, $key, $user, readSource: true, expectedWriter: $plainRepo);
@@ -786,7 +786,7 @@ public function testEnableCacheLeavesProviderInDisabledStateWhenTagValidationFai
->with(Argument::same($repo), 'Auth user cache for model [' . self::MODEL . ']')
->throws(new InvalidArgumentException('TagMode::Any is required.'));
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider = $this->providerExpectingDbFetch($user, 42, useWritePdo: false);
try {
@@ -813,12 +813,12 @@ 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 = Double::for(RedisStore::class);
- $repo1 = Double::for(CacheRepository::class);
+ $store1 = Double::for(RedisStore::class)->strict();
+ $repo1 = Double::for(CacheRepository::class)->strict();
$repo1->allows('getStore')->returns($store1);
- $store2 = Double::for(RedisStore::class);
- $repo2 = Double::for(CacheRepository::class);
+ $store2 = Double::for(RedisStore::class)->strict();
+ $repo2 = Double::for(CacheRepository::class)->strict();
$repo2->allows('getStore')->returns($store2);
$this->cacheManager->allows('store')->with(null)->returns($repo1, $repo2);
@@ -842,7 +842,7 @@ public function testRecallingEnableCacheWithoutTagsClearsPreviousTagState(): voi
protected function providerMock(): EloquentUserProvider&MockObject
{
- $hasher = Double::for(Hasher::class);
+ $hasher = Double::for(Hasher::class)->strict();
return $this->getMockBuilder(EloquentUserProvider::class)
->onlyMethods(['createModel'])
@@ -859,8 +859,8 @@ protected function providerExpectingDbFetch(
mixed $id,
bool $useWritePdo = true,
): EloquentUserProvider&MockObject {
- $model = Double::for(User::class);
- $query = Double::for(QueryBuilder::class);
+ $model = Double::for(User::class)->strict();
+ $query = Double::for(QueryBuilder::class)->strict();
$builder = Double::for(new Builder($query))->passthru();
$model->expects('newQuery')->returns($builder);
$model->expects('getAuthIdentifierName')->returns('id');
@@ -883,12 +883,12 @@ protected function providerExpectingDbFetch(
*/
protected function providerForCacheClear(): EloquentUserProvider&MockObject
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('afterCommitOrNow')
->with(Argument::type(Closure::class))
->resolves(static fn (Closure $callback): mixed => $callback());
- $model = Double::for(User::class);
+ $model = Double::for(User::class)->strict();
$model->expects('getConnection')->returns($connection);
$provider = $this->providerMock();
@@ -952,9 +952,9 @@ protected function providerWithoutDbFetch(): EloquentUserProvider&MockObject
*/
protected function stubCache(string $storeClass, ?string $name = null): Repository&DoubleInterface
{
- $store = Double::for($storeClass);
+ $store = Double::for($storeClass)->strict();
- $repo = Double::for(Repository::class);
+ $repo = Double::for(Repository::class)->strict();
$repo->allows('getStore')->returns($store);
$this->cacheManager->allows('store')->with($name)->returns($repo);
diff --git a/tests/Auth/AuthEloquentUserProviderTest.php b/tests/Auth/AuthEloquentUserProviderTest.php
index b693bad390..ec0732ff2f 100755
--- a/tests/Auth/AuthEloquentUserProviderTest.php
+++ b/tests/Auth/AuthEloquentUserProviderTest.php
@@ -63,7 +63,7 @@ public function testRetrieveByBadTokenReturnsNull(): void
public function testUpdateRememberTokenRestoresTimestampsAfterSaving(): void
{
$user = new EloquentProviderRememberUserStub;
- $provider = new EloquentUserProvider(Double::for(Hasher::class), $user::class);
+ $provider = new EloquentUserProvider(Double::for(Hasher::class)->strict(), $user::class);
$provider->updateRememberToken($user, 'remember-token');
@@ -76,7 +76,7 @@ public function testUpdateRememberTokenPreservesInitiallyDisabledTimestamps(): v
{
$user = new EloquentProviderRememberUserStub;
$user->timestamps = false;
- $provider = new EloquentUserProvider(Double::for(Hasher::class), $user::class);
+ $provider = new EloquentUserProvider(Double::for(Hasher::class)->strict(), $user::class);
$provider->updateRememberToken($user, 'remember-token');
@@ -89,7 +89,7 @@ public function testUpdateRememberTokenRestoresTimestampsAfterSaveFailure(): voi
$exception = new RuntimeException('Save failed.');
$user = new EloquentProviderRememberUserStub;
$user->saveException = $exception;
- $provider = new EloquentUserProvider(Double::for(Hasher::class), $user::class);
+ $provider = new EloquentUserProvider(Double::for(Hasher::class)->strict(), $user::class);
try {
$provider->updateRememberToken($user, 'remember-token');
@@ -153,10 +153,10 @@ public function testCredentialValidationFailed(): void
public function testCredentialValidationFailsGracefullyWithNullPassword(): void
{
- $hasher = Double::for(Hasher::class);
+ $hasher = Double::for(Hasher::class)->strict();
$hasher->expects('check')->never();
$provider = new EloquentUserProvider($hasher, 'foo');
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthPassword')->returns(null);
$result = $provider->validateCredentials($user, ['password' => 'plain']);
@@ -194,7 +194,7 @@ public function testRehashPasswordIfRequiredWithCustomPasswordColumn(): void
public function testDontRehashPasswordIfNotRequired(): void
{
- $hasher = Double::for(Hasher::class);
+ $hasher = Double::for(Hasher::class)->strict();
$hasher->expects('needsRehash')->with('hash')->returns(false);
$hasher->expects('make')->never();
diff --git a/tests/Auth/AuthGuardTest.php b/tests/Auth/AuthGuardTest.php
index d987292537..a59a9e301b 100755
--- a/tests/Auth/AuthGuardTest.php
+++ b/tests/Auth/AuthGuardTest.php
@@ -48,8 +48,8 @@ public function testBasicReturnsNullOnValidAttempt(): void
$user = new GenericUser(['id' => 10, 'password' => 'secret']);
$credentials = ['email' => 'foo@bar.com', 'password' => 'secret'];
$provider->expects('retrieveByCredentials')->with($credentials)->returns($user);
- $provider->expects('validateCredentials')->with($user, $credentials)->returns(true);
- $provider->expects('rehashPasswordIfRequired')->with($user, $credentials);
+ $provider->expects('validateCredentials')->with(Argument::same($user), $credentials)->returns(true);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), $credentials);
$this->assertNull($guard->basic('email'));
$this->assertSame($user, $guard->user());
@@ -77,7 +77,7 @@ public function testBasicReturnsResponseOnFailure(): void
$user = new GenericUser(['id' => 10, 'password' => 'secret']);
$credentials = ['email' => 'foo@bar.com', 'password' => 'secret'];
$provider->expects('retrieveByCredentials')->with($credentials)->returns($user);
- $provider->expects('validateCredentials')->with($user, $credentials)->returns(false);
+ $provider->expects('validateCredentials')->with(Argument::same($user), $credentials)->returns(false);
$provider->expects('rehashPasswordIfRequired')->never();
$guard->basic('email');
@@ -90,8 +90,8 @@ public function testBasicWithExtraConditions(): void
$user = new GenericUser(['id' => 10, 'password' => 'secret']);
$credentials = ['email' => 'foo@bar.com', 'password' => 'secret', 'active' => 1];
$provider->expects('retrieveByCredentials')->with($credentials)->returns($user);
- $provider->expects('validateCredentials')->with($user, $credentials)->returns(true);
- $provider->expects('rehashPasswordIfRequired')->with($user, $credentials);
+ $provider->expects('validateCredentials')->with(Argument::same($user), $credentials)->returns(true);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), $credentials);
$this->assertNull($guard->basic('email', ['active' => 1]));
$this->assertSame($user, $guard->user());
@@ -105,8 +105,8 @@ public function testBasicWithExtraArrayConditions(): void
$user = new GenericUser(['id' => 10, 'password' => 'secret']);
$credentials = ['email' => 'foo@bar.com', 'password' => 'secret', 'active' => 1, 'type' => [1, 2, 3]];
$provider->expects('retrieveByCredentials')->with($credentials)->returns($user);
- $provider->expects('validateCredentials')->with($user, $credentials)->returns(true);
- $provider->expects('rehashPasswordIfRequired')->with($user, $credentials);
+ $provider->expects('validateCredentials')->with(Argument::same($user), $credentials)->returns(true);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), $credentials);
$this->assertNull($guard->basic('email', ['active' => 1, 'type' => [1, 2, 3]]));
$this->assertSame($user, $guard->user());
@@ -138,8 +138,8 @@ public function testAttemptReturnsUserInterface(): void
$guard->setDispatcher($events);
$user = new GenericUser(['id' => 10]);
$provider->expects('retrieveByCredentials')->returns($user);
- $provider->expects('validateCredentials')->with($user, ['foo'])->returns(true);
- $provider->expects('rehashPasswordIfRequired')->with($user, ['foo']);
+ $provider->expects('validateCredentials')->with(Argument::same($user), ['foo'])->returns(true);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), ['foo']);
$this->assertTrue($guard->attempt(['foo']));
$this->assertSame($user, $guard->getUser());
@@ -173,7 +173,7 @@ public function testAttemptAndWithCallbacks(): void
$user = new GenericUser(['id' => 'bar']);
$provider->expects('retrieveByCredentials')->times(3)->with(['foo'])->returns($user);
$provider->expects('validateCredentials')->times(3)->returns(true, true, false);
- $provider->expects('rehashPasswordIfRequired')->with($user, ['foo']);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), ['foo']);
$this->assertTrue($mock->attemptWhen(['foo'], function (Authenticatable $user, SessionGuard $guard): bool {
$this->assertInstanceOf(Authenticatable::class, $user);
@@ -212,8 +212,8 @@ public function testAttemptRehashesPasswordWhenRequired(): void
$guard->setDispatcher($events);
$user = new GenericUser(['id' => 10]);
$provider->expects('retrieveByCredentials')->returns($user);
- $provider->expects('validateCredentials')->with($user, ['foo'])->returns(true);
- $provider->expects('rehashPasswordIfRequired')->with($user, ['foo']);
+ $provider->expects('validateCredentials')->with(Argument::same($user), ['foo'])->returns(true);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), ['foo']);
$this->assertTrue($guard->attempt(['foo']));
$this->assertSame($user, $guard->getUser());
@@ -223,13 +223,13 @@ public function testAttemptRehashesPasswordWhenRequired(): void
public function testAttemptDoesntRehashPasswordWhenDisabled(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$guard = new SessionGuard('default', $provider, new Store('test', new ArraySessionHandler(10)), new Container, rehashOnLogin: false, timeboxDuration: 0);
$events = new EventFake(new Dispatcher);
$guard->setDispatcher($events);
$user = new GenericUser(['id' => 10]);
$provider->expects('retrieveByCredentials')->returns($user);
- $provider->expects('validateCredentials')->with($user, ['foo'])->returns(true);
+ $provider->expects('validateCredentials')->with(Argument::same($user), ['foo'])->returns(true);
$provider->expects('rehashPasswordIfRequired')->never();
$this->assertTrue($guard->attempt(['foo']));
$this->assertSame($user, $guard->getUser());
@@ -578,7 +578,7 @@ public function testLoginMethodQueuesCookieWhenRememberingPasswordlessUser(): vo
$guard->getSession()->expects('put')->with($guard->getName(), 'foo');
$guard->getSession()->expects('remove')->with('password_hash_default');
$session->expects('regenerate');
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->allows('getAuthIdentifier')->returns('foo');
$user->allows('getAuthPassword')->returns(null);
$user->allows('getRememberToken')->returns('recaller');
@@ -673,18 +673,17 @@ public function testUserUsesRememberCookieIfItExists(?string $passwordHash): voi
$guard->getRecallerName() => 'id|recaller|' . $guard->hashPasswordForCookie($passwordHash),
]));
$sessionId = $session->getId();
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider->expects('retrieveByToken')->with('id', 'recaller')->returns($user);
$user->expects('getAuthIdentifier')->times(2)->returns('bar');
$user->expects('getAuthPassword')->times(2)->returns($passwordHash);
- $events = Double::for(DispatcherContract::class);
+ $events = Double::for(DispatcherContract::class)->strict();
$events->allows('hasListeners')->resolves(static fn (string $event): bool => $event === Login::class);
$rememberedLogins = [];
- $events->expects('dispatch')->times(2)->with(Argument::satisfies(function (Login $event) use ($guard, &$rememberedLogins): bool {
- $rememberedLogins[] = $guard->viaRemember();
-
- return true;
- }));
+ $events->expects('dispatch')->times(2)->with(Argument::type(Login::class))
+ ->resolves(static function () use ($guard, &$rememberedLogins): void {
+ $rememberedLogins[] = $guard->viaRemember();
+ });
$guard->setDispatcher($events);
$this->assertSame($user, $guard->user());
@@ -745,7 +744,7 @@ public function testUserReturnsNullWhenPasswordlessUserHasInvalidRememberCookieH
$cookieRequest = Request::create('/', 'GET', [], [$guard->getRecallerName() => 'id|recaller|baz']);
$app->instance('request', $cookieRequest);
$session->expects('get')->with($guard->getName())->returns(null);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider->expects('retrieveByToken')->with('id', 'recaller')->returns($user);
$user->expects('getAuthPassword')->returns(null);
@@ -761,7 +760,7 @@ public function testUserRejectsRememberCookieWithInvalidPasswordHash(string $coo
$cookieRequest = Request::create('/', 'GET', [], [$guard->getRecallerName() => 'id|recaller|' . $cookieHash]);
$app->instance('request', $cookieRequest);
$session->expects('get')->with($guard->getName())->returns(null);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider->expects('retrieveByToken')->with('id', 'recaller')->returns($user);
$user->expects('getAuthPassword')->returns('baz');
$session->expects('put')->never();
@@ -809,8 +808,8 @@ public function testLoginOnceSetsUser(): void
$user = new GenericUser(['id' => 10, 'password' => 'secret']);
$provider->expects('retrieveByCredentials')->with(['foo'])->returns($user);
- $provider->expects('validateCredentials')->with($user, ['foo'])->returns(true);
- $provider->expects('rehashPasswordIfRequired')->with($user, ['foo']);
+ $provider->expects('validateCredentials')->with(Argument::same($user), ['foo'])->returns(true);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), ['foo']);
$this->assertTrue($guard->once(['foo']));
$this->assertSame($user, $guard->user());
@@ -823,7 +822,7 @@ public function testLoginOnceFailure(): void
$user = new GenericUser(['id' => 10, 'password' => 'secret']);
$provider->expects('retrieveByCredentials')->with(['foo'])->returns($user);
- $provider->expects('validateCredentials')->with($user, ['foo'])->returns(false);
+ $provider->expects('validateCredentials')->with(Argument::same($user), ['foo'])->returns(false);
$provider->expects('rehashPasswordIfRequired')->never();
$this->assertFalse($guard->once(['foo']));
@@ -848,7 +847,7 @@ public function testForgetUserSetsUserToNull(): void
public function testForgetUserClearsCachedMiss(): void
{
$guard = $this->getGuard();
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$guard->getSession()->expects('get')->times(2)->with($guard->getName())->returns(null, 42);
$guard->getProvider()->expects('retrieveById')->with(42)->returns($user);
@@ -861,8 +860,8 @@ public function testForgetUserClearsCachedMiss(): void
public function testAuthenticatedListenerCanReadAndReplaceResolvedUser(): void
{
$guard = $this->getGuard();
- $user = Double::for(Authenticatable::class);
- $replacement = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
+ $replacement = Double::for(Authenticatable::class)->strict();
$guard->getSession()->expects('get')->with($guard->getName())->returns(1);
$guard->getProvider()->expects('retrieveById')->with(1)->returns($user);
@@ -894,7 +893,7 @@ public function testRememberedUserIsCachedBeforeAndAfterSessionRotation(): void
return $sessionId;
});
$session->expects('get')->with($guard->getName())->returns(null);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider->expects('retrieveByToken')->with('id', 'recaller')->returns($user);
$provider->expects('retrieveById')->never();
$user->expects('getAuthPassword')->returns('baz');
@@ -929,8 +928,8 @@ public function testRememberedUserIsCachedBeforeAndAfterSessionRotation(): void
public function testLoginListenersSeeTheNewUserBeforeAuthenticatedIsFired(): void
{
$guard = $this->getGuard();
- $guard->setUser(Double::for(Authenticatable::class));
- $user = Double::for(Authenticatable::class);
+ $guard->setUser(Double::for(Authenticatable::class)->strict());
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthIdentifier')->returns(42);
$user->expects('getAuthPassword')->returns(null);
$guard->getSession()->expects('put')->with($guard->getName(), 42);
@@ -965,7 +964,7 @@ public function testLoggedInUserSurvivesIndependentSessionRotation(): void
return true;
});
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthIdentifier')->returns(42);
$user->expects('getAuthPassword')->returns(null);
$session->expects('put')->with($guard->getName(), 42);
@@ -998,7 +997,7 @@ public function testMissingUserIsResolvedAgainWhenSessionStateChanges(bool $sess
return $sessionStarted;
});
$session->expects('get')->times(2)->with($guard->getName())->returns(null, 42);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider->expects('retrieveById')->with(42)->returns($user);
$this->assertNull($guard->user());
@@ -1027,7 +1026,7 @@ public function testMissingUserIsNotInheritedByAChildRequest(): void
[$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks();
$guard = new SessionGuard('default', $provider, $session, $app);
$session->expects('get')->times(2)->with($guard->getName())->returns(null, 42);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$provider->expects('retrieveById')->with(42)->returns($user);
$this->assertNull($guard->user());
@@ -1047,7 +1046,7 @@ public function testSetUserBeforeSessionStartCachesTheUser(): void
$session->allows('isStarted')->returns(false);
$guard = new SessionGuard('default', $provider, $session, $app, $timebox);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$guard->setUser($user);
@@ -1065,7 +1064,7 @@ public function testUserSetBeforeSessionStartCanBeReplacedAfterSessionStarts():
});
$guard = new SessionGuard('default', $provider, $session, $app, $timebox);
- $unstartedUser = Double::for(Authenticatable::class);
+ $unstartedUser = Double::for(Authenticatable::class)->strict();
$guard->setUser($unstartedUser);
$session->expects('get')->never();
@@ -1073,7 +1072,7 @@ public function testUserSetBeforeSessionStartCanBeReplacedAfterSessionStarts():
$this->assertSame($unstartedUser, $guard->user());
$sessionStarted = true;
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$guard->setUser($user);
$this->assertSame($user, $guard->user());
@@ -1086,7 +1085,7 @@ public function testForgetUserClearsUserSetBeforeSessionStart(): void
$session->allows('isStarted')->returns(false);
$guard = new SessionGuard('default', $provider, $session, $app, $timebox);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$guard->setUser($user);
$this->assertTrue($guard->hasUser());
@@ -1103,7 +1102,7 @@ public function testLoggedOutFlagMakesUserReturnNull(): void
$mock = Double::for(new SessionGuard('default', $provider, $session, $app))->passthru();
$mock->expects('clearUserDataFromStorage');
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->allows('getRememberToken')->returns(null);
$mock->setUser($user);
@@ -1113,7 +1112,7 @@ public function testLoggedOutFlagMakesUserReturnNull(): void
$this->assertNull($mock->user());
- $nextUser = Double::for(Authenticatable::class);
+ $nextUser = Double::for(Authenticatable::class)->strict();
$nextUser->expects('getAuthIdentifier')->returns(42);
$nextUser->expects('getAuthPassword')->returns(null);
$session->expects('put')->with($mock->getName(), 42);
@@ -1140,7 +1139,7 @@ public function testIdReturnsNullAfterLogout(): void
$mock = Double::for(new SessionGuard('default', $provider, $session, $app))->passthru();
$mock->expects('clearUserDataFromStorage');
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->allows('getRememberToken')->returns(null);
$user->allows('getAuthIdentifier')->returns(42);
@@ -1179,7 +1178,7 @@ public function testAttemptingRegistersEventListener(): void
[$session, $provider, $request, $cookie, $timebox, $app] = $this->getMocks();
$guard = new SessionGuard('default', $provider, $session, $app, $timebox);
- $dispatcher = Double::for(DispatcherContract::class);
+ $dispatcher = Double::for(DispatcherContract::class)->strict();
$dispatcher->expects('listen')
->with(Attempting::class, Argument::type('callable'));
@@ -1190,7 +1189,7 @@ public function testAttemptingRegistersEventListener(): void
public function testAttemptSkipsEventDispatchWhenNoListenersAreRegistered(): void
{
$guard = $this->getGuard();
- $guard->setDispatcher($events = Double::for(DispatcherContract::class));
+ $guard->setDispatcher($events = Double::for(DispatcherContract::class)->strict());
$events->allows('hasListeners')->returns(false);
$events->expects('dispatch')->never();
@@ -1261,7 +1260,7 @@ public function testGetNameContainsGuardName(): void
protected function getRealGuard(?Request $request = null): array
{
$session = new Store('test', new ArraySessionHandler(10));
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$app = new Container;
$app->instance('request', $request ?? Request::create('/', 'GET'));
@@ -1283,7 +1282,7 @@ protected function getGuard(): SessionGuard
*/
protected function getMocks(): array
{
- $session = Double::for(Session::class);
+ $session = Double::for(Session::class)->strict();
$session->allows('isStarted')->returns(true);
$session->allows('getId')->returns('test-session-id');
@@ -1292,10 +1291,10 @@ protected function getMocks(): array
return [
$session,
- Double::for(UserProvider::class),
+ Double::for(UserProvider::class)->strict(),
Request::create('/', 'GET'),
- Double::for(CookieJar::class),
- Double::for(Timebox::class),
+ Double::for(CookieJar::class)->strict(),
+ Double::for(Timebox::class)->strict(),
$app,
];
}
@@ -1305,7 +1304,7 @@ protected function getMocks(): array
*/
protected function mockEventDispatcher(): DispatcherContract
{
- $events = Double::for(DispatcherContract::class);
+ $events = Double::for(DispatcherContract::class)->strict();
$events->allows('hasListeners')->returns(true);
return $events;
diff --git a/tests/Auth/AuthManagerTest.php b/tests/Auth/AuthManagerTest.php
index e9ae7c96d6..fca0858c68 100644
--- a/tests/Auth/AuthManagerTest.php
+++ b/tests/Auth/AuthManagerTest.php
@@ -105,7 +105,7 @@ public function testShouldUseSetsDefaultDriverAndUserResolver(): void
$container->make('config')
->set('auth.guards.api', ['driver' => 'custom']);
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$manager->extend('custom', function () use ($guard) {
return $guard;
});
@@ -144,7 +144,7 @@ public function testExtendDriver(): void
$manager = new AuthManager($container = $this->getContainer());
$container->make('config')
->set('auth.guards.foo', ['driver' => 'bar']);
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$manager->extend('bar', function () use ($guard) {
return $guard;
@@ -163,7 +163,7 @@ public function testGuardWithExplicitFalseyNameDoesNotFallBackToDefaultDriver():
$container->make('config')
->set('auth.guards.foo', ['driver' => 'bar']);
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$test = $this;
$manager->extend('bar', function ($app, string $name) use ($guard, $test): Guard {
$test->assertSame('0', $name);
@@ -182,7 +182,7 @@ public function testGuardWithEmptyNameUsesDefaultDriver(): void
$container->make('config')
->set('auth.guards.foo', ['driver' => 'bar']);
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$manager->extend('bar', fn () => $guard);
$this->assertSame($guard, $manager->guard(''));
@@ -199,7 +199,7 @@ public function testExtendCallbackIsBoundToManager(): void
$manager->extend('bar', function () use (&$boundTo) {
$boundTo = $this;
- return Double::for(Guard::class);
+ return Double::for(Guard::class)->strict();
});
$manager->guard('foo');
@@ -372,12 +372,12 @@ public function testCreateDatabaseUserProvider(): void
'table' => 'users',
]);
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('find')->with(1)->returns(null);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('table')->with('users')->returns($query);
$resolutions = 0;
- $database = Double::for(ConnectionResolverInterface::class);
+ $database = Double::for(ConnectionResolverInterface::class)->strict();
$database->expects('connection')
->with('foo')
->resolves(function () use (&$resolutions, $connection) {
@@ -387,7 +387,7 @@ public function testCreateDatabaseUserProvider(): void
});
$container->instance('db', $database);
- $container->instance('hash', Double::for(HashContract::class));
+ $container->instance('hash', Double::for(HashContract::class)->strict());
$provider = $manager->createUserProvider('foo');
@@ -403,11 +403,11 @@ public function testDatabaseUserProviderUsesDefaultConnectionWhenOmitted(): void
'driver' => 'database',
'table' => 'users',
]);
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('find')->with(1)->returns(null);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('table')->with('users')->returns($query);
- $database = Double::for(ConnectionResolverInterface::class);
+ $database = Double::for(ConnectionResolverInterface::class)->strict();
$database->expects('connection')
->with(null)
->returns($connection);
@@ -424,7 +424,7 @@ public function testDatabaseUserProviderRequiresDeclaredTable(): void
$this->app->make('config')->set('auth.providers.incomplete', [
'driver' => 'database',
]);
- $database = Double::for(ConnectionResolverInterface::class);
+ $database = Double::for(ConnectionResolverInterface::class)->strict();
$database->expects('connection')->never();
$this->app->instance('db', $database);
@@ -443,7 +443,7 @@ public function testCreateCustomUserProvider(): void
'driver' => 'bar',
]);
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$manager->provider('bar', fn () => $provider);
$this->assertSame($provider, $manager->createUserProvider('foo'));
@@ -504,11 +504,11 @@ public function testPartialEloquentUserProviderCacheUsesProviderDefaults(): void
'enabled' => true,
],
]);
- $repository = Double::for(CacheRepository::class);
- $cache = Double::for(CacheManager::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $cache = Double::for(CacheManager::class)->strict();
$cache->expects('store')->with(null)->returns($repository);
$this->app->instance('cache', $cache);
- $validator = Double::for(ModelCacheStoreValidator::class);
+ $validator = Double::for(ModelCacheStoreValidator::class)->strict();
$validator->expects('validate')
->with(Argument::same($repository), 'Auth user cache for model [' . AuthManagerCacheUserStub::class . ']');
$this->app->instance(ModelCacheStoreValidator::class, $validator);
@@ -546,9 +546,9 @@ public function testCreateEloquentUserProviderRejectsInvalidCacheTtl(mixed $ttl,
]));
Container::setInstance($container);
- $container->instance('hash', Double::for(HashContract::class));
+ $container->instance('hash', Double::for(HashContract::class)->strict());
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->expects('store')->never();
$container->instance('cache', $cacheManager);
@@ -598,10 +598,10 @@ public function testViaRequest(): void
'provider' => 'foo',
]);
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$manager->provider('foo', fn () => $provider);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$manager->viaRequest('custom', function (Request $request, ?UserProvider $requestProvider) use ($provider, $user) {
$this->assertSame($provider, $requestProvider);
@@ -623,7 +623,7 @@ public function testViaRequestGuardWithoutProviderKeyGetsNullProvider(): void
'driver' => 'custom',
]);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$manager->viaRequest('custom', function (Request $request, ?UserProvider $requestProvider) use ($user) {
$this->assertNull($requestProvider);
@@ -639,10 +639,10 @@ public function testRedirectGuestsToConfiguresAuthenticateMiddleware(): void
{
$manager = new AuthManager($this->getContainer());
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->allows('check')->returns(false);
- $factory = Double::for(AuthFactory::class);
+ $factory = Double::for(AuthFactory::class)->strict();
$factory->allows('guard')->with(null)->returns($guard);
$manager->redirectGuestsTo('/login');
@@ -715,10 +715,10 @@ public function testRedirectUsersToConfiguresRedirectIfAuthenticatedMiddlewarePe
? '/admin'
: '/dashboard');
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->allows('check')->returns(true);
- $factory = Double::for(AuthFactory::class);
+ $factory = Double::for(AuthFactory::class)->strict();
$factory->allows('guard')->returns($guard);
AuthFacade::swap($factory);
@@ -738,10 +738,10 @@ public function testRedirectToConfiguresBothRedirectSides(): void
$this->assertSame('/login', (new AuthenticationException)->redirectTo(Request::create('/')));
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->allows('check')->returns(true);
- $factory = Double::for(AuthFactory::class);
+ $factory = Double::for(AuthFactory::class)->strict();
$factory->allows('guard')->returns($guard);
AuthFacade::swap($factory);
@@ -772,10 +772,10 @@ public function testRedirectConfigurationUsesMostRecentHighLevelRegistration():
$manager->redirectUsersTo('/first-dashboard');
$manager->redirectUsersTo('/second-dashboard');
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->allows('check')->returns(true);
- $factory = Double::for(AuthFactory::class);
+ $factory = Double::for(AuthFactory::class)->strict();
$factory->allows('guard')->returns($guard);
AuthFacade::swap($factory);
@@ -790,7 +790,7 @@ public function testGuardCachesResolvedInstances(): void
$container->make('config')
->set('auth.guards.foo', ['driver' => 'bar']);
- $manager->extend('bar', fn () => Double::for(Guard::class));
+ $manager->extend('bar', fn () => Double::for(Guard::class)->strict());
$guard1 = $manager->guard('foo');
$guard2 = $manager->guard('foo');
@@ -811,7 +811,7 @@ public function testHasResolvedGuardsReturnsTrueAfterResolving(): void
$container->make('config')
->set('auth.guards.foo', ['driver' => 'bar']);
- $manager->extend('bar', fn () => Double::for(Guard::class));
+ $manager->extend('bar', fn () => Double::for(Guard::class)->strict());
$manager->guard('foo');
$this->assertTrue($manager->hasResolvedGuards());
@@ -823,7 +823,7 @@ public function testForgetGuardsClearsCache(): void
$container->make('config')
->set('auth.guards.foo', ['driver' => 'bar']);
- $manager->extend('bar', fn () => Double::for(Guard::class));
+ $manager->extend('bar', fn () => Double::for(Guard::class)->strict());
$manager->guard('foo');
$this->assertTrue($manager->hasResolvedGuards());
@@ -842,7 +842,7 @@ public function testGetGuardsReturnsAllResolved(): void
$container->make('config')
->set('auth.guards.baz', ['driver' => 'bar']);
- $manager->extend('bar', fn () => Double::for(Guard::class));
+ $manager->extend('bar', fn () => Double::for(Guard::class)->strict());
$manager->guard('foo');
$manager->guard('baz');
@@ -893,7 +893,7 @@ public function testMagicCallDelegatesToDefaultGuard(): void
$container->make('config')
->set('auth.guards.foo', ['driver' => 'bar']);
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->expects('check')->returns(true);
$manager->extend('bar', fn () => $guard);
@@ -909,12 +909,12 @@ public function testClearUserCacheIsNoOpForCustomGuardWithoutGetProvider(): void
],
]));
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$manager->extend('custom', fn () => $guard);
$manager->clearUserCache(42, 'api');
- $this->addToAssertionCount(1);
+ $guard->unused();
}
public function testClearUserCacheUsesSpecifiedGuardProvider(): void
@@ -942,11 +942,11 @@ public function testClearUserCacheUsesSpecifiedGuardProvider(): void
]));
Container::setInstance($container);
- $container->instance('hash', Double::for(HashContract::class));
+ $container->instance('hash', Double::for(HashContract::class)->strict());
- $cacheManager = Double::for(CacheManager::class);
- $adminRepo = Double::for(CacheRepository::class);
- $coordinator = Double::for(ModelCacheCoordinator::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
+ $adminRepo = Double::for(CacheRepository::class)->strict();
+ $coordinator = Double::for(ModelCacheCoordinator::class)->strict();
$coordinator->expects('invalidate')
->with(Argument::same($adminRepo), 'admin_users:' . AuthManagerCacheAdminStub::class . ':42');
$cacheManager->allows('store')->with('admin-store')->returns($adminRepo);
@@ -963,9 +963,9 @@ public function testClearUserCacheAcceptsAnEnumGuardIdentifier(): void
'admin' => ['driver' => 'custom'],
],
]));
- $provider = Double::for(EloquentUserProvider::class);
+ $provider = Double::for(EloquentUserProvider::class)->strict();
$provider->expects('clearUserCache')->with(42);
- $guard = Double::for(TokenGuard::class);
+ $guard = Double::for(TokenGuard::class)->strict();
$guard->expects('getProvider')->returns($provider);
$manager->extend('custom', fn () => $guard);
@@ -991,11 +991,11 @@ public function testClearUserCacheUsesDefaultGuardAndRespectsResolver(): void
]));
Container::setInstance($container);
- $container->instance('hash', Double::for(HashContract::class));
+ $container->instance('hash', Double::for(HashContract::class)->strict());
- $cacheManager = Double::for(CacheManager::class);
- $repo = Double::for(CacheRepository::class);
- $coordinator = Double::for(ModelCacheCoordinator::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
+ $repo = Double::for(CacheRepository::class)->strict();
+ $coordinator = Double::for(ModelCacheCoordinator::class)->strict();
$coordinator->expects('invalidate')
->with(Argument::same($repo), EloquentUserProvider::DEFAULT_CACHE_PREFIX . ':' . AuthManagerCacheUserStub::class . ':tenant:42');
$cacheManager->allows('store')->with('web-store')->returns($repo);
@@ -1028,13 +1028,13 @@ public function testForgetGuardsDoesNotAccumulateAuthCacheDescriptors(): void
]));
Container::setInstance($container);
- $container->instance('hash', Double::for(HashContract::class));
+ $container->instance('hash', Double::for(HashContract::class)->strict());
- $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 = Double::for(CacheManager::class)->strict();
+ $firstRepo = Double::for(CacheRepository::class)->strict();
+ $firstRepo->allows('getStore')->returns(Double::for(RedisStore::class)->strict());
+ $secondRepo = Double::for(CacheRepository::class)->strict();
+ $secondRepo->allows('getStore')->returns(Double::for(RedisStore::class)->strict());
$cacheManager->allows('store')->with('redis')->returns($firstRepo, $secondRepo);
$container->instance('cache', $cacheManager);
$container->instance(ModelCacheCoordinator::class, new ModelCacheCoordinator($container));
@@ -1063,7 +1063,7 @@ protected function getContainer(array $authConfig = []): Container
$container->instance('config', new Repository([
'auth' => $authConfig,
]));
- $validator = Double::for(ModelCacheStoreValidator::class);
+ $validator = Double::for(ModelCacheStoreValidator::class)->strict();
$validator->allows('validate');
$container->instance(ModelCacheStoreValidator::class, $validator);
diff --git a/tests/Auth/AuthPasswordBrokerManagerTest.php b/tests/Auth/AuthPasswordBrokerManagerTest.php
index 8e0f997aeb..42fccb3c6f 100644
--- a/tests/Auth/AuthPasswordBrokerManagerTest.php
+++ b/tests/Auth/AuthPasswordBrokerManagerTest.php
@@ -202,7 +202,7 @@ public function testDefaultDriverThrowsWhenGuardDeclaresNoBroker(): void
public function testSetDefaultDriverOverridesGuardDeclaration(): void
{
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->expects('getDefaultDriver')->never();
$container = $this->makeContainer([
@@ -225,7 +225,7 @@ public function testSetDefaultDriverOverridesGuardDeclaration(): void
#[DataProvider('backedBrokerNames')]
public function testBrokerCanResolveBackedEnum(BackedEnum $name, string $expected): void
{
- $broker = Double::for(PasswordBrokerContract::class);
+ $broker = Double::for(PasswordBrokerContract::class)->strict();
$manager = new AuthPasswordBrokerManagerStub(new Container);
$manager->resolvedBroker = $broker;
@@ -313,14 +313,14 @@ public function testBrokerWithExplicitNameBypassesDefaultResolution(): void
],
],
]);
- $container->instance('auth', $auth = Double::for(AuthManager::class));
- $container->instance('db', $database = Double::for(ConnectionResolverInterface::class));
- $container->instance('hash', Double::for(Hasher::class));
+ $container->instance('auth', $auth = Double::for(AuthManager::class)->strict());
+ $container->instance('db', $database = Double::for(ConnectionResolverInterface::class)->strict());
+ $container->instance('hash', Double::for(Hasher::class)->strict());
$auth->expects('createUserProvider')
->with('admins')
- ->returns(Double::for(UserProvider::class));
- $connection = Double::for(Connection::class);
+ ->returns(Double::for(UserProvider::class)->strict());
+ $connection = Double::for(Connection::class)->strict();
$resolutions = 0;
$database->expects('connection')
->with('passwords')
@@ -356,13 +356,13 @@ public function testBrokerWithExplicitFalseyNameDoesNotFallBackToDefaultDriver()
],
],
]);
- $container->instance('auth', $auth = Double::for(AuthManager::class));
- $container->instance('db', $database = Double::for(ConnectionResolverInterface::class));
- $container->instance('hash', Double::for(Hasher::class));
+ $container->instance('auth', $auth = Double::for(AuthManager::class)->strict());
+ $container->instance('db', $database = Double::for(ConnectionResolverInterface::class)->strict());
+ $container->instance('hash', Double::for(Hasher::class)->strict());
$auth->expects('createUserProvider')
->with('zero')
- ->returns(Double::for(UserProvider::class));
+ ->returns(Double::for(UserProvider::class)->strict());
$database->expects('connection')->never();
$this->assertInstanceOf(PasswordBrokerContract::class, (new PasswordBrokerManager($container))->broker('0'));
@@ -370,7 +370,7 @@ public function testBrokerWithExplicitFalseyNameDoesNotFallBackToDefaultDriver()
public function testBrokerWithEmptyNameUsesDefaultDriver(): void
{
- $broker = Double::for(PasswordBrokerContract::class);
+ $broker = Double::for(PasswordBrokerContract::class)->strict();
$manager = new AuthPasswordBrokerManagerStub(new Container);
$manager->resolvedBroker = $broker;
$manager->setDefaultDriver('users');
@@ -387,14 +387,14 @@ public function testShippedDatabaseBrokerUsesDefaultConnection(): void
],
'auth' => require __DIR__ . '/../../src/foundation/config/auth.php',
]);
- $container->instance('auth', $auth = Double::for(AuthManager::class));
- $container->instance('db', $database = Double::for(ConnectionResolverInterface::class));
- $container->instance('hash', Double::for(Hasher::class));
+ $container->instance('auth', $auth = Double::for(AuthManager::class)->strict());
+ $container->instance('db', $database = Double::for(ConnectionResolverInterface::class)->strict());
+ $container->instance('hash', Double::for(Hasher::class)->strict());
$auth->expects('createUserProvider')
->with('users')
- ->returns(Double::for(UserProvider::class));
- $connection = Double::for(Connection::class);
+ ->returns(Double::for(UserProvider::class)->strict());
+ $connection = Double::for(Connection::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
$broker = (new PasswordBrokerManager($container))->broker('users');
@@ -421,13 +421,13 @@ public function testBrokerUsesDefaultExpiryAndThrottleWhenOmitted(): void
],
],
]);
- $container->instance('auth', $auth = Double::for(AuthManager::class));
- $container->instance('db', $database = Double::for(ConnectionResolverInterface::class));
- $container->instance('hash', Double::for(Hasher::class));
+ $container->instance('auth', $auth = Double::for(AuthManager::class)->strict());
+ $container->instance('db', $database = Double::for(ConnectionResolverInterface::class)->strict());
+ $container->instance('hash', Double::for(Hasher::class)->strict());
$auth->expects('createUserProvider')
->with('users')
- ->returns(Double::for(UserProvider::class));
+ ->returns(Double::for(UserProvider::class)->strict());
$database->expects('connection')->never();
$broker = (new PasswordBrokerManager($container))->broker('users');
@@ -455,16 +455,16 @@ public function testCacheBrokerUsesDefaultStore(array $broker): void
],
],
]);
- $container->instance('auth', $auth = Double::for(AuthManager::class));
- $container->instance('cache', $cache = Double::for(CacheFactory::class));
- $container->instance('hash', Double::for(Hasher::class));
+ $container->instance('auth', $auth = Double::for(AuthManager::class)->strict());
+ $container->instance('cache', $cache = Double::for(CacheFactory::class)->strict());
+ $container->instance('hash', Double::for(Hasher::class)->strict());
$auth->expects('createUserProvider')
->with('users')
- ->returns(Double::for(UserProvider::class));
+ ->returns(Double::for(UserProvider::class)->strict());
$cache->expects('store')
->with(null)
- ->returns(Double::for(CacheRepository::class));
+ ->returns(Double::for(CacheRepository::class)->strict());
$this->assertInstanceOf(
PasswordBrokerContract::class,
@@ -513,9 +513,9 @@ public function testBrokerRejectsUnknownDriver(): void
public function testRefreshingDispatcherUpdatesOnlyConcreteResolvedBrokers(): void
{
$manager = new AuthPasswordBrokerManagerStub(new Container);
- $concreteBroker = Double::for(PasswordBrokerImplementation::class);
- $customBroker = Double::for(PasswordBrokerContract::class);
- $events = Double::for(Dispatcher::class);
+ $concreteBroker = Double::for(PasswordBrokerImplementation::class)->strict();
+ $customBroker = Double::for(PasswordBrokerContract::class)->strict();
+ $events = Double::for(Dispatcher::class)->strict();
$concreteBroker->expects('setDispatcher')->with(Argument::same($events));
$manager->seedBroker('concrete', $concreteBroker);
$manager->seedBroker('custom', $customBroker);
@@ -565,7 +565,7 @@ private function makeContainer(array $config): Container
*/
private function mockAuthFactory(string $guard): AuthFactory
{
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->allows('getDefaultDriver')->returns($guard);
return $auth;
diff --git a/tests/Auth/AuthPasswordBrokerTest.php b/tests/Auth/AuthPasswordBrokerTest.php
index ee5a16ce98..5171544a11 100755
--- a/tests/Auth/AuthPasswordBrokerTest.php
+++ b/tests/Auth/AuthPasswordBrokerTest.php
@@ -51,7 +51,7 @@ public function testIfTokenIsRecentlyCreated(): void
$broker = $this->getBroker($mocks = $this->getMocks());
$user = new User;
$mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user);
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(true);
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(true);
$this->assertSame(PasswordBrokerContract::RESET_THROTTLED, $broker->sendResetLink(['foo']));
}
@@ -61,7 +61,7 @@ public function testGetUserThrowsExceptionIfUserDoesntImplementCanResetPassword(
$this->expectExceptionObject(new UnexpectedValueException('User must implement CanResetPassword interface.'));
$broker = $this->getBroker($mocks = $this->getMocks());
- $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns(Double::for(Authenticatable::class));
+ $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns(Double::for(Authenticatable::class)->strict());
$broker->getUser(['foo']);
}
@@ -78,10 +78,10 @@ public function testUserIsRetrievedByCredentials(): void
public function testBrokerCreatesTokenAndRedirectsWithoutError(): void
{
$broker = $this->getBroker($mocks = $this->getMocks());
- $user = Double::for(Authenticatable::class, CanResetPassword::class);
+ $user = Double::for(Authenticatable::class, CanResetPassword::class)->strict();
$mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user);
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$user->expects('sendPasswordResetNotification')->with('token');
$this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo']));
@@ -90,12 +90,12 @@ public function testBrokerCreatesTokenAndRedirectsWithoutError(): void
public function testResetLinkEventIsSkippedWhenThereAreNoListeners(): void
{
$mocks = $this->getMocks();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(PasswordResetLinkSent::class)->returns(false);
$events->expects('dispatch')->never();
- $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class));
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class)->strict());
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$user->expects('sendPasswordResetNotification')->with('token');
$broker = new PasswordBroker($mocks['tokens'], $mocks['users'], $mocks['name'], $events);
@@ -105,13 +105,13 @@ public function testResetLinkEventIsSkippedWhenThereAreNoListeners(): void
public function testResetLinkEventIsDispatchedWhenThereIsAListener(): void
{
$mocks = $this->getMocks();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(PasswordResetLinkSent::class)->returns(true);
$events->expects('dispatch')
->with(Argument::type(PasswordResetLinkSent::class));
- $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class));
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class)->strict());
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$user->expects('sendPasswordResetNotification')->with('token');
$broker = new PasswordBroker($mocks['tokens'], $mocks['users'], $mocks['name'], $events);
@@ -121,16 +121,16 @@ public function testResetLinkEventIsDispatchedWhenThereIsAListener(): void
public function testEventDispatcherCanBeReplacedOnAnExistingBroker(): void
{
$mocks = $this->getMocks();
- $originalEvents = Double::for(Dispatcher::class);
+ $originalEvents = Double::for(Dispatcher::class)->strict();
$originalEvents->expects('hasListeners')->never();
$originalEvents->expects('dispatch')->never();
- $replacementEvents = Double::for(Dispatcher::class);
+ $replacementEvents = Double::for(Dispatcher::class)->strict();
$replacementEvents->expects('hasListeners')->with(PasswordResetLinkSent::class)->returns(true);
$replacementEvents->expects('dispatch')
->with(Argument::type(PasswordResetLinkSent::class));
- $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class));
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class)->strict());
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$user->expects('sendPasswordResetNotification')->with('token');
$broker = new PasswordBroker($mocks['tokens'], $mocks['users'], $mocks['name'], $originalEvents);
@@ -154,7 +154,7 @@ public function testRedirectReturnedByRemindWhenRecordDoesntExistInTable(): void
$broker = $this->getBroker($mocks = $this->getMocks());
$user = new User;
$mocks['users']->expects('retrieveByCredentials')->with(Arr::except($credentials, ['token']))->returns($user);
- $mocks['tokens']->expects('exists')->with($user, 'token')->returns(false);
+ $mocks['tokens']->expects('exists')->with(Argument::same($user), 'token')->returns(false);
$this->assertSame(PasswordBrokerContract::INVALID_TOKEN, $broker->reset($credentials, function (): void {
}));
@@ -166,8 +166,8 @@ public function testResetRemovesRecordOnReminderTableAndCallsCallback(): void
$broker = $this->getBroker($mocks = $this->getMocks());
$user = new User;
$mocks['users']->expects('retrieveByCredentials')->with(['password' => 'password'])->returns($user);
- $mocks['tokens']->expects('exists')->with($user, 'token')->returns(true);
- $mocks['tokens']->expects('delete')->with($user);
+ $mocks['tokens']->expects('exists')->with(Argument::same($user), 'token')->returns(true);
+ $mocks['tokens']->expects('delete')->with(Argument::same($user));
$callback = function (CanResetPassword $user, string $password) use (&$resetArguments): string {
$resetArguments = ['user' => $user, 'password' => $password];
@@ -189,8 +189,8 @@ public function testExecutesCallbackInsteadOfSendingNotification(): void
$broker = $this->getBroker($mocks = $this->getMocks());
$user = new User;
$mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user);
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$this->assertEquals(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'], $closure));
@@ -200,9 +200,9 @@ public function testExecutesCallbackInsteadOfSendingNotification(): void
public function testSendResetLinkStampsSendingBrokerContext(): void
{
$broker = $this->getBroker($mocks = $this->getMocks());
- $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class));
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class)->strict());
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$user->expects('sendPasswordResetNotification')
->with('token')
->resolves(function (): void {
@@ -217,9 +217,9 @@ public function testSendResetLinkRestoresPreviousSendingBrokerContext(): void
CoroutineContext::set(PasswordBroker::SENDING_BROKER_CONTEXT_KEY, 'outer');
$broker = $this->getBroker($mocks = $this->getMocks());
- $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class));
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class)->strict());
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$user->expects('sendPasswordResetNotification')->with('token');
$this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo']));
@@ -231,9 +231,9 @@ public function testSendResetLinkForgetsSendingBrokerContextWhenNoneExisted(): v
CoroutineContext::forget(PasswordBroker::SENDING_BROKER_CONTEXT_KEY);
$broker = $this->getBroker($mocks = $this->getMocks());
- $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class));
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class)->strict());
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$user->expects('sendPasswordResetNotification')->with('token');
$this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo']));
@@ -243,9 +243,9 @@ public function testSendResetLinkForgetsSendingBrokerContextWhenNoneExisted(): v
public function testSendResetLinkStampsContextForCallback(): void
{
$broker = $this->getBroker($mocks = $this->getMocks());
- $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class));
- $mocks['tokens']->expects('recentlyCreatedToken')->with($user)->returns(false);
- $mocks['tokens']->expects('create')->with($user)->returns('token');
+ $mocks['users']->expects('retrieveByCredentials')->with(['foo'])->returns($user = Double::for(Authenticatable::class, CanResetPassword::class)->strict());
+ $mocks['tokens']->expects('recentlyCreatedToken')->with(Argument::same($user))->returns(false);
+ $mocks['tokens']->expects('create')->with(Argument::same($user))->returns('token');
$user->expects('sendPasswordResetNotification')->never();
$this->assertSame(PasswordBrokerContract::RESET_LINK_SENT, $broker->sendResetLink(['foo'], function (): void {
@@ -267,8 +267,8 @@ protected function getBroker(array $mocks): PasswordBroker
protected function getMocks(): array
{
return [
- 'tokens' => Double::for(TokenRepositoryInterface::class),
- 'users' => Double::for(UserProvider::class),
+ 'tokens' => Double::for(TokenRepositoryInterface::class)->strict(),
+ 'users' => Double::for(UserProvider::class)->strict(),
'name' => 'users',
];
}
diff --git a/tests/Auth/AuthPasswordResetServiceProviderTest.php b/tests/Auth/AuthPasswordResetServiceProviderTest.php
index 7ff8c15805..d7f3f70bfb 100644
--- a/tests/Auth/AuthPasswordResetServiceProviderTest.php
+++ b/tests/Auth/AuthPasswordResetServiceProviderTest.php
@@ -22,7 +22,7 @@ class AuthPasswordResetServiceProviderTest extends TestCase
public function testEventRebindDoesNotResolveAnUnusedPasswordManager(): void
{
[$application, $callback] = $this->registerProvider();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$application->expects('resolved')->with('auth.password')->returns(false);
$application->expects('make')->never()->with('auth.password');
@@ -32,8 +32,8 @@ public function testEventRebindDoesNotResolveAnUnusedPasswordManager(): void
public function testEventRebindRefreshesAnAlreadyResolvedPasswordManager(): void
{
[$application, $callback] = $this->registerProvider();
- $events = Double::for(Dispatcher::class);
- $manager = Double::for(PasswordBrokerManager::class);
+ $events = Double::for(Dispatcher::class)->strict();
+ $manager = Double::for(PasswordBrokerManager::class)->strict();
$application->expects('resolved')->with('auth.password')->returns(true);
$application->expects('make')->with('auth.password')->returns($manager);
$manager->expects('refreshEventDispatcher')->with(Argument::same($events));
@@ -49,7 +49,7 @@ public function testEventRebindRefreshesAnAlreadyResolvedPasswordManager(): void
private function registerProvider(): array
{
$callback = null;
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$application->expects('singleton')
->with('auth.password', Argument::type(Closure::class));
$application->expects('bind')
diff --git a/tests/Auth/AuthRequestGuardTest.php b/tests/Auth/AuthRequestGuardTest.php
index 6ef6b165fa..a0ce114845 100644
--- a/tests/Auth/AuthRequestGuardTest.php
+++ b/tests/Auth/AuthRequestGuardTest.php
@@ -20,7 +20,7 @@ class AuthRequestGuardTest extends TestCase
public function testCallbackReceivesRequestAndProvider(): void
{
$request = Request::create('/');
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
RequestContext::set($request);
$receivedRequest = null;
@@ -30,7 +30,7 @@ public function testCallbackReceivesRequestAndProvider(): void
$receivedRequest = $req;
$receivedProvider = $prov;
- return Double::for(Authenticatable::class);
+ return Double::for(Authenticatable::class)->strict();
}, $this->app, $provider);
$guard->user();
@@ -44,7 +44,7 @@ public function testUserReturnsCachedUserOnSubsequentCalls(): void
RequestContext::set(Request::create('/'));
$callCount = 0;
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$guard = new RequestGuard('custom', function () use (&$callCount, $user) {
++$callCount;
@@ -78,7 +78,7 @@ public function testHasUserReturnsTrueWhenUserExists(): void
{
RequestContext::set(Request::create('/'));
- $guard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class), $this->app);
+ $guard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class)->strict(), $this->app);
$guard->user();
$this->assertTrue($guard->hasUser());
@@ -105,8 +105,8 @@ public function testSetUserOverridesCachedUser(): void
{
RequestContext::set(Request::create('/'));
- $originalUser = Double::for(Authenticatable::class);
- $newUser = Double::for(Authenticatable::class);
+ $originalUser = Double::for(Authenticatable::class)->strict();
+ $newUser = Double::for(Authenticatable::class)->strict();
$guard = new RequestGuard('custom', fn () => $originalUser, $this->app);
$guard->user();
@@ -121,8 +121,8 @@ public function testSetUserOverridesTheResolverAcrossRequestChanges(): void
{
RequestContext::set(Request::create('/first'));
- $resolvedUser = Double::for(Authenticatable::class);
- $explicitUser = Double::for(Authenticatable::class);
+ $resolvedUser = Double::for(Authenticatable::class)->strict();
+ $explicitUser = Double::for(Authenticatable::class)->strict();
$guard = new RequestGuard('custom', fn () => $resolvedUser, $this->app);
$guard->setUser($explicitUser);
@@ -135,7 +135,7 @@ public function testForgetUserClearsCachedUser(): void
{
RequestContext::set(Request::create('/'));
- $guard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class), $this->app);
+ $guard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class)->strict(), $this->app);
$guard->user();
$this->assertTrue($guard->hasUser());
@@ -149,8 +149,8 @@ public function testTwoGuardNamesDoNotCollideInContext(): void
{
RequestContext::set(Request::create('/'));
- $user1 = Double::for(Authenticatable::class);
- $user2 = Double::for(Authenticatable::class);
+ $user1 = Double::for(Authenticatable::class)->strict();
+ $user2 = Double::for(Authenticatable::class)->strict();
$guard1 = new RequestGuard('guard_one', fn () => $user1, $this->app);
$guard2 = new RequestGuard('guard_two', fn () => $user2, $this->app);
@@ -162,9 +162,9 @@ public function testTwoGuardNamesDoNotCollideInContext(): void
public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsUsers(): void
{
RequestContext::set(Request::create('/'));
- $previousGuard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class), $this->app);
+ $previousGuard = new RequestGuard('custom', fn () => Double::for(Authenticatable::class)->strict(), $this->app);
$previousGuard->user();
- $previousGuard->setUser(Double::for(Authenticatable::class));
+ $previousGuard->setUser(Double::for(Authenticatable::class)->strict());
$callCount = 0;
$guard = new RequestGuard('custom', function () use (&$callCount) {
@@ -189,7 +189,7 @@ public function testReplacingRequestInContextChangesWhatGuardSees(): void
$guard = new RequestGuard('custom', function ($req) use (&$seenRequests) {
$seenRequests[] = $req;
- return Double::for(Authenticatable::class);
+ return Double::for(Authenticatable::class)->strict();
}, $this->app);
// First call sees request1
@@ -218,10 +218,10 @@ public function testAuthContextKeysIncludeOnlyDurableExplicitState(): void
public function testValidateCallsCallbackWithCredentialsRequest(): void
{
$request = Request::create('/');
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$guard = new RequestGuard('custom', function ($req) {
- return $req instanceof Request ? Double::for(Authenticatable::class) : null;
+ return $req instanceof Request ? Double::for(Authenticatable::class)->strict() : null;
}, $this->app, $provider);
$this->assertTrue($guard->validate(['request' => $request]));
diff --git a/tests/Auth/AuthServiceProviderTest.php b/tests/Auth/AuthServiceProviderTest.php
index 60c1760894..959e1b2a7e 100644
--- a/tests/Auth/AuthServiceProviderTest.php
+++ b/tests/Auth/AuthServiceProviderTest.php
@@ -52,7 +52,7 @@ public function testBootContributesEnabledConfiguredEloquentModelsAndFrameworkCo
],
]);
$resolver = null;
- $manager = Double::for(CacheManager::class);
+ $manager = Double::for(CacheManager::class)->strict();
$manager->expects('allowSerializableClassesUsing')
->with(Argument::capture($resolver));
$application = $this->consoleApplication();
@@ -61,7 +61,7 @@ public function testBootContributesEnabledConfiguredEloquentModelsAndFrameworkCo
(new AuthServiceProvider($application->instance()))->boot(
$manager,
$config,
- Double::for(GateContract::class, override: true)->instance(),
+ Double::for(GateContract::class, override: true)->strict()->instance(),
);
$this->assertInstanceOf(Closure::class, $resolver);
@@ -90,13 +90,13 @@ public function testConsoleStartupValidatesEveryEnabledProviderUsingCapturedDepe
],
],
]);
- $defaultRepository = Double::for(CacheRepository::class);
- $redisRepository = Double::for(CacheRepository::class);
- $manager = Double::for(CacheManager::class);
+ $defaultRepository = Double::for(CacheRepository::class)->strict();
+ $redisRepository = Double::for(CacheRepository::class)->strict();
+ $manager = Double::for(CacheManager::class)->strict();
$manager->expects('allowSerializableClassesUsing');
$manager->expects('store')->with(null)->returns($defaultRepository);
$manager->expects('store')->with('redis')->returns($redisRepository);
- $validator = Double::for(ModelCacheStoreValidator::class);
+ $validator = Double::for(ModelCacheStoreValidator::class)->strict();
$validator->expects('validate')
->with(Argument::same($defaultRepository), 'Auth user provider [0]');
$validator->expects('validate')
@@ -112,7 +112,7 @@ public function testConsoleStartupValidatesEveryEnabledProviderUsingCapturedDepe
(new AuthServiceProvider($application->instance()))->boot(
$manager,
$config,
- Double::for(GateContract::class, override: true)->instance(),
+ Double::for(GateContract::class, override: true)->strict()->instance(),
);
$this->assertInstanceOf(Closure::class, $bootedCallback);
@@ -140,7 +140,7 @@ public function testDisabledProvidersResolveNeitherAStoreNorTheValidator(): void
],
],
]);
- $manager = Double::for(CacheManager::class);
+ $manager = Double::for(CacheManager::class)->strict();
$resolver = null;
$manager->expects('allowSerializableClassesUsing')
->with(Argument::capture($resolver));
@@ -154,7 +154,7 @@ public function testDisabledProvidersResolveNeitherAStoreNorTheValidator(): void
(new AuthServiceProvider($application->instance()))->boot(
$manager,
$config,
- Double::for(GateContract::class, override: true)->instance(),
+ Double::for(GateContract::class, override: true)->strict()->instance(),
);
$this->assertSame([], $resolver());
@@ -174,20 +174,20 @@ public function testServerValidationUsesWorkerDependenciesAndRunsForTaskworkers(
],
],
]);
- $masterManager = Double::for(CacheManager::class);
+ $masterManager = Double::for(CacheManager::class)->strict();
$masterManager->expects('allowSerializableClassesUsing');
$masterManager->expects('store')->never();
- $workerRepository = Double::for(CacheRepository::class);
- $workerManager = Double::for(CacheManager::class);
+ $workerRepository = Double::for(CacheRepository::class)->strict();
+ $workerManager = Double::for(CacheManager::class)->strict();
$workerManager->expects('store')->with('worker')->returns($workerRepository);
- $validator = Double::for(ModelCacheStoreValidator::class);
+ $validator = Double::for(ModelCacheStoreValidator::class)->strict();
$validator->expects('validate')
->with(Argument::same($workerRepository), 'Auth user provider [users]');
$listener = null;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('listen')
->with(AfterWorkerStart::class, Argument::capture($listener));
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$application->expects('make')
->with(CacheManager::class)
->returns($workerManager);
@@ -204,11 +204,11 @@ public function testServerValidationUsesWorkerDependenciesAndRunsForTaskworkers(
(new AuthServiceProvider($application->instance()))->boot(
$masterManager,
$masterConfig,
- Double::for(GateContract::class, override: true)->instance(),
+ Double::for(GateContract::class, override: true)->strict()->instance(),
);
$this->assertInstanceOf(Closure::class, $listener);
- $server = Double::for(SwooleServer::class);
+ $server = Double::for(SwooleServer::class)->strict();
// Store validation runs in request workers and taskworkers, unlike Swoole timer registration.
$server->taskworker = true;
$listener(new AfterWorkerStart($server, 8));
@@ -219,13 +219,13 @@ public function testBootReplacesQueryBuilderMacrosWithFreshGate(): void
$config = new ConfigRepository([
'auth' => ['providers' => []],
]);
- $firstManager = Double::for(CacheManager::class);
+ $firstManager = Double::for(CacheManager::class)->strict();
$firstManager->expects('allowSerializableClassesUsing');
- $secondManager = Double::for(CacheManager::class);
+ $secondManager = Double::for(CacheManager::class)->strict();
$secondManager->expects('allowSerializableClassesUsing');
- $firstGate = Double::for(GateContract::class, override: true);
+ $firstGate = Double::for(GateContract::class, override: true)->strict();
$firstGate->expects('scope')->never();
- $secondGate = Double::for(GateContract::class, override: true);
+ $secondGate = Double::for(GateContract::class, override: true)->strict();
$secondGate->expects('scope')
->with('edit', Argument::type(EloquentBuilder::class))
->resolves(static fn (mixed $ability, EloquentBuilder $query): EloquentBuilder => $query);
@@ -237,7 +237,7 @@ public function testBootReplacesQueryBuilderMacrosWithFreshGate(): void
(new AuthServiceProvider($firstApplication->instance()))->boot($firstManager, $config, $firstGate->instance());
(new AuthServiceProvider($secondApplication->instance()))->boot($secondManager, $config, $secondGate->instance());
- $query = new EloquentBuilder(Double::for(QueryBuilder::class));
+ $query = new EloquentBuilder(Double::for(QueryBuilder::class)->strict());
$this->assertSame($query, $query->whereCan('edit'));
}
@@ -251,7 +251,7 @@ public function testStartupRequiresAnEloquentAuthenticatableModel(): void
],
],
]);
- $manager = Double::for(CacheManager::class);
+ $manager = Double::for(CacheManager::class)->strict();
$startup = $this->bootAndCaptureStartupValidation($manager, $config);
$this->expectException(InvalidArgumentException::class);
@@ -271,7 +271,7 @@ public function testStartupRequiresAStringOrNullStore(): void
],
],
]);
- $manager = Double::for(CacheManager::class);
+ $manager = Double::for(CacheManager::class)->strict();
$startup = $this->bootAndCaptureStartupValidation($manager, $config);
$this->expectException(InvalidArgumentException::class);
@@ -292,7 +292,7 @@ public function testStartupRequiresPositiveIntegerCacheTtl(mixed $ttl): void
],
],
]);
- $manager = Double::for(CacheManager::class);
+ $manager = Double::for(CacheManager::class)->strict();
$startup = $this->bootAndCaptureStartupValidation($manager, $config);
$this->expectException(InvalidArgumentException::class);
@@ -323,7 +323,7 @@ public function testStartupRequiresAnArrayOfStringsOrNullCacheTags(mixed $tags):
],
],
]);
- $manager = Double::for(CacheManager::class);
+ $manager = Double::for(CacheManager::class)->strict();
$startup = $this->bootAndCaptureStartupValidation($manager, $config);
$this->expectException(InvalidArgumentException::class);
@@ -351,10 +351,10 @@ public function testStartupValidatesTagSupportForTaggedProvider(): void
],
],
]);
- $repository = Double::for(CacheRepository::class);
- $manager = Double::for(CacheManager::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $manager = Double::for(CacheManager::class)->strict();
$manager->expects('store')->with('redis')->returns($repository);
- $validator = Double::for(ModelCacheStoreValidator::class);
+ $validator = Double::for(ModelCacheStoreValidator::class)->strict();
$validator->expects('validate')
->with(Argument::same($repository), 'Auth user provider [users]');
$validator->expects('validateAnyModeTags')
@@ -394,7 +394,7 @@ private function cachedProvider(
*/
private function consoleApplication(): OverriddenDouble
{
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$application->expects('runningInConsole')->returns(true);
return $application;
@@ -424,7 +424,7 @@ private function bootAndCaptureStartupValidation(
(new AuthServiceProvider($application->instance()))->boot(
$manager,
$config,
- Double::for(GateContract::class, override: true)->instance(),
+ Double::for(GateContract::class, override: true)->strict()->instance(),
);
$this->assertInstanceOf(Closure::class, $startup);
diff --git a/tests/Auth/AuthTokenGuardTest.php b/tests/Auth/AuthTokenGuardTest.php
index 26c5541d30..9913bce865 100644
--- a/tests/Auth/AuthTokenGuardTest.php
+++ b/tests/Auth/AuthTokenGuardTest.php
@@ -37,7 +37,7 @@ protected function createGuard(
public function testUserCanBeRetrievedByQueryStringVariable(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns($user);
@@ -55,7 +55,7 @@ public function testUserCanBeRetrievedByQueryStringVariable(): void
public function testTokenCanBeHashed(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['api_token' => hash('sha256', 'foo')])->returns($user);
@@ -73,7 +73,7 @@ public function testTokenCanBeHashed(): void
public function testUserCannotBeRetrievedWithNonStringToken(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->never();
$request = Request::create('/', 'GET', ['api_token' => [0]]);
@@ -84,7 +84,7 @@ public function testUserCannotBeRetrievedWithNonStringToken(): void
public function testUserCanBeRetrievedByAuthHeaders(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns($user);
@@ -99,7 +99,7 @@ public function testUserCanBeRetrievedByAuthHeaders(): void
public function testUserCanBeRetrievedByBearerToken(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns($user);
@@ -114,7 +114,7 @@ public function testUserCanBeRetrievedByBearerToken(): void
public function testValidateCanDetermineIfCredentialsAreValid(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns($user);
@@ -129,7 +129,7 @@ public function testValidateCanDetermineIfCredentialsAreValid(): void
#[TestWith(['provided_token', 'stored_token', 'plain-token'])]
public function testValidateHashesTokenWhenHashingIsEnabled(string $inputKey, string $storageKey, string $token): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')
@@ -149,7 +149,7 @@ public function testValidateHashesTokenWhenHashingIsEnabled(string $inputKey, st
public function testValidateCanDetermineIfCredentialsAreInvalid(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->with(['api_token' => 'foo'])->returns(null);
$request = Request::create('/', 'GET', ['api_token' => 'foo']);
@@ -160,7 +160,7 @@ public function testValidateCanDetermineIfCredentialsAreInvalid(): void
public function testValidateRejectsMissingToken(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->never();
$guard = $this->createGuard($provider, Request::create('/'));
@@ -170,7 +170,7 @@ public function testValidateRejectsMissingToken(): void
public function testValidatePreservesStringZero(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')
->with(['api_token' => '0'])
->returns(new AuthTokenGuardTestUser);
@@ -182,7 +182,7 @@ public function testValidatePreservesStringZero(): void
public function testValidateIfApiTokenIsEmpty(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->never();
$request = Request::create('/', 'GET', ['api_token' => '']);
@@ -193,7 +193,7 @@ public function testValidateIfApiTokenIsEmpty(): void
public function testValidateRejectsNonStringToken(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->never();
$request = Request::create('/');
@@ -204,7 +204,7 @@ public function testValidateRejectsNonStringToken(): void
public function testItAllowsToPassCustomRequestViaContainerAndUseItForValidation(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['api_token' => 'custom'])->returns($user);
@@ -222,7 +222,7 @@ public function testItAllowsToPassCustomRequestViaContainerAndUseItForValidation
public function testUserCanBeRetrievedByBearerTokenWithCustomKey(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns($user);
@@ -237,7 +237,7 @@ public function testUserCanBeRetrievedByBearerTokenWithCustomKey(): void
public function testUserCanBeRetrievedByQueryStringVariableWithCustomKey(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns($user);
@@ -255,7 +255,7 @@ public function testUserCanBeRetrievedByQueryStringVariableWithCustomKey(): void
public function testUserCanBeRetrievedByAuthHeadersWithCustomField(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns($user);
@@ -270,7 +270,7 @@ public function testUserCanBeRetrievedByAuthHeadersWithCustomField(): void
public function testValidateCanDetermineIfCredentialsAreValidWithCustomKey(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$user = new AuthTokenGuardTestUser;
$user->id = 1;
$provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns($user);
@@ -283,7 +283,7 @@ public function testValidateCanDetermineIfCredentialsAreValidWithCustomKey(): vo
public function testValidateCanDetermineIfCredentialsAreInvalidWithCustomKey(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->with(['custom_token_field' => 'foo'])->returns(null);
$request = Request::create('/', 'GET', ['custom_token_field' => 'foo']);
@@ -294,7 +294,7 @@ public function testValidateCanDetermineIfCredentialsAreInvalidWithCustomKey():
public function testValidateIfApiTokenIsEmptyWithCustomKey(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$request = Request::create('/', 'GET', ['custom_token_field' => '']);
$guard = $this->createGuard($provider, $request, 'custom_token_field', 'custom_token_field');
@@ -305,7 +305,7 @@ public function testValidateIfApiTokenIsEmptyWithCustomKey(): void
public function testTokenLookupStopsAfterTheFirstNonEmptyString(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$request = Double::for(new Request, override: true)->passthru();
$request->expects('query')->with('api_token')->returns('query-token');
$request->expects('input')->never();
@@ -319,7 +319,7 @@ public function testTokenLookupStopsAfterTheFirstNonEmptyString(): void
public function testTokenLookupFallsThroughInvalidAndEmptyValues(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$request = Double::for(new Request, override: true)->passthru();
$request->expects('query')->with('api_token')->returns(['invalid']);
$request->expects('input')->with('api_token')->returns('');
@@ -333,7 +333,7 @@ public function testTokenLookupFallsThroughInvalidAndEmptyValues(): void
public function testTokenLookupPreservesStringZero(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$request = Double::for(new Request, override: true)->passthru();
$request->expects('query')->with('api_token')->returns('0');
$request->expects('input')->never();
@@ -356,7 +356,7 @@ public function testDifferentTokensGetDifferentCachedUsers(): void
$user2 = new AuthTokenGuardTestUser;
$user2->id = 2;
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')
->with(['api_token' => 'token-a'])
->returns($user1);
@@ -382,7 +382,7 @@ public function testCopiedRequestRechecksTheSameTokenWithoutChangingItsParent():
{
$user = new AuthTokenGuardTestUser;
$user->id = 1;
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->with(['api_token' => 'token'])
->times(2)->returns($user, null);
$request = Request::create('/', 'GET', ['api_token' => 'token']);
@@ -400,7 +400,7 @@ public function testCopiedRequestRechecksTheSameTokenWithoutChangingItsParent():
public function testEmptyTokenUsesDefaultKey(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$request = Request::create('/', 'GET');
$guard = $this->createGuard($provider, $request);
@@ -416,7 +416,7 @@ public function testSetUserOverridesAnUnrelatedRequestToken(): void
$user = new AuthTokenGuardTestUser;
$user->id = 1;
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->never();
$request = Request::create('/', 'GET', ['api_token' => 'my-token']);
@@ -435,7 +435,7 @@ public function testForgetUserRestoresNormalTokenAuthentication(): void
$tokenUser = new AuthTokenGuardTestUser;
$tokenUser->id = 2;
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')
->with(['api_token' => 'my-token'])
->returns($tokenUser);
@@ -458,7 +458,7 @@ public function testForgetUserRestoresNormalTokenAuthentication(): void
public function testExplicitUsersAreIsolatedByGuard(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->never();
$request = Request::create('/', 'GET', ['api_token' => 'request-token']);
RequestContext::set($request);
@@ -483,12 +483,12 @@ public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsUsers()
$tokenUser->id = 1;
$explicitUser = new AuthTokenGuardTestUser;
$explicitUser->id = 2;
- $previousProvider = Double::for(UserProvider::class);
+ $previousProvider = Double::for(UserProvider::class)->strict();
$previousProvider->expects('retrieveByCredentials')->with(['api_token' => 'request-token'])->returns($tokenUser);
$previousGuard = $this->createGuard($previousProvider, Request::create('/', 'GET', ['api_token' => 'request-token']));
$this->assertSame($tokenUser, $previousGuard->user());
$previousGuard->setUser($explicitUser);
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->with(['api_token' => 'request-token'])->returns(null);
$guard = new TokenGuard('token', $provider, $this->app);
@@ -499,7 +499,7 @@ public function testNewGuardWithTheSameNameStartsWithoutThePreviousGuardsUsers()
public function testExplicitUsersAreIsolatedBetweenCoroutines(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->never();
$guard = new TokenGuard('token', $provider, $this->app);
@@ -528,7 +528,7 @@ function () use ($guard): int {
public function testAuthContextKeysIncludeOnlyDurableExplicitState(): void
{
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$guard = $this->createGuard(
$provider,
Request::create('/', 'GET', ['api_token' => 'request-token']),
@@ -544,7 +544,7 @@ public function testChangingRequestTokenChangesWhichCachedUserIsSeen(): void
$user1 = new AuthTokenGuardTestUser;
$user1->id = 1;
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')
->with(['api_token' => 'token-a'])
->returns($user1);
diff --git a/tests/Auth/AuthenticateMiddlewareTest.php b/tests/Auth/AuthenticateMiddlewareTest.php
index 97846fb69f..9e01c570bd 100644
--- a/tests/Auth/AuthenticateMiddlewareTest.php
+++ b/tests/Auth/AuthenticateMiddlewareTest.php
@@ -160,7 +160,7 @@ public function testCustomDriverClosureBoundObjectIsAuthManager(): void
$this->auth->extend(__CLASS__, function () use (&$boundTo): Guard {
$boundTo = $this;
- return Double::for(Guard::class);
+ return Double::for(Guard::class)->strict();
});
$this->auth->guard(__CLASS__);
@@ -170,7 +170,7 @@ public function testCustomDriverClosureBoundObjectIsAuthManager(): void
public function testCustomDriverStatic(): void
{
- $driver = Double::for(Guard::class);
+ $driver = Double::for(Guard::class)->strict();
$this->auth->extend(__CLASS__, static fn (): Guard => $driver);
@@ -179,7 +179,7 @@ public function testCustomDriverStatic(): void
public function testCustomInvokableDriver(): void
{
- $driver = Double::for(Guard::class);
+ $driver = Double::for(Guard::class)->strict();
$creator = new AuthenticateMiddlewareTestCustomAuthDriver($driver);
$this->auth->extend(__CLASS__, $creator(...));
@@ -265,8 +265,8 @@ protected function registerAuthDriver(string $name, bool $authenticated): Reques
protected function createAuthDriver(string $name, bool $authenticated): RequestGuard
{
return new RequestGuard($name, function () use ($authenticated): ?Authenticatable {
- return $authenticated ? Double::for(Authenticatable::class) : null;
- }, Container::getInstance(), Double::for(EloquentUserProvider::class));
+ return $authenticated ? Double::for(Authenticatable::class)->strict() : null;
+ }, Container::getInstance(), Double::for(EloquentUserProvider::class)->strict());
}
/**
diff --git a/tests/Auth/AuthenticateWithBasicAuthMiddlewareTest.php b/tests/Auth/AuthenticateWithBasicAuthMiddlewareTest.php
index 134d8086a1..e32212fa6e 100644
--- a/tests/Auth/AuthenticateWithBasicAuthMiddlewareTest.php
+++ b/tests/Auth/AuthenticateWithBasicAuthMiddlewareTest.php
@@ -42,10 +42,10 @@ public function testUsingGeneratesCorrectMiddlewareString(): void
public function testItCallsBasicWithDefaultField(): void
{
- $guard = Double::for(Guard::class, SupportsBasicAuth::class);
+ $guard = Double::for(Guard::class, SupportsBasicAuth::class)->strict();
$guard->expects('basic')->with('email')->returns(null);
- $authFactory = Double::for(AuthFactory::class);
+ $authFactory = Double::for(AuthFactory::class)->strict();
$authFactory->expects('guard')->with(null)->returns($guard);
$middleware = new AuthenticateWithBasicAuth($authFactory);
@@ -59,10 +59,10 @@ public function testItCallsBasicWithDefaultField(): void
public function testItCallsBasicWithCustomField(): void
{
- $guard = Double::for(Guard::class, SupportsBasicAuth::class);
+ $guard = Double::for(Guard::class, SupportsBasicAuth::class)->strict();
$guard->expects('basic')->with('username')->returns(null);
- $authFactory = Double::for(AuthFactory::class);
+ $authFactory = Double::for(AuthFactory::class)->strict();
$authFactory->expects('guard')->with('api')->returns($guard);
$middleware = new AuthenticateWithBasicAuth($authFactory);
@@ -76,10 +76,10 @@ public function testItCallsBasicWithCustomField(): void
public function testItUsesSpecifiedGuard(): void
{
- $guard = Double::for(Guard::class, SupportsBasicAuth::class);
+ $guard = Double::for(Guard::class, SupportsBasicAuth::class)->strict();
$guard->expects('basic')->with('email')->returns(null);
- $authFactory = Double::for(AuthFactory::class);
+ $authFactory = Double::for(AuthFactory::class)->strict();
$authFactory->expects('guard')->with('web')->returns($guard);
$middleware = new AuthenticateWithBasicAuth($authFactory);
@@ -101,7 +101,7 @@ public function testFieldOnlyDefinitionUsesDefaultGuard(): void
],
]));
- $guard = Double::for(Guard::class, SupportsBasicAuth::class);
+ $guard = Double::for(Guard::class, SupportsBasicAuth::class)->strict();
$guard->expects('basic')->with('username')->returns(null);
$auth = new AuthManager($container);
diff --git a/tests/Auth/AuthorizableTest.php b/tests/Auth/AuthorizableTest.php
index c2524cbed6..a8e620b12e 100644
--- a/tests/Auth/AuthorizableTest.php
+++ b/tests/Auth/AuthorizableTest.php
@@ -123,7 +123,7 @@ public function testCannotAcceptsUnitEnumAbilities(): void
*/
private function mockGate(): OverriddenDouble
{
- $gate = Double::for(Gate::class, override: true);
+ $gate = Double::for(Gate::class, override: true)->strict();
$container = new Container;
$container->instance(Gate::class, $gate->instance());
diff --git a/tests/Auth/AuthorizesRequestsTest.php b/tests/Auth/AuthorizesRequestsTest.php
index b7ee3d7b80..8f81b7ccc5 100644
--- a/tests/Auth/AuthorizesRequestsTest.php
+++ b/tests/Auth/AuthorizesRequestsTest.php
@@ -90,7 +90,7 @@ public function testAuthorizeForUserDelegatesToGateForUser(): void
*/
private function mockGate(): OverriddenDouble
{
- $gate = Double::for(Gate::class, override: true);
+ $gate = Double::for(Gate::class, override: true)->strict();
$container = new Container;
$container->instance(Gate::class, $gate->instance());
diff --git a/tests/Auth/CacheTokenRepositoryTest.php b/tests/Auth/CacheTokenRepositoryTest.php
index f2de676f54..956af436e9 100644
--- a/tests/Auth/CacheTokenRepositoryTest.php
+++ b/tests/Auth/CacheTokenRepositoryTest.php
@@ -21,9 +21,9 @@ public function testCreateStoresHashedTokenAndReturnsPlainToken(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0));
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
- $user = Double::for(CanResetPassword::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$hasher->expects('make')->resolves(fn ($token) => 'hashed_' . $token);
@@ -50,9 +50,9 @@ public function testExistsReturnsTrueForValidToken(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0));
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
- $user = Double::for(CanResetPassword::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$cache->expects('get')->returns([
@@ -70,10 +70,10 @@ public function testExistsReturnsFalseForExpiredToken(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0));
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
$hasher->expects('check')->never();
- $user = Double::for(CanResetPassword::class);
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$cache->expects('get')->returns([
@@ -90,9 +90,9 @@ public function testExistsReturnsFalseForInvalidHash(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0));
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
- $user = Double::for(CanResetPassword::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$cache->expects('get')->returns([
@@ -110,9 +110,9 @@ public function testRecentlyCreatedTokenReturnsTrueWithinThrottle(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0));
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
- $user = Double::for(CanResetPassword::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$cache->expects('get')->returns([
@@ -130,9 +130,9 @@ public function testRecentlyCreatedTokenReturnsFalseAfterThrottle(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0));
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
- $user = Double::for(CanResetPassword::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$cache->expects('get')->returns([
@@ -150,9 +150,9 @@ public function testRecentlyCreatedTokenReturnsFalseWhenThrottleIsZero(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::create(2024, 1, 1, 12, 0, 0));
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
- $user = Double::for(CanResetPassword::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$cache->expects('get')->returns([
@@ -168,9 +168,9 @@ public function testRecentlyCreatedTokenReturnsFalseWhenThrottleIsZero(): void
public function testDeleteRemovesFromCache(): void
{
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
- $user = Double::for(CanResetPassword::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$expectedKey = hash('sha256', 'foo@bar.com');
@@ -182,9 +182,9 @@ public function testDeleteRemovesFromCache(): void
public function testCacheKeyHashesEmail(): void
{
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
- $user = Double::for(CanResetPassword::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
+ $user = Double::for(CanResetPassword::class)->strict();
$user->allows('getEmailForPasswordReset')->returns('foo@bar.com');
$repository = new CacheTokenRepository($cache, $hasher, 'test-hash-key');
@@ -194,8 +194,8 @@ public function testCacheKeyHashesEmail(): void
public function testDeleteExpiredIsNoOp(): void
{
- $cache = Double::for(Repository::class);
- $hasher = Double::for(Hasher::class);
+ $cache = Double::for(Repository::class)->strict();
+ $hasher = Double::for(Hasher::class)->strict();
// No cache interaction expected — TTL handles expiry
$repository = new CacheTokenRepository($cache, $hasher, 'test-hash-key');
diff --git a/tests/Auth/ClearResetsCommandTest.php b/tests/Auth/ClearResetsCommandTest.php
index 5ec845ca30..a55e509778 100644
--- a/tests/Auth/ClearResetsCommandTest.php
+++ b/tests/Auth/ClearResetsCommandTest.php
@@ -21,9 +21,9 @@ class ClearResetsCommandTest extends TestCase
public function testClearsExpiredTokensThroughDefaultBroker(): void
{
- $command = $this->makeCommand($manager = Double::for(PasswordBrokerManager::class));
- $broker = Double::for(PasswordBroker::class);
- $repository = Double::for(TokenRepositoryInterface::class);
+ $command = $this->makeCommand($manager = Double::for(PasswordBrokerManager::class)->strict());
+ $broker = Double::for(PasswordBroker::class)->strict();
+ $repository = Double::for(TokenRepositoryInterface::class)->strict();
$manager->expects('broker')->with(null)->returns($broker);
$broker->expects('getRepository')->returns($repository);
@@ -34,9 +34,9 @@ public function testClearsExpiredTokensThroughDefaultBroker(): void
public function testClearsExpiredTokensThroughNamedBroker(): void
{
- $command = $this->makeCommand($manager = Double::for(PasswordBrokerManager::class));
- $broker = Double::for(PasswordBroker::class);
- $repository = Double::for(TokenRepositoryInterface::class);
+ $command = $this->makeCommand($manager = Double::for(PasswordBrokerManager::class)->strict());
+ $broker = Double::for(PasswordBroker::class)->strict();
+ $repository = Double::for(TokenRepositoryInterface::class)->strict();
$manager->expects('broker')->with('admins')->returns($broker);
$broker->expects('getRepository')->returns($repository);
diff --git a/tests/Auth/EnsureEmailIsVerifiedTest.php b/tests/Auth/EnsureEmailIsVerifiedTest.php
index d3b2488c63..de08f2a9da 100644
--- a/tests/Auth/EnsureEmailIsVerifiedTest.php
+++ b/tests/Auth/EnsureEmailIsVerifiedTest.php
@@ -26,7 +26,7 @@ public function testItCanGenerateDefinitionViaStaticMethod(): void
public function testVerifiedUserPassesThrough(): void
{
- $user = Double::for(Authenticatable::class, MustVerifyEmail::class);
+ $user = Double::for(Authenticatable::class, MustVerifyEmail::class)->strict();
$user->allows('hasVerifiedEmail')->returns(true);
$request = Request::create('/');
@@ -42,7 +42,7 @@ public function testVerifiedUserPassesThrough(): void
public function testUserThatDoesNotImplementMustVerifyEmailPassesThrough(): void
{
// User implements Authenticatable but does not implement MustVerifyEmail.
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$request = Request::create('/');
$request->setUserResolver(fn () => $user);
@@ -68,7 +68,7 @@ public function testGuestRequestReturnsJsonWhenExpectsJson(): void
public function testUnverifiedUserReturnsJsonWhenExpectsJson(): void
{
- $user = Double::for(Authenticatable::class, MustVerifyEmail::class);
+ $user = Double::for(Authenticatable::class, MustVerifyEmail::class)->strict();
$user->allows('hasVerifiedEmail')->returns(false);
$request = Request::create('/');
@@ -86,7 +86,7 @@ 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 = Double::for(Authenticatable::class, MustVerifyEmail::class);
+ $user = Double::for(Authenticatable::class, MustVerifyEmail::class)->strict();
$user->allows('hasVerifiedEmail')->returns(false);
$request = Request::create('/');
diff --git a/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php b/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
index fdcc1cb2df..18599ae324 100644
--- a/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
+++ b/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
@@ -99,13 +99,13 @@ public function testDefaultRedirectFallsBackToSlash(): void
public function testMultipleGuardsRedirectsIfAnyAuthenticated(): void
{
- $guestGuard = Double::for(Guard::class);
+ $guestGuard = Double::for(Guard::class)->strict();
$guestGuard->allows('check')->returns(false);
- $authGuard = Double::for(Guard::class);
+ $authGuard = Double::for(Guard::class)->strict();
$authGuard->allows('check')->returns(true);
- $factory = Double::for(AuthFactory::class);
+ $factory = Double::for(AuthFactory::class)->strict();
$factory->expects('guard')->with('web')->returns($guestGuard);
$factory->expects('guard')->with('api')->returns($authGuard);
Auth::swap($factory);
@@ -120,13 +120,13 @@ public function testMultipleGuardsRedirectsIfAnyAuthenticated(): void
public function testPassesThroughWhenAllGuardsAreGuests(): void
{
- $guard1 = Double::for(Guard::class);
+ $guard1 = Double::for(Guard::class)->strict();
$guard1->allows('check')->returns(false);
- $guard2 = Double::for(Guard::class);
+ $guard2 = Double::for(Guard::class)->strict();
$guard2->allows('check')->returns(false);
- $factory = Double::for(AuthFactory::class);
+ $factory = Double::for(AuthFactory::class)->strict();
$factory->expects('guard')->with('web')->returns($guard1);
$factory->expects('guard')->with('api')->returns($guard2);
$factory->expects('shouldUse')->with('web');
@@ -240,10 +240,10 @@ public function testFlushStateClearsRedirectCallback(): void
*/
protected function swapAuthGuard(bool $authenticated): void
{
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->allows('check')->returns($authenticated);
- $factory = Double::for(AuthFactory::class);
+ $factory = Double::for(AuthFactory::class)->strict();
$factory->allows('guard')->returns($guard);
Auth::swap($factory);
}
@@ -268,16 +268,16 @@ protected function makeAuthManager(bool $webAuthenticated, bool $secondaryAuthen
$auth->extend('web', fn (): RequestGuard => new RequestGuard(
'web',
- static fn (): ?Authenticatable => $webAuthenticated ? Double::for(Authenticatable::class) : null,
+ static fn (): ?Authenticatable => $webAuthenticated ? Double::for(Authenticatable::class)->strict() : null,
$container,
- Double::for(EloquentUserProvider::class),
+ Double::for(EloquentUserProvider::class)->strict(),
));
$auth->extend('secondary', fn (): RequestGuard => new RequestGuard(
'secondary',
- static fn (): ?Authenticatable => $secondaryAuthenticated ? Double::for(Authenticatable::class) : null,
+ static fn (): ?Authenticatable => $secondaryAuthenticated ? Double::for(Authenticatable::class)->strict() : null,
$container,
- Double::for(EloquentUserProvider::class),
+ Double::for(EloquentUserProvider::class)->strict(),
));
return $auth;
diff --git a/tests/Auth/RequirePasswordMiddlewareTest.php b/tests/Auth/RequirePasswordMiddlewareTest.php
index cdb3458b0e..6f60dc4354 100644
--- a/tests/Auth/RequirePasswordMiddlewareTest.php
+++ b/tests/Auth/RequirePasswordMiddlewareTest.php
@@ -26,7 +26,7 @@ public function testReturnsJson423WhenStaleAndRequestExpectsJson(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(20000));
- $session = Double::for(Session::class);
+ $session = Double::for(Session::class)->strict();
$session->expects('get')
->with('auth.password_confirmed_at_web', 0)
->returns(0); // Never confirmed
@@ -36,12 +36,12 @@ public function testReturnsJson423WhenStaleAndRequestExpectsJson(): void
$request->headers->set('Accept', 'application/json');
$jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423);
- $responseFactory = Double::for(ResponseFactory::class);
+ $responseFactory = Double::for(ResponseFactory::class)->strict();
$responseFactory->expects('json')
->with(['message' => 'Password confirmation required.'], 423)
->returns($jsonResponse);
- $urlGenerator = Double::for(UrlGenerator::class);
+ $urlGenerator = Double::for(UrlGenerator::class)->strict();
$middleware = $this->middleware(responseFactory: $responseFactory, urlGenerator: $urlGenerator);
$result = $middleware->handle($request, fn () => new Response('should not reach'));
@@ -55,7 +55,7 @@ public function testCustomTimeoutIsHonored(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1000));
- $session = Double::for(Session::class);
+ $session = Double::for(Session::class)->strict();
$session->expects('get')->times(2)
->with('auth.password_confirmed_at_web', 0)
->returns(990); // Confirmed 10 seconds ago
@@ -63,8 +63,8 @@ public function testCustomTimeoutIsHonored(): void
$request = Request::create('/');
$request->setHypervelSession($session);
- $responseFactory = Double::for(ResponseFactory::class);
- $urlGenerator = Double::for(UrlGenerator::class);
+ $responseFactory = Double::for(ResponseFactory::class)->strict();
+ $urlGenerator = Double::for(UrlGenerator::class)->strict();
$middleware = $this->middleware(responseFactory: $responseFactory, urlGenerator: $urlGenerator);
@@ -95,7 +95,7 @@ public function testConfirmationIsScopedToCurrentGuard(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(20000));
- $session = Double::for(Session::class);
+ $session = Double::for(Session::class)->strict();
$session->expects('get')
->with('auth.password_confirmed_at_admin', 0)
->returns(0);
@@ -104,7 +104,7 @@ public function testConfirmationIsScopedToCurrentGuard(): void
$request->setHypervelSession($session);
$request->headers->set('Accept', 'application/json');
- $responseFactory = Double::for(ResponseFactory::class);
+ $responseFactory = Double::for(ResponseFactory::class)->strict();
$responseFactory->expects('json')
->with(['message' => 'Password confirmation required.'], 423)
->returns($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423));
@@ -121,7 +121,7 @@ public function testPerGuardTimeoutIsHonored(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1000));
- $session = Double::for(Session::class);
+ $session = Double::for(Session::class)->strict();
$session->expects('get')
->with('auth.password_confirmed_at_admin', 0)
->times(2)
@@ -130,7 +130,7 @@ public function testPerGuardTimeoutIsHonored(): void
$request = Request::create('/');
$request->setHypervelSession($session);
- $responseFactory = Double::for(ResponseFactory::class);
+ $responseFactory = Double::for(ResponseFactory::class)->strict();
$responseFactory->expects('json')
->with(['message' => 'Password confirmation required.'], 423)
->returns($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423));
@@ -162,7 +162,7 @@ public function testRouteParameterOverridesPerGuardTimeout(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1000));
- $session = Double::for(Session::class);
+ $session = Double::for(Session::class)->strict();
$session->expects('get')
->with('auth.password_confirmed_at_admin', 0)
->returns(994);
@@ -171,7 +171,7 @@ public function testRouteParameterOverridesPerGuardTimeout(): void
$request->setHypervelSession($session);
$request->headers->set('Accept', 'application/json');
- $responseFactory = Double::for(ResponseFactory::class);
+ $responseFactory = Double::for(ResponseFactory::class)->strict();
$responseFactory->expects('json')
->with(['message' => 'Password confirmation required.'], 423)
->returns($jsonResponse = new JsonResponse(['message' => 'Password confirmation required.'], 423));
@@ -203,12 +203,12 @@ private function middleware(
?Repository $config = null,
string $guard = 'web'
): RequirePassword {
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->allows('getDefaultDriver')->returns($guard);
return new RequirePassword(
- $responseFactory ?? Double::for(ResponseFactory::class),
- $urlGenerator ?? Double::for(UrlGenerator::class),
+ $responseFactory ?? Double::for(ResponseFactory::class)->strict(),
+ $urlGenerator ?? Double::for(UrlGenerator::class)->strict(),
$auth,
$config ?? new Repository([
'auth' => [
diff --git a/tests/Auth/TimeboxIsolationTest.php b/tests/Auth/TimeboxIsolationTest.php
index 1fca51ea83..9d85d88a08 100644
--- a/tests/Auth/TimeboxIsolationTest.php
+++ b/tests/Auth/TimeboxIsolationTest.php
@@ -29,8 +29,8 @@ public function testGuardOperationsUseIndependentTimeboxes(string $operation): v
{
$recorder = new TimeboxOperationRecorder;
$timebox = new TrackingTimebox($recorder);
- $provider = Double::for(UserProvider::class);
- $user = Double::for(Authenticatable::class);
+ $provider = Double::for(UserProvider::class)->strict();
+ $user = Double::for(Authenticatable::class)->strict();
$provider->expects('retrieveByCredentials')->times(2)->returns($user, null);
$provider->expects('validateCredentials')->with(Argument::same($user), ['email' => 'test@example.com'])->returns(true);
@@ -42,8 +42,8 @@ public function testGuardOperationsUseIndependentTimeboxes(string $operation): v
$guard = new TrackingSessionGuard(
'web',
$provider,
- Double::for(Session::class),
- Double::for(Container::class, override: true)->instance(),
+ Double::for(Session::class)->strict(),
+ Double::for(Container::class, override: true)->strict()->instance(),
$timebox,
timeboxDuration: 1_000_000,
);
@@ -69,11 +69,11 @@ public function testSendingResetLinksUsesIndependentTimeboxes(): void
{
$recorder = new TimeboxOperationRecorder;
$timebox = new TrackingTimebox($recorder);
- $users = Double::for(UserProvider::class);
+ $users = Double::for(UserProvider::class)->strict();
$users->expects('retrieveByCredentials')->times(2)->with(['email' => 'missing@example.com'])->returns(null);
$broker = new PasswordBroker(
- Double::for(TokenRepositoryInterface::class),
+ Double::for(TokenRepositoryInterface::class)->strict(),
$users,
'users',
timebox: $timebox,
@@ -91,9 +91,9 @@ public function testPasswordResetsUseIndependentTimeboxes(): void
{
$recorder = new TimeboxOperationRecorder;
$timebox = new TrackingTimebox($recorder);
- $tokens = Double::for(TokenRepositoryInterface::class);
- $users = Double::for(UserProvider::class);
- $user = Double::for(Authenticatable::class, CanResetPassword::class);
+ $tokens = Double::for(TokenRepositoryInterface::class)->strict();
+ $users = Double::for(UserProvider::class)->strict();
+ $user = Double::for(Authenticatable::class, CanResetPassword::class)->strict();
$credentials = [
'email' => 'test@example.com',
'password' => 'secret',
diff --git a/tests/Auth/UseGuardMiddlewareTest.php b/tests/Auth/UseGuardMiddlewareTest.php
index 5db0326ff3..5f5ed46c2f 100644
--- a/tests/Auth/UseGuardMiddlewareTest.php
+++ b/tests/Auth/UseGuardMiddlewareTest.php
@@ -26,7 +26,7 @@ class UseGuardMiddlewareTest extends TestCase
public function testItSelectsTheGuardForTheCurrentRequest(): void
{
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->expects('shouldUse')->with('admin');
$request = Request::create('/login');
@@ -90,7 +90,7 @@ private function makeAuthManager(): AuthManager
$guard,
static fn (): ?Authenticatable => null,
$container,
- Double::for(EloquentUserProvider::class),
+ Double::for(EloquentUserProvider::class)->strict(),
));
}
diff --git a/tests/Auth/VerifiedEventTest.php b/tests/Auth/VerifiedEventTest.php
index 4892c08bf3..b557e81912 100644
--- a/tests/Auth/VerifiedEventTest.php
+++ b/tests/Auth/VerifiedEventTest.php
@@ -17,7 +17,7 @@ class VerifiedEventTest extends TestCase
public function testAcceptsVerifiableUserThatIsNotAuthenticatable(): void
{
- $user = Double::for(MustVerifyEmail::class);
+ $user = Double::for(MustVerifyEmail::class)->strict();
$this->assertNotInstanceOf(Authenticatable::class, $user);
$this->assertSame($user, (new Verified($user))->user);
diff --git a/tests/Broadcasting/AblyBroadcasterTest.php b/tests/Broadcasting/AblyBroadcasterTest.php
index fd7b061080..d8e537b825 100644
--- a/tests/Broadcasting/AblyBroadcasterTest.php
+++ b/tests/Broadcasting/AblyBroadcasterTest.php
@@ -155,10 +155,10 @@ public function testAuthThrowAccessDeniedHttpExceptionWithPresenceChannelWhenReq
public function testAuthUsesRewrittenChannelForConfiguredGuardAndOriginalNameForPresenceSignature(): void
{
$wireChannel = 'presence-application.tenant.orders.5';
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthIdentifier')->returns(42);
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->allows('input')->with('channel_name')->returns($wireChannel);
$request->allows('input')->with('socket_id')->returns('abcd.1234');
$request->expects('user')->times(3)->with('members')->returns($user);
diff --git a/tests/Broadcasting/BroadcastConnectionReleaseTest.php b/tests/Broadcasting/BroadcastConnectionReleaseTest.php
index 4cee4dce7b..10e7b94b19 100644
--- a/tests/Broadcasting/BroadcastConnectionReleaseTest.php
+++ b/tests/Broadcasting/BroadcastConnectionReleaseTest.php
@@ -47,7 +47,7 @@ protected function defineEnvironment(Application $app): void
public function testPusherReleasesIdleSessionsAndPreservesTransactionsAndPins(): void
{
$observed = [];
- $pusher = Double::for(Pusher::class);
+ $pusher = Double::for(Pusher::class)->strict();
$pusher->expects('trigger')->times(12)->resolves(function () use (&$observed): object {
$observed[] = $this->borrowedConnections();
DB::connection('broadcast')->selectOne('select 1');
@@ -66,13 +66,13 @@ public function testPusherReleasesIdleSessionsAndPreservesTransactionsAndPins():
public function testAblyReleasesAfterPreparingTheMessage(): void
{
$observed = [];
- $ably = Double::for(AblyRest::class);
- $channel = Double::for(Channel::class);
+ $ably = Double::for(AblyRest::class)->strict();
+ $channel = Double::for(Channel::class)->strict();
$channel->expects('publish')->times(3)->resolves(function () use (&$observed): void {
$observed[] = $this->borrowedConnections();
});
$channel->expects('getCipherParams')->times(3)->returns(null);
- $ably->channels = Double::for(Channels::class);
+ $ably->channels = Double::for(Channels::class)->strict();
$ably->channels->expects('get')->times(3)->returns($channel);
$ably->channels->expects('release')->times(3);
$broadcaster = Double::for(new AblyBroadcaster($this->app, $ably))->passthru();
@@ -90,7 +90,7 @@ public function testAblyReleasesAfterPreparingTheMessage(): void
public function testMercureReleasesBeforeBorrowingItsHttpClient(): void
{
$observed = [];
- $token = Double::for(TokenProviderInterface::class);
+ $token = Double::for(TokenProviderInterface::class)->strict();
$token->allows('getJwt')->returns('test.token.signature');
$hub = new Hub(
new PoolDefinition('release-test', 'mercure', 'release-test', PoolOptions::fromArray([])),
diff --git a/tests/Broadcasting/BroadcastEventTest.php b/tests/Broadcasting/BroadcastEventTest.php
index 7ad780cde4..c7c889fbf1 100644
--- a/tests/Broadcasting/BroadcastEventTest.php
+++ b/tests/Broadcasting/BroadcastEventTest.php
@@ -55,7 +55,7 @@ public function testUniqueBroadcastEventChildPropertyOverridesInheritedAttribute
public function testBasicEventBroadcastParameterFormatting(): void
{
- $broadcaster = Double::for(Broadcaster::class);
+ $broadcaster = Double::for(Broadcaster::class)->strict();
$broadcaster->expects('broadcast')->with(
['test-channel'],
@@ -63,7 +63,7 @@ public function testBasicEventBroadcastParameterFormatting(): void
['firstName' => 'Taylor', 'lastName' => 'Otwell', 'collection' => ['foo' => 'bar']]
);
- $manager = Double::for(BroadcastingFactory::class);
+ $manager = Double::for(BroadcastingFactory::class)->strict();
$manager->expects('connection')->with(null)->returns($broadcaster);
@@ -74,7 +74,7 @@ public function testBasicEventBroadcastParameterFormatting(): void
public function testManualParameterSpecification(): void
{
- $broadcaster = Double::for(Broadcaster::class);
+ $broadcaster = Double::for(Broadcaster::class)->strict();
$broadcaster->expects('broadcast')->with(
['test-channel'],
@@ -82,7 +82,7 @@ public function testManualParameterSpecification(): void
['name' => 'Taylor', 'socket' => null]
);
- $manager = Double::for(BroadcastingFactory::class);
+ $manager = Double::for(BroadcastingFactory::class)->strict();
$manager->expects('connection')->with(null)->returns($broadcaster);
@@ -104,13 +104,13 @@ public function testUninitializedPublicPropertiesAreOmittedFromThePayload(): voi
$payload = get_object_vars($event);
$payload['collection'] = ['foo' => 'bar'];
- $broadcaster = Double::for(Broadcaster::class);
+ $broadcaster = Double::for(Broadcaster::class)->strict();
$broadcaster->expects('broadcast')->with(
['test-channel'],
$event::class,
Argument::satisfies(static fn (array $actual): bool => $actual == $payload),
);
- $manager = Double::for(BroadcastingFactory::class);
+ $manager = Double::for(BroadcastingFactory::class)->strict();
$manager->expects('connection')->with(null)->returns($broadcaster);
(new BroadcastEvent($event))->handle($manager);
@@ -118,11 +118,11 @@ public function testUninitializedPublicPropertiesAreOmittedFromThePayload(): voi
public function testSpecificBroadcasterGiven(): void
{
- $broadcaster = Double::for(Broadcaster::class);
+ $broadcaster = Double::for(Broadcaster::class)->strict();
$broadcaster->expects('broadcast');
- $manager = Double::for(BroadcastingFactory::class);
+ $manager = Double::for(BroadcastingFactory::class)->strict();
$manager->expects('connection')->with('log')->returns($broadcaster);
@@ -133,7 +133,7 @@ public function testSpecificBroadcasterGiven(): void
public function testSpecificChannelsPerConnection(): void
{
- $broadcaster = Double::for(Broadcaster::class);
+ $broadcaster = Double::for(Broadcaster::class)->strict();
$broadcaster->expects('broadcast')->with(
['first-channel'],
@@ -147,7 +147,7 @@ public function testSpecificChannelsPerConnection(): void
['firstName' => 'Taylor']
);
- $manager = Double::for(BroadcastingFactory::class);
+ $manager = Double::for(BroadcastingFactory::class)->strict();
$manager->expects('connection')->with('first_connection')->returns($broadcaster);
$manager->expects('connection')->with('second_connection')->returns($broadcaster);
@@ -191,11 +191,11 @@ public function testBroadcastAsUnitEnumResolvesToName(): void
public function testSingleStringChannelIsBroadcast(): void
{
- $broadcaster = Double::for(Broadcaster::class);
+ $broadcaster = Double::for(Broadcaster::class)->strict();
$broadcaster->expects('broadcast')
->with(['test-channel'], TestBroadcastEventWithStringChannel::class, Argument::type('array'));
- $manager = Double::for(BroadcastingFactory::class);
+ $manager = Double::for(BroadcastingFactory::class)->strict();
$manager->expects('connection')->with(null)->returns($broadcaster);
(new BroadcastEvent(new TestBroadcastEventWithStringChannel))->handle($manager);
@@ -294,14 +294,14 @@ public function testVariadicBackoffIsReadFromTheUnderlyingEvent(): void
*/
protected function assertEventBroadcastsAs(object $event, string $name): void
{
- $broadcaster = Double::for(Broadcaster::class);
+ $broadcaster = Double::for(Broadcaster::class)->strict();
$broadcaster->expects('broadcast')->with(
['test-channel'],
$name,
['firstName' => 'Taylor', 'lastName' => 'Otwell', 'collection' => ['foo' => 'bar']]
);
- $manager = Double::for(BroadcastingFactory::class);
+ $manager = Double::for(BroadcastingFactory::class)->strict();
$manager->expects('connection')->with(null)->returns($broadcaster);
(new BroadcastEvent($event))->handle($manager);
diff --git a/tests/Broadcasting/BroadcastPoolProxyTest.php b/tests/Broadcasting/BroadcastPoolProxyTest.php
index 5b494875e4..4340179df4 100644
--- a/tests/Broadcasting/BroadcastPoolProxyTest.php
+++ b/tests/Broadcasting/BroadcastPoolProxyTest.php
@@ -35,7 +35,7 @@ protected function tearDownInCoroutine(): void
public function testAuthenticatedUserResolverStateIsWrittenOnEveryBorrowIncludingNull(): void
{
- $broadcaster = new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->instance());
+ $broadcaster = new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->strict()->instance());
[$configured, $pools, $definition] = $this->proxy(fn () => $broadcaster);
[$unconfigured] = $this->proxy(fn () => $broadcaster, $pools, $definition);
$configured->resolveAuthenticatedUserUsing(function (Request $request): array {
@@ -64,7 +64,7 @@ public function testAuthenticatedUserResolverStateIsWrittenOnEveryBorrowIncludin
public function testReplacingAndClearingAuthenticatedUserResolverUpdatesBorrowedBroadcaster(): void
{
[$proxy] = $this->proxy(
- fn () => new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->instance())
+ fn () => new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->strict()->instance())
);
$request = Request::create('/broadcasting/user-auth', 'POST');
@@ -110,7 +110,7 @@ public function testConfiguredCallbackFailsClearlyForContractOnlyBroadcaster():
public function testChannelRegistrationReturnsTheProxy(): void
{
[$proxy] = $this->proxy(
- fn () => new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->instance())
+ fn () => new PoolProxyUserAuthenticationBroadcaster(Double::for(ContainerContract::class, override: true)->strict()->instance())
);
$this->assertSame($proxy, $proxy->channel('orders.{order}', fn (): bool => true));
diff --git a/tests/Broadcasting/BroadcasterTest.php b/tests/Broadcasting/BroadcasterTest.php
index d6fdba234f..86e06ef58c 100644
--- a/tests/Broadcasting/BroadcasterTest.php
+++ b/tests/Broadcasting/BroadcasterTest.php
@@ -72,7 +72,7 @@ public function testExtractingParametersWhileCheckingForUserAccess(): void
$this->assertSame([], $parameters);
// Test Explicit Binding...
- $binder = Double::for(BindingRegistrar::class);
+ $binder = Double::for(BindingRegistrar::class)->strict();
$binder->expects('getBindingCallback')->times(2)->with('model')->returns(function (): string {
return 'bound';
});
@@ -96,7 +96,7 @@ public function testCanUseChannelClasses(): void
public function testCallableChannelHandlersReceiveTheUserAndBoundModel(callable $handler): void
{
$user = new DummyUser;
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->expects('user')->with(Argument::none())->returns($user);
$this->broadcaster->channel('orders.{order}', $handler);
@@ -122,7 +122,7 @@ public static function callableChannelHandlers(): array
public function testModelRouteBinding(): void
{
- $binder = Double::for(BindingRegistrar::class);
+ $binder = Double::for(BindingRegistrar::class)->strict();
$routeModelCallback = RouteBinding::forModel($this->container, BroadcasterTestEloquentModelStub::class);
$binder->expects('getBindingCallback')->times(2)->with('model')->returns($routeModelCallback);
@@ -348,7 +348,7 @@ public function testUserAuthenticationWithoutResolve(): void
public function testChannelAuthorizerRewritesTheNameBeforeGuardLookupBindingAndInvocation(): void
{
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$user = new DummyUser;
$request->expects('user')->times(2)->with('members')->returns($user);
@@ -410,7 +410,7 @@ public function testChannelAuthorizerDeniesBeforeTheChannelCallbackRuns(): void
public function testChannelAuthorizerLeavesUnchangedNamesOnTheNativePath(): void
{
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$user = new DummyUser;
$request->expects('user')->with(Argument::none())->returns($user);
@@ -429,7 +429,7 @@ public function testChannelAuthorizerLeavesUnchangedNamesOnTheNativePath(): void
public function testChannelAuthorizerIsSingleOwner(): void
{
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->expects('user')->with(Argument::none())->returns(new DummyUser);
Broadcaster::authorizeChannelsUsing(static fn (Request $request, string $channel): ?string => null);
@@ -444,7 +444,7 @@ public function testChannelAuthorizerIsSingleOwner(): void
public function testPassingNullRemovesChannelAuthorizer(): void
{
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->expects('user')->with(Argument::none())->returns(new DummyUser);
Broadcaster::authorizeChannelsUsing(static fn (Request $request, string $channel): ?string => null);
@@ -457,7 +457,7 @@ public function testPassingNullRemovesChannelAuthorizer(): void
public function testBaseChannelResponsePathPreservesPublicOverrides(): void
{
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->expects('user')->with(Argument::none())->returns(new DummyUser);
$broadcaster = new PublicResponseOnlyBroadcaster($this->container);
@@ -528,7 +528,7 @@ public function testFlushStateClearsChannelsOptionsFormatterAndAuthorizer(): voi
$this->assertSame([], $this->broadcaster->retrieveChannelOptions('orders'));
$this->assertSame(['orders'], $this->broadcaster->formatOutgoingChannels(['orders']));
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->expects('user')->with(Argument::none())->returns(new DummyUser);
$this->broadcaster->channel('orders', static fn (): bool => true);
$this->assertTrue($this->broadcaster->verifyAccess($request->instance(), 'orders'));
diff --git a/tests/Broadcasting/InteractsWithBroadcastingTest.php b/tests/Broadcasting/InteractsWithBroadcastingTest.php
index c2b6a562ab..897a4c7007 100644
--- a/tests/Broadcasting/InteractsWithBroadcastingTest.php
+++ b/tests/Broadcasting/InteractsWithBroadcastingTest.php
@@ -108,8 +108,8 @@ public function testBroadcastWithIntegerBackedEnumUsesNormalizedConnection(): vo
$event->broadcastVia(InteractsWithBroadcastingTestConnectionIntEnum::Connection1);
$broadcastEvent = new BroadcastEvent($event);
- $manager = Double::for(BroadcastingFactory::class);
- $broadcaster = Double::for(Broadcaster::class);
+ $manager = Double::for(BroadcastingFactory::class)->strict();
+ $broadcaster = Double::for(Broadcaster::class)->strict();
$manager->expects('connection')->with('1')->returns($broadcaster);
$broadcaster->expects('broadcast');
diff --git a/tests/Broadcasting/LogBroadcasterTest.php b/tests/Broadcasting/LogBroadcasterTest.php
index f839ede0b7..706efb468c 100644
--- a/tests/Broadcasting/LogBroadcasterTest.php
+++ b/tests/Broadcasting/LogBroadcasterTest.php
@@ -26,7 +26,7 @@ public function testBroadcastUsesFormattedChannelNames(): void
),
);
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->expects('info')
->with(Argument::satisfies(
static fn (string $message): bool => str_contains(
@@ -46,7 +46,7 @@ public function testBroadcastThrowsWhenPayloadCannotBeEncoded(): void
{
$this->expectException(JsonException::class);
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->expects('info')->never();
(new LogBroadcaster($logger))->broadcast(
diff --git a/tests/Broadcasting/MercureBroadcasterTest.php b/tests/Broadcasting/MercureBroadcasterTest.php
index ed4b1568b8..9edb035c71 100644
--- a/tests/Broadcasting/MercureBroadcasterTest.php
+++ b/tests/Broadcasting/MercureBroadcasterTest.php
@@ -48,7 +48,7 @@ protected function setUp(): void
{
parent::setUp();
- $this->hub = Double::for(HubInterface::class);
+ $this->hub = Double::for(HubInterface::class)->strict();
$this->hub->allows('getPublicUrl')->returns('https://localhost/.well-known/mercure');
$this->hub->allows('getCookieName')->returns('__Secure-mercure_access_token');
$this->hub->allows('getFactory')->returns($this->tokenFactory());
@@ -87,7 +87,7 @@ public function testConstructingRegistersTheHubsCookieNameAsNeverEncrypted(): vo
public function testSettingAHubRegistersItsCookieNameAsNeverEncrypted(): void
{
- $hub = Double::for(HubInterface::class);
+ $hub = Double::for(HubInterface::class)->strict();
$hub->expects('getCookieName')->returns('custom_mercure_cookie');
$this->broadcaster->setHub($hub);
@@ -591,11 +591,7 @@ public function testBroadcastEncryptedUpdateRoundTrips(): void
$broadcaster = $this->encryptedBroadcaster();
$captured = null;
- $this->hub->expects('publish')->with(Argument::satisfies(function (Update $update) use (&$captured): bool {
- $captured = $update;
-
- return true;
- }));
+ $this->hub->expects('publish')->with(Argument::capture($captured));
$broadcaster->broadcast(['private-encrypted-room.1'], 'MessageSent', ['text' => 'hi', 'socket' => 'abcd.1234']);
@@ -615,11 +611,7 @@ public function testBroadcastEncryptedChannelsUseDistinctKeys(): void
$broadcaster = $this->encryptedBroadcaster();
$captured = null;
- $this->hub->expects('publish')->with(Argument::satisfies(function (Update $update) use (&$captured): bool {
- $captured = $update;
-
- return true;
- }));
+ $this->hub->expects('publish')->with(Argument::capture($captured));
$broadcaster->broadcast(['private-encrypted-a'], 'Tick');
@@ -745,7 +737,7 @@ public function testAuthAndBroadcastHonorACustomTopicPrefix(): void
*/
protected function broadcasterForHub(string $publicUrl, string $cookieName = '__Secure-mercure_access_token'): MercureBroadcaster
{
- $hub = Double::for(HubInterface::class);
+ $hub = Double::for(HubInterface::class)->strict();
$hub->allows('getPublicUrl')->returns($publicUrl);
$hub->allows('getCookieName')->returns($cookieName);
$hub->allows('getFactory')->returns($this->tokenFactory());
diff --git a/tests/Broadcasting/PendingBroadcastTest.php b/tests/Broadcasting/PendingBroadcastTest.php
index 367e469a23..da2e967808 100644
--- a/tests/Broadcasting/PendingBroadcastTest.php
+++ b/tests/Broadcasting/PendingBroadcastTest.php
@@ -35,7 +35,7 @@ class PendingBroadcastTest extends TestCase
public function testViaAcceptsStringBackedEnum(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch');
$event = new TestPendingBroadcastEvent;
@@ -49,7 +49,7 @@ public function testViaAcceptsStringBackedEnum(): void
public function testViaAcceptsUnitEnum(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch');
$event = new TestPendingBroadcastEvent;
@@ -62,7 +62,7 @@ public function testViaAcceptsUnitEnum(): void
public function testViaNormalizesIntegerBackedEnumImmediately(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch');
$event = new TestPendingBroadcastEvent;
@@ -75,7 +75,7 @@ public function testViaNormalizesIntegerBackedEnumImmediately(): void
public function testViaAcceptsNull(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch');
$event = new TestPendingBroadcastEvent;
@@ -88,7 +88,7 @@ public function testViaAcceptsNull(): void
public function testViaAcceptsString(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch');
$event = new TestPendingBroadcastEvent;
diff --git a/tests/Broadcasting/PusherBroadcasterTest.php b/tests/Broadcasting/PusherBroadcasterTest.php
index 372e5709d6..f4789b89c8 100644
--- a/tests/Broadcasting/PusherBroadcasterTest.php
+++ b/tests/Broadcasting/PusherBroadcasterTest.php
@@ -41,7 +41,7 @@ protected function setUp(): void
parent::setUp();
$this->container = new ApplicationContainer;
- $this->pusher = Double::for(Pusher::class);
+ $this->pusher = Double::for(Pusher::class)->strict();
$this->broadcaster = new PusherBroadcaster($this->container, $this->pusher);
}
@@ -151,10 +151,10 @@ public function testAuthUsesRewrittenChannelForConfiguredGuardAndOriginalNameFor
$wireChannel = 'presence-application.tenant.orders.5';
$calls = 0;
$boundOrder = null;
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthIdentifier')->returns(42);
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->allows('input')->with('channel_name')->returns($wireChannel);
$request->allows('input')->with('socket_id')->returns('abcd.1234');
$request->allows('input')->with('callback', false)->returns(false);
@@ -303,8 +303,8 @@ public function testJsonpCallbackReturnsJsonpWhenExplicitlyEnabled(): void
$container->singleton(
ResponseFactoryContract::class,
fn (): ResponseFactory => new ResponseFactory(
- Double::for(ViewFactory::class),
- Double::for(Redirector::class),
+ Double::for(ViewFactory::class)->strict(),
+ Double::for(Redirector::class)->strict(),
)
);
diff --git a/tests/Broadcasting/RedisBroadcasterTest.php b/tests/Broadcasting/RedisBroadcasterTest.php
index ebc2b01939..144bea518d 100644
--- a/tests/Broadcasting/RedisBroadcasterTest.php
+++ b/tests/Broadcasting/RedisBroadcasterTest.php
@@ -39,7 +39,7 @@ protected function setUp(): void
parent::setUp();
$this->container = new Container;
- $this->redis = Double::for(Redis::class);
+ $this->redis = Double::for(Redis::class)->strict();
$this->broadcaster = new RedisBroadcaster($this->container, $this->redis);
}
@@ -147,10 +147,10 @@ public function testAuthThrowAccessDeniedHttpExceptionWithPresenceChannelWhenReq
public function testAuthUsesRewrittenChannelForConfiguredGuardAndPresenceUser(): void
{
$broadcaster = new RedisBroadcaster($this->container, $this->redis, 'default', 'redis.');
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthIdentifier')->returns(42);
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->allows('input')
->with('channel_name')
->returns('redis.presence-application.tenant.orders.5');
@@ -255,7 +255,7 @@ public function testPresenceAuthenticationThrowsWhenUserDataCannotBeEncoded(): v
public function testBroadcastUsesPublishPerChannelOnCluster(): void
{
- $connection = Double::for(RedisBroadcasterConnection::class);
+ $connection = Double::for(RedisBroadcasterConnection::class)->strict();
$connection->expects('isCluster')->returns(true);
$connection->expects('publish')->with('test-channel-1', Argument::type('string'));
$connection->expects('publish')->with('test-channel-2', Argument::type('string'));
@@ -269,7 +269,7 @@ public function testBroadcastUsesPublishPerChannelOnCluster(): void
public function testClusterBroadcastWrapsRedisClusterException(): void
{
- $connection = Double::for(RedisBroadcasterConnection::class);
+ $connection = Double::for(RedisBroadcasterConnection::class)->strict();
$connection->expects('isCluster')->returns(true);
$connection->expects('publish')
->with('test-channel', Argument::type('string'))
@@ -286,7 +286,7 @@ public function testClusterBroadcastWrapsRedisClusterException(): void
public function testBroadcastUsesEvalOnNonCluster(): void
{
- $connection = Double::for(RedisBroadcasterConnection::class);
+ $connection = Double::for(RedisBroadcasterConnection::class)->strict();
$connection->expects('isCluster')->returns(false);
$connection->expects('eval');
$connection->expects('publish')->never();
@@ -306,7 +306,7 @@ public function testClusterBroadcastLeavesRedisPrefixToNativePublishAfterFormatt
),
);
- $connection = Double::for(RedisBroadcasterConnection::class);
+ $connection = Double::for(RedisBroadcasterConnection::class)->strict();
$connection->expects('isCluster')->returns(true);
$connection->expects('publish')
->with('application.orders', Argument::type('string'));
@@ -329,7 +329,7 @@ public function testLuaBroadcastAddsRedisPrefixAfterFormattingChannels(): void
),
);
- $connection = Double::for(RedisBroadcasterConnection::class);
+ $connection = Double::for(RedisBroadcasterConnection::class)->strict();
$connection->expects('isCluster')->returns(false);
$connection->expects('eval')
->with(
@@ -353,7 +353,7 @@ public function testBroadcastThrowsWhenPayloadCannotBeEncoded(): void
$this->expectException(JsonException::class);
$this->redis->expects('connection')->returns(
- Double::for(RedisBroadcasterConnection::class)
+ Double::for(RedisBroadcasterConnection::class)->strict()
);
$this->broadcaster->broadcast(
@@ -365,7 +365,7 @@ public function testBroadcastThrowsWhenPayloadCannotBeEncoded(): void
public function testBroadcastPayloadDoesNotDuplicateSocketInData(): void
{
- $connection = Double::for(RedisBroadcasterConnection::class);
+ $connection = Double::for(RedisBroadcasterConnection::class)->strict();
$connection->allows('isCluster')->returns(false);
$connection->expects('eval')->with(Argument::all(function (string $script, int $numberOfKeys, string $payload): bool {
$decoded = json_decode($payload, true);
diff --git a/tests/Bus/BusBatchTest.php b/tests/Bus/BusBatchTest.php
index 23afbe8f49..f410c10990 100644
--- a/tests/Bus/BusBatchTest.php
+++ b/tests/Bus/BusBatchTest.php
@@ -9,6 +9,7 @@
use Hypervel\Bus\Batchable;
use Hypervel\Bus\BatchFactory;
use Hypervel\Bus\BatchRepository;
+use Hypervel\Bus\ChainedBatch;
use Hypervel\Bus\DatabaseBatchRepository;
use Hypervel\Bus\Events\BatchCanceled;
use Hypervel\Bus\Events\BatchFinished;
@@ -119,7 +120,7 @@ public function testBatchRepositoryUsesDefaultDatabaseConnectionWhenBatchingData
public function testBatchRepositoryAppliesAZeroBeforeCursor(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$batch = $this->createTestBatch($queue);
$repository = new DatabaseBatchRepository(
@@ -134,7 +135,7 @@ public function testBatchRepositoryAppliesAZeroBeforeCursor(): void
public function testJobsCanBeAddedToTheBatch(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$batch = $this->createTestBatch($queue);
@@ -149,7 +150,7 @@ public function testJobsCanBeAddedToTheBatch(): void
$thirdJob = function (): void {
};
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with('test-connection')
->returns($connection);
@@ -279,12 +280,12 @@ public function testProcessedJobsCanBeCalculated(): void
public function testProgressContinuesOnlyAfterOrdinaryCallbackFailures(bool $canceled): void
{
$failure = new RuntimeException('Progress failed.', previous: $canceled ? new CanceledException : null);
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->times($canceled ? 0 : 1)->with(Argument::same($failure), []);
$this->app->instance(ExceptionHandler::class, $handler);
- $repository = Double::for(BatchRepository::class);
+ $repository = Double::for(BatchRepository::class)->strict();
$continued = false;
- $batch = new Batch(Double::for(Factory::class), $repository, 'batch', 'batch', 2, 2, 0, [], [
+ $batch = new Batch(Double::for(Factory::class)->strict(), $repository, 'batch', 'batch', 2, 2, 0, [], [
'progress' => [
static fn () => throw $failure,
static function () use (&$continued): void { $continued = true; },
@@ -306,7 +307,7 @@ static function () use (&$continued): void { $continued = true; },
public function testSuccessfulJobsCanBeRecorded(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$batch = $this->createTestBatch($queue);
@@ -318,7 +319,7 @@ public function testSuccessfulJobsCanBeRecorded(): void
use Batchable;
};
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with('test-connection')
->returns($connection);
@@ -428,7 +429,7 @@ public function testBatchStartedEventIsDispatchedWhenFirstJobFails(): void
public function testFailedJobsCanBeRecordedWhileNotAllowingFailures(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$batch = $this->createTestBatch($queue, $allowFailures = false);
@@ -440,7 +441,7 @@ public function testFailedJobsCanBeRecordedWhileNotAllowingFailures(): void
use Batchable;
};
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with('test-connection')
->returns($connection);
@@ -469,7 +470,7 @@ public function testFailedJobsCanBeRecordedWhileNotAllowingFailures(): void
public function testFailedJobsCanBeRecordedWhileAllowingFailures(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$batch = $this->createTestBatch($queue, $allowFailures = true);
@@ -481,7 +482,7 @@ public function testFailedJobsCanBeRecordedWhileAllowingFailures(): void
use Batchable;
};
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with('test-connection')
->returns($connection);
@@ -528,7 +529,7 @@ public function testPendingBatchFiltersOutFalsyJobs(): void
public function testFailureCallbacksExecuteCorrectly(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$repository = new DatabaseBatchRepository(
new BatchFactory($queue),
@@ -561,7 +562,7 @@ function (Batch $batch, ?Throwable $e): void {
use Batchable;
};
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with('test-connection')
->returns($connection);
@@ -635,14 +636,14 @@ public function testBatchCanBeDeleted(): void
public function testDeletedBatchIgnoresLateJobResultsAndCallbacks(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$batch = $this->createTestBatch($queue, $allowFailures = true);
$job = new class {
use Batchable;
};
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with('test-connection')
->returns($connection);
@@ -704,7 +705,7 @@ public function testBatchStateCanBeInspected(): void
public function testChainCanBeAddedToBatch(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$batch = $this->createTestBatch($queue);
@@ -714,7 +715,7 @@ public function testChainCanBeAddedToBatch(): void
$thirdJob = new ThirdTestJob;
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with('test-connection')
->returns($connection);
@@ -741,7 +742,7 @@ public function testChainCanBeAddedToBatch(): void
public function testChainedJobsInBatchPreserveTheirQueueWhenBatchHasNoQueue(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$repository = new DatabaseBatchRepository(
new BatchFactory($queue),
@@ -757,7 +758,7 @@ public function testChainedJobsInBatchPreserveTheirQueueWhenBatchHasNoQueue(): v
$firstJob = (new ChainHeadJob)->onQueue('custom-queue');
$secondJob = (new SecondTestJob)->onQueue('custom-queue');
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with('test-connection')
->returns($connection);
@@ -774,7 +775,7 @@ public function testChainedJobsInBatchPreserveTheirQueueWhenBatchHasNoQueue(): v
public function testChainedJobsPreserveTheirRoutesWhenTheBatchHasNone(): void
{
- $queue = Double::for(Factory::class);
+ $queue = Double::for(Factory::class)->strict();
$repository = new DatabaseBatchRepository(
new BatchFactory($queue),
@@ -791,7 +792,7 @@ public function testChainedJobsPreserveTheirRoutesWhenTheBatchHasNone(): void
->onConnection('custom-connection')
->onQueue('custom-queue');
- $connection = Double::for(QueueContract::class);
+ $connection = Double::for(QueueContract::class)->strict();
$queue->expects('connection')
->with(null)
->returns($connection);
@@ -819,7 +820,7 @@ function (): void {
},
])->dispatch();
- $this->assertTrue(true);
+ Queue::assertPushedWithChain(ChainedBatch::class, [ChainedBatch::class, CallQueuedClosure::class]);
}
public function testOptionsSerializationOnPostgres(): void
@@ -827,12 +828,15 @@ public function testOptionsSerializationOnPostgres(): void
$pendingBatch = (new PendingBatch($this->app, Collection::make()))
->onQueue('test-queue');
- $connection = Double::for(PostgresConnection::class);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $connection = Double::for(PostgresConnection::class)->strict();
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$connection->expects('table')->times(2)->returns($builder);
+ $builder->expects('insert')->with(Argument::satisfies(static function (array $values) use ($pendingBatch): bool {
+ return unserialize(base64_decode($values['options'])) === $pendingBatch->options;
+ }))->returns(true);
$builder->expects('useWritePdo')->returns($builder);
$builder->expects('where')->returns($builder);
$builder->expects('first')->returns((object) [
@@ -849,28 +853,23 @@ public function testOptionsSerializationOnPostgres(): void
]);
$repository = new DatabaseBatchRepository(
- new BatchFactory(Double::for(Factory::class)),
+ new BatchFactory(Double::for(Factory::class)->strict()),
$resolver,
'job_batches'
);
$repository->store($pendingBatch);
-
- $builder->received('insert')
- ->with(Argument::satisfies(function (array $argument) use ($pendingBatch): bool {
- return unserialize(base64_decode($argument['options'])) === $pendingBatch->options;
- }));
}
#[TestWith([false], 'ordinary restoration failure')]
#[TestWith([true], 'wrapped cancellation')]
public function testOptionsRestorationFallbackDoesNotSwallowCancellation(bool $canceled): void
{
- $factory = Double::for(BatchFactory::class);
- $connection = Double::for(PostgresConnection::class);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $factory = Double::for(BatchFactory::class)->strict();
+ $connection = Double::for(PostgresConnection::class)->strict();
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$connection->expects('table')->returns($builder);
$builder->expects('useWritePdo')->returns($builder);
$builder->expects('where')->returns($builder);
@@ -886,7 +885,7 @@ public function testOptionsRestorationFallbackDoesNotSwallowCancellation(bool $c
} else {
$factory->expects('make')
->with(Argument::same($repository), 'batch', '', 0, 0, 0, [], [], Argument::remaining())
- ->returns(Double::for(Batch::class));
+ ->returns(Double::for(Batch::class)->strict());
}
$caught = null;
@@ -907,13 +906,13 @@ public function testOptionsRestorationFallbackDoesNotSwallowCancellation(bool $c
#[DataProvider('serializedOptions')]
public function testOptionsUnserializeOnPostgres(string $serialize, array $options): void
{
- $factory = Double::for(BatchFactory::class);
+ $factory = Double::for(BatchFactory::class)->strict();
- $connection = Double::for(PostgresConnection::class);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $connection = Double::for(PostgresConnection::class)->strict();
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$connection->expects('table')->returns($builder);
$builder->expects('useWritePdo')->returns($builder);
$builder->expects('where')->returns($builder);
@@ -934,8 +933,8 @@ public function testOptionsUnserializeOnPostgres(string $serialize, array $optio
$batch = new DatabaseBatchRepository($factory, $resolver, 'job_batches');
$factory->expects('make')
- ->with($batch, '', '', 0, 0, 0, [], $options, Argument::remaining())
- ->returns(Double::for(Batch::class));
+ ->with(Argument::same($batch), '', '', 0, 0, 0, [], $options, Argument::remaining())
+ ->returns(Double::for(Batch::class)->strict());
$batch->find('1');
}
diff --git a/tests/Bus/BusBatchableTest.php b/tests/Bus/BusBatchableTest.php
index 5bb9bc853a..70b9fa9c1b 100644
--- a/tests/Bus/BusBatchableTest.php
+++ b/tests/Bus/BusBatchableTest.php
@@ -29,8 +29,8 @@ public function testBatchMayBeRetrieved(): void
Container::setInstance($container = new Container);
- $repository = Double::for(BatchRepository::class);
- $batch = Double::for(Batch::class);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $batch = Double::for(Batch::class)->strict();
$repository->expects('find')->with('test-batch-id')->returns($batch);
$container->instance(BatchRepository::class, $repository);
@@ -62,8 +62,8 @@ public function testZeroBatchIdMayBeRetrievedAndFaked(): void
Container::setInstance($container = new Container);
- $repository = Double::for(BatchRepository::class);
- $batch = Double::for(Batch::class);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $batch = Double::for(Batch::class)->strict();
$repository->expects('find')->with('0')->returns($batch);
$container->instance(BatchRepository::class, $repository);
diff --git a/tests/Bus/BusDebounceLockTest.php b/tests/Bus/BusDebounceLockTest.php
index 5a058b0be8..939a1362ef 100644
--- a/tests/Bus/BusDebounceLockTest.php
+++ b/tests/Bus/BusDebounceLockTest.php
@@ -54,7 +54,7 @@ public function testConcurrentFirstDispatchesDoNotOverwriteTheMaxWaitAnchor(): v
public function testReleaseProbeFailureDoesNotRemoveEitherDebounceRecord(): void
{
$failure = new RuntimeException('Owner probe failed.');
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('get')->with('debounce-key')->throws($failure);
$cache->expects('forget')->never();
@@ -74,7 +74,7 @@ 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 = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$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);
@@ -91,7 +91,7 @@ public function testAcquisitionFailureRemainsPrimaryWhenCleanupProbeFails(bool $
public function testReleasePreservesCancellationFromSecondCleanup(): void
{
$failure = new RuntimeException('Cache cleanup failed.', previous: new CanceledException);
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('forget')->with('key')->throws(new RuntimeException('First deletion failed.'));
$cache->expects('forget')->with('key:first_dispatched_at')->throws($failure);
$caught = null;
diff --git a/tests/Bus/BusDispatcherTest.php b/tests/Bus/BusDispatcherTest.php
index 678192a6c6..8492e54cd9 100644
--- a/tests/Bus/BusDispatcherTest.php
+++ b/tests/Bus/BusDispatcherTest.php
@@ -58,7 +58,7 @@ public function testCommandsThatShouldQueueIsQueuedUsingCustomQueueAndDelay(): v
$container->instance('queue.routes', new QueueRoutes);
Container::setInstance($container);
$dispatcher = new Dispatcher($container, function (): Queue {
- $mock = Double::for(Queue::class);
+ $mock = Double::for(Queue::class)->strict();
$mock->expects('later')->with(10, Argument::type(BusDispatcherTestSpecificQueueAndDelayCommand::class), '', 'foo');
return $mock;
@@ -76,7 +76,7 @@ public function testCommandsAreQueuedUsingAttributesInheritedFromParentClass():
$dispatcher = new Dispatcher($container, function (?string $connection) use (&$usedConnection): Queue {
$usedConnection = $connection;
- $mock = Double::for(Queue::class);
+ $mock = Double::for(Queue::class)->strict();
$mock->expects('later')->with(10, Argument::type(BusDispatcherTestQueueableChildCommand::class), '', 'foo');
return $mock;
@@ -90,12 +90,12 @@ public function testCommandsAreQueuedUsingAttributesInheritedFromParentClass():
public function testCommandsThatShouldQueueIsQueuedUsingQueueAndDelayAttributes(): void
{
$container = new Container;
- $queueRoutes = Double::for(QueueRoutes::class);
+ $queueRoutes = Double::for(QueueRoutes::class)->strict();
$queueRoutes->expects('getConnection')->returns(null);
$container->instance('queue.routes', $queueRoutes);
Container::setInstance($container);
$dispatcher = new Dispatcher($container, function (): Queue {
- $mock = Double::for(Queue::class);
+ $mock = Double::for(Queue::class)->strict();
$mock->expects('later')->with(10, Argument::type(BusDispatcherTestSpecificQueueAndDelayAttributesCommand::class), '', 'foo');
return $mock;
@@ -107,12 +107,12 @@ public function testCommandsThatShouldQueueIsQueuedUsingQueueAndDelayAttributes(
public function testCommandDelayPropertyOverridesDelayAttribute(): void
{
$container = new Container;
- $queueRoutes = Double::for(QueueRoutes::class);
+ $queueRoutes = Double::for(QueueRoutes::class)->strict();
$queueRoutes->expects('getConnection')->returns(null);
$container->instance('queue.routes', $queueRoutes);
Container::setInstance($container);
$dispatcher = new Dispatcher($container, function (): Queue {
- $mock = Double::for(Queue::class);
+ $mock = Double::for(Queue::class)->strict();
$mock->expects('later')->with(60, Argument::type(BusDispatcherTestSpecificQueueAndDelayAttributeWithPropertyCommand::class), '', 'foo');
return $mock;
@@ -167,7 +167,7 @@ public function testExplicitConnectionWinsOverForwardedQueue(): void
$queueRoutes->forward('reports', 'processing', 'cloud');
$container->instance('queue.routes', $queueRoutes);
- $mock = Double::for(Queue::class);
+ $mock = Double::for(Queue::class)->strict();
$mock->expects('push')->with(Argument::type(BusDispatcherQueueable::class), '', 'reports');
$usedConnection = false;
@@ -255,11 +255,11 @@ public function testDispatchBulk(): void
$container->instance('queue.routes', new QueueRoutes);
Container::setInstance($container);
- $defaultQueue = Double::for(Queue::class);
+ $defaultQueue = Double::for(Queue::class)->strict();
$defaultQueue->expects('bulk')->with(Argument::satisfies(fn (array $jobs): bool => count($jobs) === 2), '', null);
$defaultQueue->expects('bulk')->with(Argument::satisfies(fn (array $jobs): bool => count($jobs) === 1), '', 'high');
- $priorityQueue = Double::for(Queue::class);
+ $priorityQueue = Double::for(Queue::class)->strict();
$priorityQueue->expects('bulk')->with(Argument::satisfies(fn (array $jobs): bool => count($jobs) === 1), '', 'high');
$dispatcher = new Dispatcher(
@@ -285,10 +285,10 @@ public function testDispatchBulkKeepsColonBearingRoutesSeparate(): void
$firstJob = (new BusDispatcherQueueable)->onConnection('a:b')->onQueue('c');
$secondJob = (new BusDispatcherQueueable)->onConnection('a')->onQueue('b:c');
- $firstQueue = Double::for(Queue::class);
+ $firstQueue = Double::for(Queue::class)->strict();
$firstQueue->expects('bulk')->with(Argument::same([$firstJob]), '', 'c');
- $secondQueue = Double::for(Queue::class);
+ $secondQueue = Double::for(Queue::class)->strict();
$secondQueue->expects('bulk')->with(Argument::same([$secondJob]), '', 'b:c');
$dispatcher = new Dispatcher(
diff --git a/tests/Bus/BusPendingBatchTest.php b/tests/Bus/BusPendingBatchTest.php
index 87b9fa3146..86d6fbdc3d 100644
--- a/tests/Bus/BusPendingBatchTest.php
+++ b/tests/Bus/BusPendingBatchTest.php
@@ -48,8 +48,8 @@ public function testBeforeCallbackCancellationStopsBatchDispatch(string $scenari
$cancellation = new CanceledException;
$failure = $scenario === 'direct' ? $cancellation : new RuntimeException('Before cleanup failed.', previous: $cancellation);
$container = new Container;
- $repository = Double::for(BatchRepository::class);
- $batch = Double::for(Batch::class);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $batch = Double::for(Batch::class)->strict();
$batch->id = 'batch';
$batch->expects('add')->never();
$repository->expects('store')->returns($batch);
@@ -58,7 +58,7 @@ public function testBeforeCallbackCancellationStopsBatchDispatch(string $scenari
$deleteThrows ? $deletion->throws($deletionFailure) : $deletion->returns(null);
$container->instance(BatchRepository::class, $repository);
if ($reporting) {
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->throws($failure);
$container->instance(ExceptionHandler::class, $handler);
Container::setInstance($container);
@@ -86,8 +86,8 @@ public function testDeletionFailureRetainsDispatchCancellation(bool $stored): vo
$cancellation = new CanceledException;
$cleanup = new RuntimeException('Batch deletion failed.');
$container = new Container;
- $repository = Double::for(BatchRepository::class);
- $batch = Double::for(Batch::class);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $batch = Double::for(Batch::class)->strict();
$batch->id = 'batch';
$batch->expects('add')->throws($cancellation);
$container->instance(BatchRepository::class, $repository);
@@ -150,7 +150,7 @@ public function testChainedBatchPreservesZeroConnectionAndQueueIdentifiers(): vo
->onConnection(PendingBatchIntegerIdentifier::Zero)
->onQueue(PendingBatchIntegerIdentifier::Zero);
- $dispatcher = Double::for(QueueingDispatcher::class);
+ $dispatcher = Double::for(QueueingDispatcher::class)->strict();
$dispatcher->expects('batch')
->resolves(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs));
$container->instance(BusDispatcher::class, $dispatcher);
@@ -175,7 +175,7 @@ public function testDirectlyRoutedChainedBatchPreservesZeroConnectionAndQueueIde
->onConnection('0')
->onQueue('0');
- $dispatcher = Double::for(QueueingDispatcher::class);
+ $dispatcher = Double::for(QueueingDispatcher::class)->strict();
$dispatcher->expects('batch')
->resolves(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs));
$container->instance(BusDispatcher::class, $dispatcher);
@@ -199,7 +199,7 @@ public function testChainedBatchPreservesSourceEmptyConnectionAndQueueOptions():
->onConnection('')
->onQueue('');
- $dispatcher = Double::for(QueueingDispatcher::class);
+ $dispatcher = Double::for(QueueingDispatcher::class)->strict();
$dispatcher->expects('batch')
->resolves(fn (Collection $jobs): PendingBatch => new PendingBatch($container, $jobs));
$container->instance(BusDispatcher::class, $dispatcher);
@@ -226,13 +226,8 @@ public function testChainedBatchRemainderInheritsEmptyIdentifiersAndPreservesZer
$chainedBatch->chainConnection = 'chain-connection';
$chainedBatch->chainQueue = 'chain-queue';
- $dispatcher = Double::for(BusDispatcher::class);
- $dispatcher->expects('dispatch')->with(Argument::satisfies(function (ChainedBatchQueueableJob $job) use ($expectedConnection, $expectedQueue): bool {
- $this->assertSame($expectedConnection, $job->connection);
- $this->assertSame($expectedQueue, $job->queue);
-
- return true;
- }));
+ $dispatcher = Double::for(BusDispatcher::class)->strict();
+ $dispatcher->expects('dispatch')->with(Argument::capture($job));
$container->instance(BusDispatcher::class, $dispatcher);
$pendingBatch = $chainedBatch->attachRemainder(
@@ -242,9 +237,13 @@ public function testChainedBatchRemainderInheritsEmptyIdentifiersAndPreservesZer
$callbacks = $pendingBatch->finallyCallbacks();
$this->assertCount(1, $callbacks);
- $batch = Double::for(Batch::class);
+ $batch = Double::for(Batch::class)->strict();
$batch->expects('cancelled')->returns(false);
$callbacks[0]($batch);
+
+ $this->assertInstanceOf(ChainedBatchQueueableJob::class, $job);
+ $this->assertSame($expectedConnection, $job->connection);
+ $this->assertSame($expectedQueue, $job->queue);
}
}
@@ -259,23 +258,22 @@ public function testChainedBatchRemainderKeepsJobAttributesOverChainDefaults():
$chainedBatch->chainConnection = 'chain-connection';
$chainedBatch->chainQueue = 'chain-queue';
- $dispatcher = Double::for(BusDispatcher::class);
- $dispatcher->expects('dispatch')->with(Argument::satisfies(function (AttributedChainedBatchQueueableJob $job): bool {
- $this->assertNull($job->connection);
- $this->assertNull($job->queue);
- $this->assertSame('chain-connection', $job->chainConnection);
- $this->assertSame('chain-queue', $job->chainQueue);
-
- return true;
- }));
+ $dispatcher = Double::for(BusDispatcher::class)->strict();
+ $dispatcher->expects('dispatch')->with(Argument::capture($job));
$container->instance(BusDispatcher::class, $dispatcher);
$callbacks = $chainedBatch->attachRemainder(new PendingBatch($container, new Collection([$sourceJob])))
->finallyCallbacks();
- $batch = Double::for(Batch::class);
+ $batch = Double::for(Batch::class)->strict();
$batch->expects('cancelled')->returns(false);
$callbacks[0]($batch);
+
+ $this->assertInstanceOf(AttributedChainedBatchQueueableJob::class, $job);
+ $this->assertNull($job->connection);
+ $this->assertNull($job->queue);
+ $this->assertSame('chain-connection', $job->chainConnection);
+ $this->assertSame('chain-queue', $job->chainQueue);
}
public function testPendingBatchMayBeConfiguredAndDispatched(): void
@@ -306,10 +304,10 @@ public function testPendingBatchMayBeConfiguredAndDispatched(): void
$this->assertArrayHasKey('extra-option', $pendingBatch->options);
$this->assertSame(123, $pendingBatch->options['extra-option']);
- $repository = Double::for(BatchRepository::class);
- $storedBatch = Double::for(Batch::class);
- $repository->expects('store')->with($pendingBatch)->returns($storedBatch);
- $batch = Double::for(Batch::class);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $storedBatch = Double::for(Batch::class)->strict();
+ $repository->expects('store')->with(Argument::same($pendingBatch))->returns($storedBatch);
+ $batch = Double::for(Batch::class)->strict();
$storedBatch->expects('add')->with(Argument::type(Collection::class))->returns($batch);
$container->instance(BatchRepository::class, $repository);
@@ -323,7 +321,7 @@ public function testBatchDispatchedEventIsSkippedWithoutListeners(): void
{
$container = new Container;
- $eventDispatcher = Double::for(Dispatcher::class);
+ $eventDispatcher = Double::for(Dispatcher::class)->strict();
$eventDispatcher->expects('hasListeners')->with(BatchDispatched::class)->returns(false);
$eventDispatcher->expects('dispatch')->never();
$container->instance(Dispatcher::class, $eventDispatcher);
@@ -334,9 +332,9 @@ public function testBatchDispatchedEventIsSkippedWithoutListeners(): void
$pendingBatch = new PendingBatch($container, new Collection([$job]));
- $repository = Double::for(BatchRepository::class);
- $batch = Double::for(Batch::class);
- $repository->expects('store')->with($pendingBatch)->returns($batch);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $batch = Double::for(Batch::class)->strict();
+ $repository->expects('store')->with(Argument::same($pendingBatch))->returns($batch);
$batch->expects('add')->with(Argument::type(Collection::class))->returns($batch);
$container->instance(BatchRepository::class, $repository);
@@ -347,7 +345,7 @@ public function testBatchDispatchedEventIsDispatchedAfterResponse(): void
{
$container = new Container;
- $eventDispatcher = Double::for(Dispatcher::class);
+ $eventDispatcher = Double::for(Dispatcher::class)->strict();
$eventDispatcher->expects('hasListeners')->with(BatchDispatched::class)->returns(true);
$eventDispatcher->expects('dispatch')->with(Argument::type(BatchDispatched::class));
$container->instance(Dispatcher::class, $eventDispatcher);
@@ -358,9 +356,9 @@ public function testBatchDispatchedEventIsDispatchedAfterResponse(): void
$pendingBatch = new PendingBatch($container, new Collection([$job]));
- $repository = Double::for(BatchRepository::class);
- $batch = Double::for(Batch::class);
- $repository->expects('store')->with($pendingBatch)->returns($batch);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $batch = Double::for(Batch::class)->strict();
+ $repository->expects('store')->with(Argument::same($pendingBatch))->returns($batch);
$batch->expects('add')->with(Argument::type(Collection::class))->returns($batch);
$container->instance(BatchRepository::class, $repository);
@@ -379,10 +377,10 @@ public function testBatchIsDeletedFromStorageIfExceptionThrownDuringBatching():
$pendingBatch = new PendingBatch($container, new Collection([$job]));
- $repository = Double::for(BatchRepository::class);
+ $repository = Double::for(BatchRepository::class)->strict();
- $batch = Double::for(Batch::class);
- $repository->expects('store')->with($pendingBatch)->returns($batch);
+ $batch = Double::for(Batch::class)->strict();
+ $repository->expects('store')->with(Argument::same($pendingBatch))->returns($batch);
$batch->id = 'test-id';
@@ -410,10 +408,10 @@ public function testBatchIsDispatchedWhenDispatchifIsTrue(): void
$pendingBatch = new PendingBatch($container, new Collection([$job]));
- $repository = Double::for(BatchRepository::class);
- $storedBatch = Double::for(Batch::class);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $storedBatch = Double::for(Batch::class)->strict();
$repository->expects('store')->returns($storedBatch);
- $batch = Double::for(Batch::class);
+ $batch = Double::for(Batch::class)->strict();
$storedBatch->expects('add')->returns($batch);
$container->instance(BatchRepository::class, $repository);
@@ -438,7 +436,7 @@ public function testBatchIsNotDispatchedWhenDispatchifIsFalse(): void
$pendingBatch = new PendingBatch($container, new Collection([$job]));
- $repository = Double::for(BatchRepository::class);
+ $repository = Double::for(BatchRepository::class)->strict();
$container->instance(BatchRepository::class, $repository);
$result = $pendingBatch->dispatchIf(false);
@@ -462,10 +460,10 @@ public function testBatchIsDispatchedWhenDispatchunlessIsFalse(): void
$pendingBatch = new PendingBatch($container, new Collection([$job]));
- $repository = Double::for(BatchRepository::class);
- $storedBatch = Double::for(Batch::class);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $storedBatch = Double::for(Batch::class)->strict();
$repository->expects('store')->returns($storedBatch);
- $batch = Double::for(Batch::class);
+ $batch = Double::for(Batch::class)->strict();
$storedBatch->expects('add')->returns($batch);
$container->instance(BatchRepository::class, $repository);
@@ -490,7 +488,7 @@ public function testBatchIsNotDispatchedWhenDispatchunlessIsTrue(): void
$pendingBatch = new PendingBatch($container, new Collection([$job]));
- $repository = Double::for(BatchRepository::class);
+ $repository = Double::for(BatchRepository::class)->strict();
$container->instance(BatchRepository::class, $repository);
$result = $pendingBatch->dispatchUnless(true);
@@ -520,10 +518,10 @@ public function testBatchBeforeEventIsCalled(): void
$beforeCalled = true;
})->onConnection('test-connection')->onQueue('test-queue');
- $repository = Double::for(BatchRepository::class);
- $storedBatch = Double::for(Batch::class);
- $repository->expects('store')->with($pendingBatch)->returns($storedBatch);
- $batch = Double::for(Batch::class);
+ $repository = Double::for(BatchRepository::class)->strict();
+ $storedBatch = Double::for(Batch::class)->strict();
+ $repository->expects('store')->with(Argument::same($pendingBatch))->returns($storedBatch);
+ $batch = Double::for(Batch::class)->strict();
$storedBatch->expects('add')->with(Argument::type(Collection::class))->returns($batch);
$container->instance(BatchRepository::class, $repository);
diff --git a/tests/Bus/BusPendingDispatchTest.php b/tests/Bus/BusPendingDispatchTest.php
index d24bfb5654..634fa57d0e 100644
--- a/tests/Bus/BusPendingDispatchTest.php
+++ b/tests/Bus/BusPendingDispatchTest.php
@@ -184,7 +184,7 @@ public function testPrepareForDispatchCanAbortDispatchBeforeDebounceCacheIsResol
{
Container::setInstance($container = new Container);
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->never();
$dispatcher->expects('dispatchAfterResponse')->never();
$container->instance(Dispatcher::class, $dispatcher);
@@ -200,7 +200,7 @@ public function testPrepareForDispatchCanAbortDispatchBeforeUniqueLockCacheIsRes
{
Container::setInstance($container = new Container);
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->never();
$dispatcher->expects('dispatchAfterResponse')->never();
$container->instance(Dispatcher::class, $dispatcher);
@@ -213,7 +213,7 @@ public function testPrepareForDispatchAllowsDispatch(): void
{
Container::setInstance($container = new Container);
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->with(Argument::type(PreparingPendingDispatchJob::class));
$dispatcher->expects('dispatchAfterResponse')->never();
$container->instance(Dispatcher::class, $dispatcher);
@@ -233,7 +233,7 @@ public function testUniqueMetadataReachesAfterResponseDispatcherBeforeUnclaimedO
$deferredJob = null;
$metadata = null;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->never();
$dispatcher->expects('dispatchAfterResponse')
->with(Argument::same($job))
diff --git a/tests/Bus/DispatchLockContextTest.php b/tests/Bus/DispatchLockContextTest.php
index 3e974c1951..e9402b0fa8 100644
--- a/tests/Bus/DispatchLockContextTest.php
+++ b/tests/Bus/DispatchLockContextTest.php
@@ -41,11 +41,11 @@ class DispatchLockContextTest extends TestCase
public function testReleaseAttemptsBothLocksAndPreservesCancellationFromDebounceCleanup(): void
{
$failure = new RuntimeException('Debounce cleanup failed.', previous: new CanceledException);
- $unique = Double::for(Cache::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $unique = Double::for(Cache::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$unique->expects('lock')->with('unique')->returns($lock);
$lock->expects('forceRelease')->throws(new RuntimeException('Unique release failed.'));
- $debounce = Double::for(Cache::class);
+ $debounce = Double::for(Cache::class)->strict();
$debounce->expects('get')->with('debounce')->returns('owner');
$debounce->expects('forget')->with('debounce')->throws($failure);
$debounce->expects('forget')->with('debounce:first_dispatched_at')->returns(true);
@@ -204,12 +204,12 @@ public function testStaleDispatchReleaseCannotRemoveNewerOwnersLock(): void
public function testMetadataSurvivesUntilAfterCommitPayloadCreation(string $queueClass, bool $delayed): void
{
$container = new Container;
- $container->instance(Cache::class, Double::for(Cache::class));
+ $container->instance(Cache::class, Double::for(Cache::class)->strict());
$container->instance(ContainerContract::class, $container);
$container->instance(EventDispatcher::class, new EventsDispatcher($container));
Container::setInstance($container);
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('addCallback')
->resolves(fn (callable $callback) => $callback());
diff --git a/tests/Bus/OutboxOptionsTest.php b/tests/Bus/OutboxOptionsTest.php
index be3c9f4093..2acfd94f52 100644
--- a/tests/Bus/OutboxOptionsTest.php
+++ b/tests/Bus/OutboxOptionsTest.php
@@ -47,7 +47,7 @@ public function testUnusedOutboxPropertiesAreNotSerialized(): void
public function testPendingDispatchForwardsOutboxOptions(): void
{
$job = new OutboxQueueableJob;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
$dispatcher->expects('dispatch')->with(Argument::same($job))->returns(null);
diff --git a/tests/Bus/QueueableTest.php b/tests/Bus/QueueableTest.php
index cf8f2d32a9..759a03f9f5 100644
--- a/tests/Bus/QueueableTest.php
+++ b/tests/Bus/QueueableTest.php
@@ -161,16 +161,15 @@ public function testDispatchNextJobPreservesExplicitZeroIdentifiers(): void
$job->chainConnection = 'default-connection';
$job->chainQueue = 'default-queue';
- $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);
-
- return true;
- }));
+ $dispatcher = Double::for(Dispatcher::class)->strict();
+ $dispatcher->expects('dispatch')->with(Argument::capture($next));
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
$job->dispatchNextJobInChain();
+
+ $this->assertInstanceOf(FakeJob::class, $next);
+ $this->assertSame('0', $next->connection);
+ $this->assertSame('0', $next->queue);
}
public function testDispatchNextJobInheritsChainIdentifiersForEmptyStrings(): void
@@ -180,16 +179,15 @@ public function testDispatchNextJobInheritsChainIdentifiersForEmptyStrings(): vo
$job->chainConnection = 'default-connection';
$job->chainQueue = 'default-queue';
- $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);
-
- return true;
- }));
+ $dispatcher = Double::for(Dispatcher::class)->strict();
+ $dispatcher->expects('dispatch')->with(Argument::capture($next));
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
$job->dispatchNextJobInChain();
+
+ $this->assertInstanceOf(FakeJob::class, $next);
+ $this->assertSame('default-connection', $next->connection);
+ $this->assertSame('default-queue', $next->queue);
}
public function testDispatchNextJobKeepsItsAttributesOverChainDefaults(): void
@@ -199,18 +197,17 @@ public function testDispatchNextJobKeepsItsAttributesOverChainDefaults(): void
$job->chainConnection = 'default-connection';
$job->chainQueue = 'default-queue';
- $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);
- $this->assertSame('default-queue', $next->chainQueue);
-
- return true;
- }));
+ $dispatcher = Double::for(Dispatcher::class)->strict();
+ $dispatcher->expects('dispatch')->with(Argument::capture($next));
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
$job->dispatchNextJobInChain();
+
+ $this->assertInstanceOf(AttributedFakeJob::class, $next);
+ $this->assertNull($next->connection);
+ $this->assertNull($next->queue);
+ $this->assertSame('default-connection', $next->chainConnection);
+ $this->assertSame('default-queue', $next->chainQueue);
}
}
diff --git a/tests/Cache/CacheDatabaseLockTest.php b/tests/Cache/CacheDatabaseLockTest.php
index 59ca834121..fdf8ca75fa 100644
--- a/tests/Cache/CacheDatabaseLockTest.php
+++ b/tests/Cache/CacheDatabaseLockTest.php
@@ -55,7 +55,7 @@ public function testOwnershipAndLifetimeReadTheWriterInsteadOfAStaleReplica(): v
$reader->exec("insert into cache_locks values ('key', 'stale', 1010)");
$connection = new SQLiteConnection($writer, ':memory:');
$connection->setReadPdo($reader);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
$lock = new DatabaseLock($resolver, null, 'key', 'cache_locks', 60, 'fresh', null);
@@ -97,7 +97,7 @@ public function testLockCanBeAcquiredIfAlreadyOwnedBySameOwner(): void
// So it tries to update
$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 = Double::for(Builder::class)->strict();
$query->expects('where')->with('owner', $owner)->returns($query);
$query->expects('orWhere')->with('expiration', '<=', Argument::type('int'))->returns($query);
$callback($query);
@@ -122,7 +122,7 @@ public function testLockCannotBeAcquiredIfAlreadyHeld(): void
// Update fails too (someone else owns it)
$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 = Double::for(Builder::class)->strict();
$query->expects('where')->with('owner', $lock->owner())->returns($query);
$query->expects('orWhere')->with('expiration', '<=', Argument::type('int'))->returns($query);
@@ -158,14 +158,14 @@ 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')->strict()]);
+ [$lock] = $this->getLock(lockLottery: [1, 1], driver: 'sqlite', tables: [$this->liveOwnerRead(static fn (): string => 'other-owner')]);
$this->assertFalse($lock->acquire());
}
public function testSqliteLockIsInsertedWhenNoLiveLockExists(): void
{
- $insert = Double::for(Builder::class);
+ $insert = Double::for(Builder::class)->strict();
$insert->expects('insertOrIgnore')->returns(1);
[$lock] = $this->getLock(driver: 'sqlite', tables: [$this->liveOwnerRead(static fn (): null => null), $insert]);
@@ -182,9 +182,9 @@ public function testSqliteExpiredOrOwnLockIsTakenOverByTheConditionalUpdate(bool
$read = $this->liveOwnerRead(static function () use (&$lock, $own): ?string {
return $own ? $lock->owner() : null;
});
- $insert = Double::for(Builder::class);
+ $insert = Double::for(Builder::class)->strict();
$insert->expects('insertOrIgnore')->returns(0);
- $update = Double::for(Builder::class);
+ $update = Double::for(Builder::class)->strict();
$update->expects('where')->with('key', 'foo');
$update->expects('where')->with(Argument::type(Closure::class));
$update->expects('update')->returns(1);
@@ -199,13 +199,13 @@ public function testSqliteExpiredOrOwnLockIsTakenOverByTheConditionalUpdate(bool
#[TestWith(['mariadb', true])]
public function testATakeoverThatChangedNoRowIsConfirmedWithACurrentReadWhereOnlyChangedRowsCount(string $driver, bool $owned): void
{
- $insert = Double::for(Builder::class);
+ $insert = Double::for(Builder::class)->strict();
$insert->expects('insert')->throws(new UniqueConstraintViolationException('', '', [], new Exception));
- $update = Double::for(Builder::class);
+ $update = Double::for(Builder::class)->strict();
$update->expects('where')->with('key', 'foo');
$update->expects('where')->with(Argument::type(Closure::class));
$update->expects('update')->returns(0);
- $read = Double::for(Builder::class);
+ $read = Double::for(Builder::class)->strict();
// 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]);
@@ -218,12 +218,12 @@ public function testATakeoverThatChangedNoRowIsConfirmedWithACurrentReadWhereOnl
#[TestWith([false])]
public function testARefreshThatChangedNoRowIsConfirmedWithACurrentReadWhereOnlyChangedRowsCount(bool $owned): void
{
- $update = Double::for(Builder::class);
+ $update = Double::for(Builder::class)->strict();
$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);
+ $read = Double::for(Builder::class)->strict();
[$lock] = $this->getLock(driver: 'mysql', tables: [$update, $read]);
$this->expectLiveOwnerCurrentRead($read, $lock->owner(), $owned);
@@ -250,7 +250,6 @@ public function testLockCanBeAcquiredWithoutAutomaticPruning(?array $lottery): v
{
[$lock, $table] = $this->getLock(lockLottery: $lottery);
- $table->strict();
$table->expects('insertOrIgnore')->returns(1);
$this->assertTrue($lock->acquire());
@@ -488,9 +487,9 @@ public function testGetConnectionNameCanReturnNull(): void
*/
protected function getLock(int $seconds = 10, ?array $lockLottery = [0, 1], ?string $connectionName = 'default', string $driver = 'pgsql', array $tables = []): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
- $table = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $table = Double::for(Builder::class)->strict();
$table->allows('useWritePdo');
$resolver->allows('connection')->with($connectionName)->returns($connection);
@@ -529,7 +528,7 @@ protected function expectLiveOwnerCurrentRead(Builder $read, string $owner, bool
*/
protected function liveOwnerRead(Closure $owner): Builder&DoubleInterface
{
- $read = Double::for(Builder::class);
+ $read = Double::for(Builder::class)->strict();
$read->expects('useWritePdo');
$read->expects('where')->with('key', 'foo');
$read->expects('where')->with('expiration', '>', Argument::type('int'));
diff --git a/tests/Cache/CacheDatabaseStoreTest.php b/tests/Cache/CacheDatabaseStoreTest.php
index c63df54320..8933c98f5d 100644
--- a/tests/Cache/CacheDatabaseStoreTest.php
+++ b/tests/Cache/CacheDatabaseStoreTest.php
@@ -335,8 +335,8 @@ public function testItemsMayBeFlushedFromCache(): void
public function testLocksMayBeFlushedFromCache(): void
{
[$store, , , $resolver] = $this->getStore();
- $lockConnection = Double::for(Connection::class);
- $lockTable = Double::for(Builder::class);
+ $lockConnection = Double::for(Connection::class)->strict();
+ $lockTable = Double::for(Builder::class)->strict();
$resolver->allows('connection')->with('locks')->returns($lockConnection);
$lockConnection->expects('table')->with('cache_locks')->returns($lockTable);
$lockTable->expects('delete')->returns(2);
@@ -443,7 +443,7 @@ public function testSupportsFlushingLocksRequiresSeparateLockTable(): void
$this->assertTrue($store->supportsFlushingLocks());
- $store = new DatabaseStore(Double::for(ConnectionResolverInterface::class), 'default', 'cache', '', 'cache');
+ $store = new DatabaseStore(Double::for(ConnectionResolverInterface::class)->strict(), 'default', 'cache', '', 'cache');
$this->assertFalse($store->supportsFlushingLocks());
}
@@ -472,9 +472,9 @@ protected function getStore(
array|bool|null $serializableClasses = null,
?SerializableClassPolicy $serializableClassPolicy = null,
): array {
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
- $table = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $table = Double::for(Builder::class)->strict();
$resolver->allows('connection')->with('default')->returns($connection);
$connection->allows('table')->with('table')->returns($table);
@@ -496,9 +496,9 @@ protected function getStore(
*/
protected function getPostgresStore(): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(PostgresConnection::class);
- $table = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(PostgresConnection::class)->strict();
+ $table = Double::for(Builder::class)->strict();
$resolver->allows('connection')->with('default')->returns($connection);
$connection->allows('table')->with('table')->returns($table);
@@ -513,9 +513,9 @@ protected function getPostgresStore(): array
*/
protected function getSqliteStore(): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(SQLiteConnection::class);
- $table = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(SQLiteConnection::class)->strict();
+ $table = Double::for(Builder::class)->strict();
$resolver->allows('connection')->with('default')->returns($connection);
$connection->allows('table')->with('table')->returns($table);
@@ -530,8 +530,8 @@ protected function getSqliteStore(): array
*/
protected function getMocks(): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $resolver->allows('connection')->with('default')->returns(Double::for(Connection::class));
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $resolver->allows('connection')->with('default')->returns(Double::for(Connection::class)->strict());
return [$resolver, 'default', 'table', 'prefix'];
}
@@ -541,8 +541,8 @@ protected function getMocks(): array
*/
protected function getPostgresMocks(): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $resolver->allows('connection')->with('default')->returns(Double::for(PostgresConnection::class));
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $resolver->allows('connection')->with('default')->returns(Double::for(PostgresConnection::class)->strict());
return [$resolver, 'default', 'table', 'prefix'];
}
@@ -552,8 +552,8 @@ protected function getPostgresMocks(): array
*/
protected function getSqliteMocks(): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $resolver->allows('connection')->with('default')->returns(Double::for(SQLiteConnection::class));
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $resolver->allows('connection')->with('default')->returns(Double::for(SQLiteConnection::class)->strict());
return [$resolver, 'default', 'table', 'prefix'];
}
@@ -568,7 +568,7 @@ protected function getSqliteMocks(): array
*/
protected function mockTable(DatabaseStore $store): array
{
- $table = Double::for(Builder::class);
+ $table = Double::for(Builder::class)->strict();
$connection = $store->getConnection();
$connection->allows('table')->with('table')->returns($table);
diff --git a/tests/Cache/CacheEventsTest.php b/tests/Cache/CacheEventsTest.php
index dc4fb598a5..f6f23b27ea 100644
--- a/tests/Cache/CacheEventsTest.php
+++ b/tests/Cache/CacheEventsTest.php
@@ -60,7 +60,7 @@ protected function event(object $event): void
parent::event($event);
}
};
- $dispatcher = Double::for(DispatcherContract::class);
+ $dispatcher = Double::for(DispatcherContract::class)->strict();
$dispatcher->allows('hasListeners')->returns(false);
$dispatcher->expects('dispatch')->never();
$repository->setEventDispatcher($dispatcher);
@@ -97,7 +97,7 @@ protected function event(object $event): void
parent::event($event);
}
};
- $dispatcher = Double::for(DispatcherContract::class);
+ $dispatcher = Double::for(DispatcherContract::class)->strict();
$dispatcher->allows('hasListeners')->returns(false);
$dispatcher->expects('dispatch')->never();
$repository->setEventDispatcher($dispatcher);
@@ -190,7 +190,7 @@ public function testTaggedManyTriggersManyEvents(): void
public function testGetDispatchesFailureEventWhenTheStoreThrows(): void
{
$exception = new RuntimeException('The cache read failed.');
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('get')->with('foo')->throws($exception);
$events = [];
$repository = new Repository($store, ['store' => 'array']);
@@ -215,7 +215,7 @@ public function testGetDispatchesFailureEventWhenTheStoreThrows(): void
public function testManyDispatchesFailureEventWhenTheStoreThrows(): void
{
$exception = new RuntimeException('The cache batch read failed.');
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('many')->with(['foo', 'bar'])->throws($exception);
$events = [];
$repository = new Repository($store, ['store' => 'array']);
@@ -240,7 +240,7 @@ public function testManyDispatchesFailureEventWhenTheStoreThrows(): void
public function testPutDispatchesFailureEventWhenTheStoreThrows(): void
{
$exception = new RuntimeException('The cache write failed.');
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('put')->with('foo', 'bar', 60)->throws($exception);
$events = [];
$repository = new Repository($store, ['store' => 'array']);
@@ -270,7 +270,7 @@ public function testFalseWriteResultDispatchesFailureEventsWithoutException(
array $eventClasses,
array $keys,
): void {
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects($method)->with(...$arguments)->returns(false);
$events = [];
$repository = new Repository($store, ['store' => 'array']);
@@ -303,7 +303,7 @@ public function testPutManyDispatchesFailureEventsWhenTheStoreThrows(): void
{
$exception = new RuntimeException('The cache batch write failed.');
$values = ['foo' => 'bar', 'baz' => 'qux'];
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('putMany')->with($values, 60)->throws($exception);
$events = [];
$repository = new Repository($store, ['store' => 'array']);
@@ -328,7 +328,7 @@ public function testPutManyDispatchesFailureEventsWhenTheStoreThrows(): void
public function testForeverDispatchesFailureEventWhenTheStoreThrows(): void
{
$exception = new RuntimeException('The cache forever write failed.');
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forever')->with('foo', 'bar')->throws($exception);
$events = [];
$repository = new Repository($store, ['store' => 'array']);
@@ -353,7 +353,7 @@ public function testForeverDispatchesFailureEventWhenTheStoreThrows(): void
public function testForgetDispatchesFailureEventWhenTheStoreThrows(): void
{
$exception = new RuntimeException('The cache forget failed.');
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forget')->with('foo')->throws($exception);
$events = [];
$repository = new Repository($store, ['store' => 'array']);
@@ -387,7 +387,7 @@ public function testCancellationDoesNotDispatchFailureEvents(
if ($cleanupThrows) {
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
- $store = Double::for(Store::class, CanFlushLocks::class, AuthoritativeRawReadable::class);
+ $store = Double::for(Store::class, CanFlushLocks::class, AuthoritativeRawReadable::class)->strict();
$store->allows('supportsFlushingLocks')->returns(true);
$store->expects($storeMethod)
->with(...$storeArguments)
@@ -582,7 +582,7 @@ public function testForgetTriggersEvents(): void
public function testForgetDoesTriggerFailedEventOnFailure(): void
{
$dispatcher = $this->getDispatcher();
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forget')->returns(false);
$repository = new Repository($store);
$repository->setEventDispatcher($dispatcher);
@@ -629,7 +629,7 @@ public function testEmptyTaggedFlushIsIdempotentAndDispatchesSuccessEvents(): vo
public function testFlushDispatchesFailureEventWithExactException(string $method): void
{
$exception = new RuntimeException('The cache flush failed.');
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('flush')->throws($exception);
$events = [];
$repository = new Repository($store, ['store' => 'array']);
@@ -661,7 +661,7 @@ public function testFlushLocksTriggersEvents(): void
public function testFlushLocksDispatchesFailureEventWithExactException(): void
{
$exception = new RuntimeException('The cache lock flush failed.');
- $store = Double::for(Store::class, CanFlushLocks::class);
+ $store = Double::for(Store::class, CanFlushLocks::class)->strict();
$store->expects('supportsFlushingLocks')->returns(true);
$store->expects('flushLocks')->throws($exception);
$events = [];
@@ -689,7 +689,7 @@ public function testFlushFailureDoesDispatchEvent(string $method): void
$dispatcher = $this->getDispatcher();
// Create a store that fails to flush
- $failingStore = Double::for(Store::class);
+ $failingStore = Double::for(Store::class)->strict();
$failingStore->expects('flush')->returns(false);
$repository = new Repository($failingStore, ['store' => 'array']);
@@ -707,7 +707,7 @@ public function testFlushLocksFailureDoesDispatchEvent(): void
$dispatcher = $this->getDispatcher();
// Create a store that fails to flush locks
- $failingStore = Double::for(ArrayStore::class);
+ $failingStore = Double::for(ArrayStore::class)->strict();
$failingStore->allows('supportsFlushingLocks')->returns(true);
$failingStore->expects('flushLocks')->returns(false);
diff --git a/tests/Cache/CacheFailoverStoreTest.php b/tests/Cache/CacheFailoverStoreTest.php
index 13360083be..119e7b386b 100644
--- a/tests/Cache/CacheFailoverStoreTest.php
+++ b/tests/Cache/CacheFailoverStoreTest.php
@@ -51,7 +51,7 @@ public function testFlushLocksCallsFlushLocksOnAllBackingStores(): void
$this->assertTrue($storeA->lock('lock-a', 60)->get());
$this->assertTrue($storeB->lock('lock-b', 60)->get());
- $cache = Double::for(CacheManager::class);
+ $cache = Double::for(CacheManager::class)->strict();
$cache->expects('store')->with('store-a')->returns(new Repository($storeA));
$cache->expects('store')->with('store-b')->returns(new Repository($storeB));
@@ -85,7 +85,7 @@ public function testIncompleteClassHandlerRunsOnceAcrossFailoverRepositories():
public function testAuthoritativeReadDelegatesToCapableRepository(): void
{
- $backingStore = Double::for(Store::class, AuthoritativeRawReadable::class);
+ $backingStore = Double::for(Store::class, AuthoritativeRawReadable::class)->strict();
$backingStore->expects('getAuthoritativeRaw')->with('key')->returns(NullSentinel::VALUE);
$store = $this->makeFailoverStore(['cache' => $backingStore]);
@@ -127,11 +127,11 @@ public function testAuthoritativeReadRecursesThroughMemoizedFailoverAndStack():
public function testAuthoritativeReadFailsOverAfterStoreFailure(): void
{
$failure = new RuntimeException('primary unavailable');
- $primary = Double::for(Store::class, AuthoritativeRawReadable::class);
+ $primary = Double::for(Store::class, AuthoritativeRawReadable::class)->strict();
$primary->expects('getAuthoritativeRaw')->with('key')->throws($failure);
- $secondary = Double::for(Store::class, AuthoritativeRawReadable::class);
+ $secondary = Double::for(Store::class, AuthoritativeRawReadable::class)->strict();
$secondary->expects('getAuthoritativeRaw')->with('key')->returns('value');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(CacheFailedOver::class)->returns(false);
$events->expects('dispatch')->never();
@@ -145,7 +145,7 @@ public function testAuthoritativeReadFailsOverAfterStoreFailure(): void
public function testRawReadsFallBackToContractRepositoryWithLossyNullSemantics(): void
{
- $repository = Double::for(RepositoryContract::class);
+ $repository = Double::for(RepositoryContract::class)->strict();
$repository->expects('get')->with('key')->returns('value');
$repository->expects('get')->with(['cached-null', 'miss'])->returns([
'cached-null' => null,
@@ -167,7 +167,7 @@ public function testRawReadsFallBackToContractRepositoryWithLossyNullSemantics()
public function testCountersPreserveEveryContractValidResult(): void
{
- $backingStore = Double::for(Store::class);
+ $backingStore = Double::for(Store::class)->strict();
$backingStore->expects('increment')->with('increment', 2)->returns(true);
$backingStore->expects('decrement')->with('decrement', 3)->returns(false);
$store = $this->makeFailoverStore(['cache' => $backingStore]);
@@ -180,7 +180,7 @@ public function testCountersPreserveEveryContractValidResult(): void
public function testLockFlushCapabilityRequiresAtLeastOneLockProvider(bool $hasStore): void
{
$store = $this->makeFailoverStore($hasStore ? [
- 'plain' => Double::for(Store::class),
+ 'plain' => Double::for(Store::class)->strict(),
] : []);
$this->assertFalse($store->supportsFlushingLocks());
@@ -208,10 +208,10 @@ public function testLockFlushCapabilityRequiresEveryLockProviderToSupportFlushin
$flushable = $this->lockStore();
$flushable->expects('supportsFlushingLocks')->returns(true);
- $unsupported = Double::for(Store::class, LockProvider::class);
+ $unsupported = Double::for(Store::class, LockProvider::class)->strict();
$store = $this->makeFailoverStore([
- 'plain' => Double::for(Store::class),
+ 'plain' => Double::for(Store::class)->strict(),
'flushable' => $flushable,
'unsupported' => $unsupported,
]);
@@ -244,7 +244,7 @@ public function testLockFlushCapabilityIsTrueWhenEveryLockProviderSupportsIt():
$second->expects('supportsFlushingLocks')->returns(true);
$store = $this->makeFailoverStore([
- 'plain' => Double::for(Store::class),
+ 'plain' => Double::for(Store::class)->strict(),
'first' => $first,
'second' => $second,
]);
@@ -350,14 +350,14 @@ public function testFirstSuccessOperationDoesNotFailOverAfterCancellation(bool $
if ($cleanupThrows) {
$cancellation = new RuntimeException('Read cleanup failed.', previous: $cancellation);
}
- $first = Double::for(Store::class);
+ $first = Double::for(Store::class)->strict();
$first->expects('get')->with('key')->throws(new RuntimeException('first failure'));
- $second = Double::for(Store::class);
+ $second = Double::for(Store::class)->strict();
$second->expects('get')->with('key')->throws($cancellation);
- $third = Double::for(Store::class);
+ $third = Double::for(Store::class)->strict();
$third->expects('get')->never();
$failedStores = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(CacheFailedOver::class)->returns(true);
$events->expects('dispatch')->resolves(
function (CacheFailedOver $event) use (&$failedStores): void {
@@ -387,11 +387,11 @@ public function testEveryStoreOperationDoesNotContinueAfterCancellation(bool $cl
if ($cleanupThrows) {
$cancellation = new RuntimeException('Forget cleanup failed.', previous: $cancellation);
}
- $first = Double::for(Store::class);
+ $first = Double::for(Store::class)->strict();
$first->expects('forget')->with('key')->returns(true);
- $second = Double::for(Store::class);
+ $second = Double::for(Store::class)->strict();
$second->expects('forget')->with('key')->throws($cancellation);
- $third = Double::for(Store::class);
+ $third = Double::for(Store::class)->strict();
$third->expects('forget')->never();
$store = $this->makeFailoverStore([
'first' => $first,
@@ -410,17 +410,17 @@ public function testEveryStoreOperationDoesNotContinueAfterCancellation(bool $cl
public function testFirstSuccessListenerFailurePreservesObservedAndUnattemptedFailures(): void
{
$listenerFailure = new RuntimeException('listener failure');
- $first = Double::for(Store::class);
+ $first = Double::for(Store::class)->strict();
$first->expects('forget')->with('key')->returns(true);
$first->expects('get')->times(2)->with('key')->throws(new RuntimeException('first failure'));
- $second = Double::for(Store::class);
+ $second = Double::for(Store::class)->strict();
$second->expects('forget')->with('key')->throws(new RuntimeException('second failure'));
$second->expects('get')->with('key')->throws(new RuntimeException('second failure'));
- $third = Double::for(Store::class);
+ $third = Double::for(Store::class)->strict();
$third->expects('forget')->with('key')->returns(true);
$third->expects('get')->with('key')->returns('value');
$failedStores = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->with(CacheFailedOver::class)->returns(true);
$events->allows('dispatch')->resolves(
function (CacheFailedOver $event) use (&$failedStores, $listenerFailure): void {
@@ -453,7 +453,7 @@ public function testEveryStoreListenerFailurePreservesObservedAndUnattemptedFail
{
$listenerFailure = new RuntimeException('listener failure');
$firstCall = 0;
- $first = Double::for(Store::class);
+ $first = Double::for(Store::class)->strict();
$first->expects('forget')->times(3)->with('key')->resolves(
function () use (&$firstCall): bool {
++$firstCall;
@@ -463,12 +463,12 @@ function () use (&$firstCall): bool {
: throw new RuntimeException('first failure');
}
);
- $second = Double::for(Store::class);
+ $second = Double::for(Store::class)->strict();
$second->expects('forget')->times(2)->with('key')->throws(new RuntimeException('second failure'));
- $third = Double::for(Store::class);
+ $third = Double::for(Store::class)->strict();
$third->expects('forget')->times(2)->with('key')->returns(true);
$failedStores = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->with(CacheFailedOver::class)->returns(true);
$events->allows('dispatch')->resolves(
function (CacheFailedOver $event) use (&$failedStores, $listenerFailure): void {
@@ -505,7 +505,7 @@ public function testListenerInterruptionPreservesUnattemptedFailureHistoryWithSp
$thirdFailure = new RuntimeException('third failure');
$firstCall = 0;
$secondCall = 0;
- $first = Double::for(Store::class);
+ $first = Double::for(Store::class)->strict();
$first->expects('forget')->times(3)->with('key')->resolves(
function () use (&$firstCall, $firstFailure): bool {
++$firstCall;
@@ -513,7 +513,7 @@ function () use (&$firstCall, $firstFailure): bool {
return $firstCall === 1 ? true : throw $firstFailure;
}
);
- $second = Double::for(Store::class);
+ $second = Double::for(Store::class)->strict();
$second->expects('forget')->times(3)->with('key')->resolves(
function () use (&$secondCall, $secondFailure): bool {
++$secondCall;
@@ -521,10 +521,10 @@ function () use (&$secondCall, $secondFailure): bool {
return $secondCall === 1 ? true : throw $secondFailure;
}
);
- $third = Double::for(Store::class);
+ $third = Double::for(Store::class)->strict();
$third->expects('forget')->times(2)->with('key')->throws($thirdFailure);
$failedStores = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->with(CacheFailedOver::class)->returns(true);
$events->allows('dispatch')->resolves(
function (CacheFailedOver $event) use (&$failedStores, $listenerFailure): void {
@@ -562,10 +562,10 @@ function (CacheFailedOver $event) use (&$failedStores, $listenerFailure): void {
public function testReplacementStoreReportsItsOwnFirstFailure(): void
{
- $cache = Double::for(CacheManager::class);
- $events = Double::for(Dispatcher::class);
- $primary = Double::for(RepositoryContract::class);
- $secondary = Double::for(RepositoryContract::class);
+ $cache = Double::for(CacheManager::class)->strict();
+ $events = Double::for(Dispatcher::class)->strict();
+ $primary = Double::for(RepositoryContract::class)->strict();
+ $secondary = Double::for(RepositoryContract::class)->strict();
$primary->allows('get')->throws(new RuntimeException('Primary unavailable.'));
$secondary->allows('get')->returns('value');
$cache->allows('store')->with('primary')->returns($primary);
@@ -584,12 +584,12 @@ public function testReplacementStoreReportsItsOwnFirstFailure(): void
public function testFailoverEventCarriesLogicalAndFailedBackingStoreNames(): void
{
$exception = new RuntimeException('primary unavailable');
- $first = Double::for(Store::class);
+ $first = Double::for(Store::class)->strict();
$first->expects('get')->with('key')->throws($exception);
- $second = Double::for(Store::class);
+ $second = Double::for(Store::class)->strict();
$second->expects('get')->with('key')->returns('value');
$captured = null;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(CacheFailedOver::class)->returns(true);
$events->expects('dispatch')->resolves(function (CacheFailedOver $event) use (&$captured): void {
$captured = $event;
@@ -617,7 +617,7 @@ public function testSeparateLockStoreReportingRequiresEveryLockProviderToBeSepar
$shared->expects('hasSeparateLockStore')->returns(false);
$store = $this->makeFailoverStore([
- 'plain' => Double::for(Store::class),
+ 'plain' => Double::for(Store::class)->strict(),
'separate' => $separate,
'shared' => $shared,
]);
@@ -634,7 +634,7 @@ public function testSeparateLockStoreReportingIsTrueWhenEveryLockProviderIsSepar
$second->expects('hasSeparateLockStore')->returns(true);
$store = $this->makeFailoverStore([
- 'plain' => Double::for(Store::class),
+ 'plain' => Double::for(Store::class)->strict(),
'first' => $first,
'second' => $second,
]);
@@ -654,7 +654,7 @@ protected function makeFailoverStore(
?array $storeNames = null,
?string $failoverStoreName = null,
): FailoverStore {
- $cache = Double::for(CacheManager::class);
+ $cache = Double::for(CacheManager::class)->strict();
foreach ($stores as $name => $store) {
$cache->allows('store')
@@ -675,6 +675,6 @@ protected function makeFailoverStore(
*/
protected function lockStore(): Store&LockProvider&CanFlushLocks
{
- return Double::for(Store::class, LockProvider::class, CanFlushLocks::class);
+ return Double::for(Store::class, LockProvider::class, CanFlushLocks::class)->strict();
}
}
diff --git a/tests/Cache/CacheFileStoreTest.php b/tests/Cache/CacheFileStoreTest.php
index 5eca6794af..fd2639e8dc 100644
--- a/tests/Cache/CacheFileStoreTest.php
+++ b/tests/Cache/CacheFileStoreTest.php
@@ -369,7 +369,7 @@ public function testSerializableClassPolicyControlsCachedObjects(): void
public function testLockStoreRetainsBothSerializationPolicies(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->allows('exists')->returns(true);
$serializableClasses = [stdClass::class];
$policy = new SerializableClassPolicy(static fn (): false => false);
@@ -567,7 +567,7 @@ public function testTouchExtendsTtl(): void
public function testStoreItemProperlySetsPermissions(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$store = new FileStore($files, __DIR__, 0644);
$files->allows('exists')->returns(true);
$hash = hash('xxh128', 'foo');
@@ -587,7 +587,7 @@ public function testStoreItemProperlySetsPermissions(): void
public function testStoreItemDirectoryProperlySetsPermissions(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$store = new FileStore($files, __DIR__, 0606);
$hash = hash('xxh128', 'foo');
$cache_parent_dir = substr($hash, 0, 2);
diff --git a/tests/Cache/CacheManagerTest.php b/tests/Cache/CacheManagerTest.php
index 7c51484005..55c5d43230 100644
--- a/tests/Cache/CacheManagerTest.php
+++ b/tests/Cache/CacheManagerTest.php
@@ -124,7 +124,7 @@ public function testCustomDriverOverridesInternalDrivers(): void
$app = $this->getApp($userConfig);
$cacheManager = new CacheManager($app);
- $repository = Double::for(CacheRepository::class);
+ $repository = Double::for(CacheRepository::class)->strict();
$repository->allows('get')->with('foo')->returns('bar');
$cacheManager->extend('array', fn (): CacheRepository => $repository);
@@ -179,12 +179,12 @@ public function testFailoverDriverPassesItsConfiguredNameToFailoverEvents(): voi
],
]);
$failure = new RuntimeException('primary unavailable');
- $primary = Double::for(Store::class);
+ $primary = Double::for(Store::class)->strict();
$primary->expects('get')->with('key')->throws($failure);
- $secondary = Double::for(Store::class);
+ $secondary = Double::for(Store::class)->strict();
$secondary->expects('get')->with('key')->returns('value');
$captured = null;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(CacheFailedOver::class)->returns(true);
$events->expects('dispatch')->resolves(function (CacheFailedOver $event) use (&$captured): void {
$captured = $event;
@@ -326,9 +326,9 @@ public function testManagerBuiltSerializingStoresShareOnePolicy(): void
],
],
]);
- $app->instance('db', Double::for(ConnectionResolverInterface::class));
+ $app->instance('db', Double::for(ConnectionResolverInterface::class)->strict());
$app->instance('files', new Filesystem);
- $filesystem = Double::for(FilesystemFactory::class);
+ $filesystem = Double::for(FilesystemFactory::class)->strict();
$filesystem->expects('disk')->with('test')->returns(new ArrayFilesystem);
$app->instance('filesystem', $filesystem);
$app->instance(SwooleTableManager::class, new SwooleTableManager($app));
@@ -407,7 +407,7 @@ public function testItCanCreateStorageDriver(): void
{
$disk = new ArrayFilesystem;
- $filesystem = Double::for(FilesystemFactory::class);
+ $filesystem = Double::for(FilesystemFactory::class)->strict();
$filesystem->expects('disk')->with('s3')->returns($disk);
$app = $this->getApp([
@@ -505,7 +505,7 @@ public function testCustomCreatorsStillOverrideMultiWordInternalDrivers(): void
];
$cacheManager = new CacheManager($this->getApp($userConfig));
- $repository = Double::for(CacheRepository::class);
+ $repository = Double::for(CacheRepository::class)->strict();
$cacheManager->extend('worker-array', fn (): CacheRepository => $repository);
@@ -535,7 +535,7 @@ public function testItMakesRepositoryWhenContainerHasNoDispatcher(): void
$this->assertSame($theStore, $repo->getStore());
// binding dispatcher after the repo's birth will have no effect.
- $eventDispatcher = Double::for(Dispatcher::class);
+ $eventDispatcher = Double::for(Dispatcher::class)->strict();
$app->instance(Dispatcher::class, $eventDispatcher);
$this->assertNull($repo->getEventDispatcher());
@@ -566,7 +566,7 @@ public function testItRefreshesDispatcherOnAllStores(): void
$app = $this->getApp($userConfig);
- $originalDispatcher = Double::for(Dispatcher::class);
+ $originalDispatcher = Double::for(Dispatcher::class)->strict();
$app->instance(Dispatcher::class, $originalDispatcher);
$cacheManager = new CacheManager($app);
@@ -576,7 +576,7 @@ public function testItRefreshesDispatcherOnAllStores(): void
$this->assertSame($originalDispatcher, $repo1->getEventDispatcher());
$this->assertSame($originalDispatcher, $repo2->getEventDispatcher());
- $replacementDispatcher = Double::for(Dispatcher::class);
+ $replacementDispatcher = Double::for(Dispatcher::class)->strict();
$app->instance(Dispatcher::class, $replacementDispatcher);
$cacheManager->refreshEventDispatcher();
@@ -595,10 +595,10 @@ public function testRefreshEventDispatcherSkipsCustomRepositoryImplementations()
],
],
]);
- $app->instance(Dispatcher::class, Double::for(Dispatcher::class));
+ $app->instance(Dispatcher::class, Double::for(Dispatcher::class)->strict());
$cacheManager = new CacheManager($app);
- $repository = Double::for(CacheRepository::class);
+ $repository = Double::for(CacheRepository::class)->strict();
$cacheManager->extend('custom', fn (): CacheRepository => $repository);
$this->assertSame($repository, $cacheManager->store('custom'));
@@ -682,7 +682,7 @@ public function testForgetDriver(): void
$cacheManager->expects('resolve')
->with('array')
->times(4)
- ->returns(Double::for(CacheRepository::class));
+ ->returns(Double::for(CacheRepository::class)->strict());
$cacheManager->expects('getDefaultDriver')
->returns('array');
@@ -928,7 +928,7 @@ public function testSessionDriverResolvesSessionStore(): void
$app = $this->getApp($userConfig);
- $session = Double::for(Session::class);
+ $session = Double::for(Session::class)->strict();
$app->instance('session.store', $session);
$cacheManager = new CacheManager($app);
@@ -1156,7 +1156,7 @@ protected function getAppWithRedis(array $userConfig): Container
$app = $this->getApp($userConfig);
// Mock Redis client
- $redisClient = Double::for(Redis::class);
+ $redisClient = Double::for(Redis::class)->strict();
$redisClient->allows('getOption')
->with(Redis::OPT_COMPRESSION)
->returns(Redis::COMPRESSION_NONE);
@@ -1165,20 +1165,20 @@ protected function getAppWithRedis(array $userConfig): Container
->returns('');
// Mock RedisConnection
- $connection = Double::for(PhpRedisConnection::class);
+ $connection = Double::for(PhpRedisConnection::class)->strict();
$connection->allows('release');
$connection->allows('serialized')->returns(false);
$connection->allows('client')->returns($redisClient);
// Mock RedisPool
- $pool = Double::for(RedisPool::class);
+ $pool = Double::for(RedisPool::class)->strict();
$pool->allows('borrow')->returns($connection);
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$poolManager->allows('pool')->with('default')->returns($pool);
// Mock RedisFactory
- $redisFactory = Double::for(RedisFactory::class);
+ $redisFactory = Double::for(RedisFactory::class)->strict();
$app->instance('redis', $redisFactory);
$app->instance(PoolManager::class, $poolManager);
diff --git a/tests/Cache/CacheMemoizedStoreTest.php b/tests/Cache/CacheMemoizedStoreTest.php
index 9b0f115779..8d28f2f969 100644
--- a/tests/Cache/CacheMemoizedStoreTest.php
+++ b/tests/Cache/CacheMemoizedStoreTest.php
@@ -148,7 +148,7 @@ public function testIncompleteClassHandlerRunsOnceAcrossMemoizedRepositories():
public function testPutManyWithEmptyInputReturnsDelegatedRepositoryResult(): void
{
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->expects('putMany')->with([], 60)->returns(false);
$store = new MemoizedStore('memoized', $repository);
@@ -211,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(Double::for(Store::class)));
+ $nonTaggable = new MemoizedStore('test', new Repository(Double::for(Store::class)->strict()));
$this->assertTrue($taggable->supportsTags());
$this->assertSame(TagMode::All, $taggable->getTagMode());
@@ -391,7 +391,7 @@ public function testManyFiresCacheHitNotCacheMissedForSentinelThroughMemoizedSto
// Capture only the many() read-path events by attaching the dispatcher
// after the write.
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -413,7 +413,7 @@ public function testManyFiresCacheHitNotCacheMissedForSentinelThroughMemoizedSto
public function testLockFlushCapabilityDelegatesToUnderlyingStore(): void
{
$flushable = new MemoizedStore('test', new Repository(new ArrayStore));
- $nonFlushableStore = Double::for(Store::class);
+ $nonFlushableStore = Double::for(Store::class)->strict();
$nonFlushable = new MemoizedStore('test', new Repository($nonFlushableStore));
$this->assertTrue($flushable->supportsFlushingLocks());
@@ -428,7 +428,7 @@ public function testLocksCanBeFlushedWhenUnderlyingStoreSupportsIt(): void
public function testFlushLocksDelegatesToUnderlyingStore(): void
{
- $store = Double::for(Store::class, CanFlushLocks::class);
+ $store = Double::for(Store::class, CanFlushLocks::class)->strict();
$store->expects('supportsFlushingLocks')->returns(true);
$store->expects('flushLocks')->returns(true);
@@ -452,7 +452,7 @@ public function testFlushLocksThrowsWhenUnderlyingStoreDoesNotSupportIt(): void
public function testFlushLocksRejectsUnsupportedUnderlyingStore(): void
{
- $store = Double::for(Store::class, CanFlushLocks::class);
+ $store = Double::for(Store::class, CanFlushLocks::class)->strict();
$store->expects('supportsFlushingLocks')->returns(false);
$store->expects('flushLocks')->never();
diff --git a/tests/Cache/CacheNullStoreTest.php b/tests/Cache/CacheNullStoreTest.php
index 809e0582d5..21930e50f5 100644
--- a/tests/Cache/CacheNullStoreTest.php
+++ b/tests/Cache/CacheNullStoreTest.php
@@ -71,7 +71,7 @@ public function testRememberNullableAlwaysReRunsCallbackOnNullStore(): void
public function testTaggedFlushReportsRejectedTagIdentifierWrites(): void
{
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$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 cef402c206..c0fbef688e 100644
--- a/tests/Cache/CacheRedisLockTest.php
+++ b/tests/Cache/CacheRedisLockTest.php
@@ -74,7 +74,7 @@ public function testLockCanBeReleased(): void
{
[$lock, $redis] = $this->getLock();
- $connection = Double::for(CacheLockRedisConnection::class);
+ $connection = Double::for(CacheLockRedisConnection::class)->strict();
$connection->expects('pack')
->with([$lock->owner()])
->returns(['packed-owner']);
@@ -91,7 +91,7 @@ public function testLockCanBeReleased(): void
public function testReleaseReturnsFalseWhenNotOwner(): void
{
[$lock, $redis] = $this->getLock(seconds: 60);
- $connection = Double::for(CacheLockRedisConnection::class);
+ $connection = Double::for(CacheLockRedisConnection::class)->strict();
$connection->expects('pack')
->with([$lock->owner()])
->returns(['packed-owner']);
@@ -117,7 +117,7 @@ public function testLockCanBeForceReleased(): void
public function testOwnerReturnsTheOwnerIdentifier(): void
{
- $redis = Double::for(CacheLockRedisProxy::class);
+ $redis = Double::for(CacheLockRedisProxy::class)->strict();
$lock = new RedisLock($redis, 'lock:foo', 60, 'my-owner-id');
@@ -134,7 +134,7 @@ public function testOwnerIsAutoGeneratedWhenNotProvided(): void
public function testGetCallsAcquireAndExecutesCallbackOnSuccess(): void
{
[$lock, $redis] = $this->getLock(seconds: 60);
- $connection = Double::for(CacheLockRedisConnection::class);
+ $connection = Double::for(CacheLockRedisConnection::class)->strict();
$connection->expects('pack')
->with([$lock->owner()])
->returns(['packed-owner']);
@@ -169,7 +169,7 @@ public function testGetReturnsFalseWhenLockNotAcquired(): void
public function testGetReleasesLockAfterCallbackEvenOnException(): void
{
[$lock, $redis] = $this->getLock(seconds: 60);
- $connection = Double::for(CacheLockRedisConnection::class);
+ $connection = Double::for(CacheLockRedisConnection::class)->strict();
$connection->expects('pack')
->with([$lock->owner()])
->returns(['packed-owner']);
@@ -195,7 +195,7 @@ public function testRefreshExtendsLockTtl(): void
{
[$lock, $redis] = $this->getLock();
- $connection = Double::for(CacheLockRedisConnection::class);
+ $connection = Double::for(CacheLockRedisConnection::class)->strict();
$connection->expects('pack')
->with([$lock->owner()])
->returns(['packed-owner']);
@@ -213,7 +213,7 @@ public function testRefreshWithCustomTtl(): void
{
[$lock, $redis] = $this->getLock();
- $connection = Double::for(CacheLockRedisConnection::class);
+ $connection = Double::for(CacheLockRedisConnection::class)->strict();
$connection->expects('pack')
->with([$lock->owner()])
->returns(['packed-owner']);
@@ -231,7 +231,7 @@ public function testRefreshReturnsFalseWhenNotOwned(): void
{
[$lock, $redis] = $this->getLock();
- $connection = Double::for(CacheLockRedisConnection::class);
+ $connection = Double::for(CacheLockRedisConnection::class)->strict();
$connection->expects('pack')
->with([$lock->owner()])
->returns(['packed-owner']);
@@ -366,7 +366,7 @@ public function testGetConnectionNameReturnsConnectionName(): void
*/
protected function getLock(int $seconds = 10): array
{
- $redis = Double::for(CacheLockRedisProxy::class);
+ $redis = Double::for(CacheLockRedisProxy::class)->strict();
$lock = new RedisLock($redis, 'foo', $seconds);
diff --git a/tests/Cache/CacheRedisStoreTest.php b/tests/Cache/CacheRedisStoreTest.php
index 86d768361d..c03a0573eb 100755
--- a/tests/Cache/CacheRedisStoreTest.php
+++ b/tests/Cache/CacheRedisStoreTest.php
@@ -40,6 +40,6 @@ public function testGetAndSetPrefix(): void
*/
protected function getRedis(): RedisStore
{
- return new RedisStore(Double::for(Factory::class), 'prefix:');
+ return new RedisStore(Double::for(Factory::class)->strict(), 'prefix:');
}
}
diff --git a/tests/Cache/CacheRepositoryEnumTest.php b/tests/Cache/CacheRepositoryEnumTest.php
index 75201d9e64..8beafc8195 100644
--- a/tests/Cache/CacheRepositoryEnumTest.php
+++ b/tests/Cache/CacheRepositoryEnumTest.php
@@ -442,10 +442,10 @@ public function testTagsWithMixedEnumsAndStrings(): void
public function testTagsWithBackedEnumVariadicArgs(): void
{
- $store = Double::for(ArrayStore::class);
+ $store = Double::for(ArrayStore::class)->strict();
$repo = new Repository($store);
- $taggedCache = Double::for(TaggedCache::class);
+ $taggedCache = Double::for(TaggedCache::class)->strict();
$taggedCache->allows('setDefaultCacheTime');
$store->expects('tags')->with(['users', 'posts'])->returns($taggedCache);
@@ -454,10 +454,10 @@ public function testTagsWithBackedEnumVariadicArgs(): void
public function testTagsWithUnitEnumVariadicArgs(): void
{
- $store = Double::for(ArrayStore::class);
+ $store = Double::for(ArrayStore::class)->strict();
$repo = new Repository($store);
- $taggedCache = Double::for(TaggedCache::class);
+ $taggedCache = Double::for(TaggedCache::class)->strict();
$taggedCache->allows('setDefaultCacheTime');
$store->expects('tags')->with(['Reports', 'Exports'])->returns($taggedCache);
@@ -510,10 +510,10 @@ public function testOffsetAccessWithUnitEnum(): void
protected function getRepository(): Repository
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(true);
$dispatcher->allows('dispatch')->with(Argument::any())->returns(null);
- $repository = new Repository(Double::for(Store::class));
+ $repository = new Repository(Double::for(Store::class)->strict());
$repository->setEventDispatcher($dispatcher);
diff --git a/tests/Cache/CacheRepositoryTest.php b/tests/Cache/CacheRepositoryTest.php
index bd4b6d7354..d281eefab3 100644
--- a/tests/Cache/CacheRepositoryTest.php
+++ b/tests/Cache/CacheRepositoryTest.php
@@ -74,7 +74,7 @@ public function testGetReturnsValueFromCache(): void
public function testAuthoritativeRawReadUsesItemKeyAndPreservesSentinelEvents(): void
{
- $store = Double::for(Store::class, AuthoritativeRawReadable::class);
+ $store = Double::for(Store::class, AuthoritativeRawReadable::class)->strict();
$store->expects('getAuthoritativeRaw')->with('prefix:foo')->returns(NullSentinel::VALUE);
$repository = new class($store) extends Repository {
@@ -85,7 +85,7 @@ protected function itemKey(string $key): string
};
$events = [];
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(true);
$dispatcher->allows('dispatch')->resolves(function ($event) use (&$events): void {
$events[] = $event;
@@ -103,12 +103,12 @@ protected function itemKey(string $key): string
public function testAuthoritativeRawReadDispatchesRetrievalFailure(): void
{
$failure = new RuntimeException('read failed');
- $store = Double::for(Store::class, AuthoritativeRawReadable::class);
+ $store = Double::for(Store::class, AuthoritativeRawReadable::class)->strict();
$store->expects('getAuthoritativeRaw')->with('foo')->throws($failure);
$repository = new Repository($store);
$events = [];
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(true);
$dispatcher->allows('dispatch')->resolves(function ($event) use (&$events): void {
$events[] = $event;
@@ -131,7 +131,7 @@ public function testAuthoritativeRawReadDispatchesRetrievalFailure(): void
public function testAuthoritativeRawReadPreservesCancellation(): void
{
$cancellation = new CanceledException('read canceled');
- $store = Double::for(Store::class, AuthoritativeRawReadable::class);
+ $store = Double::for(Store::class, AuthoritativeRawReadable::class)->strict();
$store->expects('getAuthoritativeRaw')->with('foo')->throws($cancellation);
$repository = new Repository($store);
@@ -339,7 +339,7 @@ public function testAuthoritativeRawReadFallsBackToStoreAndHandlesIncompleteClas
$handled[] = [$key, $class];
});
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('get')->with('prefix:foo')->returns($incomplete);
$repository = new class($store) extends Repository {
@@ -417,7 +417,7 @@ public function testManyEmitsOneFailureWithoutPartialSuccessWhenIncompleteClassH
]);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')->resolves(function ($event) use (&$captured): void {
$captured[] = $event;
@@ -605,8 +605,8 @@ public function testFlexibleSkipsRefreshWhenAuthoritativeMarkerChanged(): void
{
$created = CarbonImmutable::now()->subSeconds(11)->getTimestamp();
$markerKey = Repository::FLEXIBLE_CREATED_KEY_PREFIX . 'foo';
- $store = Double::for(Store::class, LockProvider::class, AuthoritativeRawReadable::class);
- $lock = Double::for(Lock::class);
+ $store = Double::for(Store::class, LockProvider::class, AuthoritativeRawReadable::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$store->expects('many')->with(['foo', $markerKey])->returns([
'foo' => 'stale',
@@ -811,7 +811,7 @@ public function testEmptyPutManyReturnsTrueWithoutStoreOrEvents(): void
{
$repo = $this->getRepository();
$repo->getStore()->expects('putMany')->never();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never();
$events->expects('dispatch')->never();
$repo->setEventDispatcher($events);
@@ -871,7 +871,7 @@ public function testAddWithStoreFailureReturnsFalse(): void
public function testCacheAddCallsRedisStoreAdd(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('add')->with('k', 'v', 60)->returns(true);
$repository = new Repository($store);
$this->assertTrue($repository->add('k', 'v', 60));
@@ -879,12 +879,12 @@ public function testCacheAddCallsRedisStoreAdd(): void
public function testAddMethodCanAcceptDateIntervals(): void
{
- $storeWithAdd = Double::for(RedisStore::class);
+ $storeWithAdd = Double::for(RedisStore::class)->strict();
$storeWithAdd->expects('add')->with('k', 'v', 61)->returns(true);
$repository = new Repository($storeWithAdd);
$this->assertTrue($repository->add('k', 'v', DateInterval::createFromDateString('61 seconds')));
- $storeWithoutAdd = Double::for(ArrayStore::class);
+ $storeWithoutAdd = Double::for(ArrayStore::class)->strict();
$this->assertFalse(method_exists(ArrayStore::class, 'add'), 'This store should not have add method on it.');
$storeWithoutAdd->expects('get')->with('k')->returns(null);
$storeWithoutAdd->expects('put')->with('k', 'v', 60)->returns(true);
@@ -894,12 +894,12 @@ public function testAddMethodCanAcceptDateIntervals(): void
public function testAddMethodCanAcceptDateTimeInterface(): void
{
- $withAddStore = Double::for(RedisStore::class);
+ $withAddStore = Double::for(RedisStore::class)->strict();
$withAddStore->expects('add')->with('k', 'v', 61)->returns(true);
$repository = new Repository($withAddStore);
$this->assertTrue($repository->add('k', 'v', CarbonImmutable::now()->addSeconds(61)));
- $noAddStore = Double::for(ArrayStore::class);
+ $noAddStore = Double::for(ArrayStore::class)->strict();
$this->assertFalse(method_exists(ArrayStore::class, 'add'), 'This store should not have add method on it.');
$noAddStore->expects('get')->with('k')->returns(null);
$noAddStore->expects('put')->with('k', 'v', 62)->returns(true);
@@ -940,7 +940,7 @@ public function testAddWithDatetimeInPastOrZeroSecondsReturnsImmediately(): void
public function testCounterFailuresAreReturnedWithoutCoercion(): void
{
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('increment')->with('increment', 2)->returns(false);
$store->expects('decrement')->with('decrement', 3)->returns(false);
$repository = new Repository($store);
@@ -1056,10 +1056,10 @@ public function testRemovingMultipleKeysFailsIfOneFails(): void
public function testAllTagsArePassedToTaggableStore(): void
{
- $store = Double::for(ArrayStore::class);
+ $store = Double::for(ArrayStore::class)->strict();
$repo = new Repository($store);
- $taggedCache = Double::for(TaggedCache::class);
+ $taggedCache = Double::for(TaggedCache::class)->strict();
$taggedCache->expects('setDefaultCacheTime')->returns($taggedCache);
$store->expects('tags')->with(['foo', 'bar', 'baz'])->returns($taggedCache);
$repo->tags('foo', 'bar', 'baz');
@@ -1079,7 +1079,7 @@ public function testItThrowsExceptionWhenTaggableStoreReportsUnsupportedTags():
$this->expectException(NotSupportedException::class);
$this->expectExceptionMessageIsOrContains('Detailed tag support failure.');
- $store = Double::for(TaggableStore::class);
+ $store = Double::for(TaggableStore::class)->strict();
$store->expects('supportsTags')->never();
$store->expects('tags')->with(['foo'])->throws(
new NotSupportedException('Detailed tag support failure.')
@@ -1150,7 +1150,7 @@ public function testDefaultCacheLifeTimeIsSetOnTaggableStore(): void
public function testFlushLocksDelegatesToStore(): void
{
- $flushable = Double::for(RedisStore::class);
+ $flushable = Double::for(RedisStore::class)->strict();
$flushable->expects('supportsFlushingLocks')->returns(true);
$flushable->expects('flushLocks')->returns(true);
@@ -1169,7 +1169,7 @@ public function testTaggableRepositoriesSupportTags(): void
public function testTaggableRepositoriesCanReportUnsupportedTags(): void
{
- $taggable = Double::for(TaggableStore::class);
+ $taggable = Double::for(TaggableStore::class)->strict();
$taggable->expects('supportsTags')->returns(false);
$taggableRepo = new Repository($taggable);
@@ -1186,7 +1186,7 @@ public function testNonTaggableRepositoryDoesNotSupportTags(): void
public function testFlushableLockRepositorySupportsFlushingLocks(): void
{
- $flushable = Double::for(RedisStore::class);
+ $flushable = Double::for(RedisStore::class)->strict();
$flushable->expects('supportsFlushingLocks')->returns(true);
$flushableRepo = new Repository($flushable);
@@ -1195,7 +1195,7 @@ public function testFlushableLockRepositorySupportsFlushingLocks(): void
public function testFlushableLockRepositoryCanReportUnsupportedFlushingLocks(): void
{
- $flushable = Double::for(RedisStore::class);
+ $flushable = Double::for(RedisStore::class)->strict();
$flushable->expects('supportsFlushingLocks')->returns(false);
$flushableRepo = new Repository($flushable);
@@ -1204,7 +1204,7 @@ public function testFlushableLockRepositoryCanReportUnsupportedFlushingLocks():
public function testNonFlushableLockRepositoryDoesNotSupportFlushingLocks(): void
{
- $nonFlushable = Double::for(Store::class);
+ $nonFlushable = Double::for(Store::class)->strict();
$nonFlushableRepo = new Repository($nonFlushable);
$this->assertFalse($nonFlushableRepo->supportsFlushingLocks());
@@ -1214,7 +1214,7 @@ public function testItThrowsExceptionWhenStoreDoesNotSupportFlushingLocks(): voi
{
$this->expectException(BadMethodCallException::class);
- $nonFlushable = Double::for(Store::class);
+ $nonFlushable = Double::for(Store::class)->strict();
$nonFlushableRepo = new Repository($nonFlushable);
$nonFlushableRepo->flushLocks();
@@ -1284,9 +1284,9 @@ public function testAtomicExecutesCallbackAndReturnsResult(): void
public function testAtomicPassesLockAndWaitSecondsToLock(): void
{
- $store = Double::for(Store::class, LockProvider::class);
+ $store = Double::for(Store::class, LockProvider::class)->strict();
$repo = new Repository($store);
- $lock = Double::for(Lock::class);
+ $lock = Double::for(Lock::class)->strict();
$store->expects('lock')->with('foo', 30, null)->returns($lock);
$lock->expects('block')->with(15, Argument::type('callable'))->resolves(function ($seconds, $callback) {
@@ -1302,9 +1302,9 @@ public function testAtomicPassesLockAndWaitSecondsToLock(): void
public function testAtomicPassesOwnerToLock(): void
{
- $store = Double::for(Store::class, LockProvider::class);
+ $store = Double::for(Store::class, LockProvider::class)->strict();
$repo = new Repository($store);
- $lock = Double::for(Lock::class);
+ $lock = Double::for(Lock::class)->strict();
$store->expects('lock')->with('foo', 10, 'my-owner')->returns($lock);
$lock->expects('block')->with(10, Argument::type('callable'))->resolves(function ($seconds, $callback) {
@@ -1379,7 +1379,7 @@ public function testManyDispatchesEventsForIntegerArrayKeys(): void
$repo->put('1', 'cached', 60);
$captured = [];
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->resolves(
static fn (string $event): bool => in_array($event, [CacheHit::class, CacheMissed::class], true)
);
@@ -1643,12 +1643,12 @@ public static function typedGetterTypeMismatchProvider(): array
public function testRememberFiresEventsWithRedisStore(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('withPinnedConnection')->never();
$store->expects('get')->with('foo')->returns(null);
$store->expects('put')->with('foo', 'bar', 10)->returns(true);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->expects('dispatch')->times(4); // RetrievingKey, CacheMissed, WritingKey, KeyWritten
@@ -1662,12 +1662,12 @@ public function testRememberFiresEventsWithRedisStore(): void
public function testRememberForeverFiresEventsWithRedisStore(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('withPinnedConnection')->never();
$store->expects('get')->with('foo')->returns(null);
$store->expects('forever')->with('foo', 'bar')->returns(true);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->expects('dispatch')->times(4); // RetrievingKey, CacheMissed, WritingKey, KeyWritten
@@ -1681,11 +1681,11 @@ public function testRememberForeverFiresEventsWithRedisStore(): void
public function testRememberHitFiresEventsWithRedisStore(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('withPinnedConnection')->never();
$store->expects('get')->with('foo')->returns('cached');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->expects('dispatch')->times(2); // RetrievingKey, CacheHit
@@ -1699,12 +1699,12 @@ public function testRememberHitFiresEventsWithRedisStore(): void
public function testRememberSkipsDispatchWhenCacheEventsHaveNoListeners(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('withPinnedConnection')->never();
$store->expects('get')->with('foo')->returns(null);
$store->expects('put')->with('foo', 'bar', 10);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->times(4)->returns(false);
$events->expects('dispatch')->never();
@@ -1718,13 +1718,13 @@ public function testRememberSkipsDispatchWhenCacheEventsHaveNoListeners(): void
public function testRememberNullableFiresEventsWithNullPayloadOnCacheMiss(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('withPinnedConnection')->never();
$store->expects('get')->with('foo')->returns(null);
$store->expects('put')->with('foo', NullSentinel::VALUE, 10)->returns(true);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -1753,13 +1753,13 @@ public function testRememberNullableFiresEventsWithNullPayloadOnCacheMiss(): voi
public function testRememberForeverNullableFiresEventsWithNullPayloadOnCacheMiss(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('withPinnedConnection')->never();
$store->expects('get')->with('foo')->returns(null);
$store->expects('forever')->with('foo', NullSentinel::VALUE)->returns(true);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -1798,7 +1798,7 @@ public function testFlexibleNullableFiresEventsWithNullPayloadOnCacheMiss(): voi
->returns(true);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -1832,12 +1832,12 @@ public function testFlexibleNullableFiresEventsWithNullPayloadOnCacheMiss(): voi
public function testRememberNullableFiresHitEventWithNullPayloadOnSentinelRetrieval(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('withPinnedConnection')->never();
$store->expects('get')->with('foo')->returns(NullSentinel::VALUE);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -1869,7 +1869,7 @@ public function testManyFiresCacheHitWithNullPayloadForCachedNullEntry(): void
// Capture only the many() read-path events by attaching the dispatcher
// after the write.
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -1890,11 +1890,11 @@ public function testManyFiresCacheHitWithNullPayloadForCachedNullEntry(): void
public function testRememberWorksWithoutPinnableStore(): void
{
- $store = Double::for(ArrayStore::class);
+ $store = Double::for(ArrayStore::class)->strict();
$store->expects('get')->with('foo')->returns(null);
$store->expects('put')->with('foo', 'bar', 10);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')->with(Argument::any())->returns(null);
@@ -1913,7 +1913,7 @@ protected function getRepository(): Repository
{
// A plain dispatcher reports no listeners, so the repository would skip building events.
$dispatcher = new EventFake(new EventDispatcher(new Container));
- $repository = new Repository(Double::for(Store::class));
+ $repository = new Repository(Double::for(Store::class)->strict());
$repository->setEventDispatcher($dispatcher);
diff --git a/tests/Cache/CacheServiceProviderTest.php b/tests/Cache/CacheServiceProviderTest.php
index aa26ddc990..08046f940f 100644
--- a/tests/Cache/CacheServiceProviderTest.php
+++ b/tests/Cache/CacheServiceProviderTest.php
@@ -34,7 +34,7 @@ public function testConsoleFinalizationRunsAfterEveryProviderCanContribute(): vo
$manager->allowSerializableClassesUsing(
static fn (): array => [CachePolicyEarlyContribution::class],
);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$listeners = [];
$events->expects('listen')
->times(2)
@@ -42,7 +42,7 @@ public function testConsoleFinalizationRunsAfterEveryProviderCanContribute(): vo
$listeners[$event][] = $listener;
});
$bootedCallback = null;
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$application->expects('make')
->with(CacheManager::class)
->returns($manager);
@@ -85,7 +85,7 @@ public function testConsoleFinalizationRunsAfterEveryProviderCanContribute(): vo
public function testServerFinalizationResolvesTheWorkerManagerAtEventTime(bool $customProcess): void
{
$workerManager = $this->manager();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$listeners = [];
$events->expects('listen')
->times(3)
@@ -94,7 +94,7 @@ public function testServerFinalizationResolvesTheWorkerManagerAtEventTime(bool $
$listeners[$name][] = $listener;
}
});
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$application->expects('make')
->with(CacheManager::class)
->returns($workerManager);
@@ -113,9 +113,9 @@ public function testServerFinalizationResolvesTheWorkerManagerAtEventTime(bool $
$this->assertCount(2, $listeners[AfterWorkerStart::class]);
if ($customProcess) {
- $event = new BeforeProcessHandle(Double::for(AbstractProcess::class), 0);
+ $event = new BeforeProcessHandle(Double::for(AbstractProcess::class)->strict(), 0);
} else {
- $server = Double::for(SwooleServer::class);
+ $server = Double::for(SwooleServer::class)->strict();
// Policy finalization runs in request workers and taskworkers, unlike Swoole timer registration.
$server->taskworker = true;
$event = new AfterWorkerStart($server, 9);
@@ -131,7 +131,7 @@ public function testServerFinalizationResolvesTheWorkerManagerAtEventTime(bool $
public function testFacadeCallsTheManagerExtensionWithoutResolvingAStore(): void
{
$resolver = static fn (): array => [CachePolicyEarlyContribution::class];
- $manager = Double::for(CacheManager::class);
+ $manager = Double::for(CacheManager::class)->strict();
$manager->expects('allowSerializableClassesUsing')
->with(Argument::same($resolver));
$manager->expects('store')->never();
diff --git a/tests/Cache/CacheStackStoreLocksTest.php b/tests/Cache/CacheStackStoreLocksTest.php
index a06085b9f7..0db2940c71 100644
--- a/tests/Cache/CacheStackStoreLocksTest.php
+++ b/tests/Cache/CacheStackStoreLocksTest.php
@@ -21,8 +21,8 @@ class CacheStackStoreLocksTest extends TestCase
public function testLockDelegatesToBottomLayer(): void
{
- $bottom = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $bottom = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$bottom->expects('lock')->with('name', 30, 'owner')->returns($lock);
@@ -33,8 +33,8 @@ public function testLockDelegatesToBottomLayer(): void
public function testRestoreLockDelegatesToBottomLayer(): void
{
- $bottom = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $bottom = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$bottom->expects('restoreLock')->with('name', 'owner')->returns($lock);
@@ -55,7 +55,7 @@ public function testLockThrowsWhenBottomLayerDoesNotSupportLocks(): void
public function testSupportsFlushingLocksReflectsBottomLayerProbe(): void
{
- $bottom = Double::for(Store::class, CanFlushLocks::class);
+ $bottom = Double::for(Store::class, CanFlushLocks::class)->strict();
$bottom->expects('supportsFlushingLocks')->returns(true);
$this->assertTrue((new StackStore([$this->plainStore(), $bottom]))->supportsFlushingLocks());
@@ -63,7 +63,7 @@ public function testSupportsFlushingLocksReflectsBottomLayerProbe(): void
public function testSupportsFlushingLocksReturnsFalseWhenBottomLayerProbeIsFalse(): void
{
- $bottom = Double::for(Store::class, CanFlushLocks::class);
+ $bottom = Double::for(Store::class, CanFlushLocks::class)->strict();
$bottom->expects('supportsFlushingLocks')->returns(false);
$this->assertFalse((new StackStore([$this->plainStore(), $bottom]))->supportsFlushingLocks());
@@ -76,7 +76,7 @@ public function testSupportsFlushingLocksReturnsFalseWhenBottomLayerDoesNotImple
public function testFlushLocksDelegatesToBottomLayer(): void
{
- $bottom = Double::for(Store::class, CanFlushLocks::class);
+ $bottom = Double::for(Store::class, CanFlushLocks::class)->strict();
$bottom->expects('supportsFlushingLocks')->returns(true);
$bottom->expects('flushLocks')->returns(true);
@@ -85,7 +85,7 @@ public function testFlushLocksDelegatesToBottomLayer(): void
public function testFlushLocksThrowsWhenBottomLayerCannotFlushLocks(): void
{
- $bottom = Double::for(Store::class, CanFlushLocks::class);
+ $bottom = Double::for(Store::class, CanFlushLocks::class)->strict();
$bottom->expects('supportsFlushingLocks')->returns(false);
$bottom->expects('flushLocks')->never();
@@ -99,7 +99,7 @@ public function testFlushLocksThrowsWhenBottomLayerCannotFlushLocks(): void
public function testHasSeparateLockStoreDelegatesToBottomLayer(): void
{
- $bottom = Double::for(Store::class, CanFlushLocks::class);
+ $bottom = Double::for(Store::class, CanFlushLocks::class)->strict();
$bottom->expects('hasSeparateLockStore')->returns(true);
$this->assertTrue((new StackStore([$this->plainStore(), $bottom]))->hasSeparateLockStore());
@@ -110,6 +110,6 @@ public function testHasSeparateLockStoreDelegatesToBottomLayer(): void
*/
private function plainStore(): Store&DoubleInterface
{
- return Double::for(Store::class);
+ return Double::for(Store::class)->strict();
}
}
diff --git a/tests/Cache/CacheStackStoreTagsTest.php b/tests/Cache/CacheStackStoreTagsTest.php
index 9e8ad4a34b..6844776353 100644
--- a/tests/Cache/CacheStackStoreTagsTest.php
+++ b/tests/Cache/CacheStackStoreTagsTest.php
@@ -75,10 +75,11 @@ public function testInvalidCompositionsDoNotSupportTags(): void
try {
$stack->tags(['t']);
- $this->fail('Expected NotSupportedException was not thrown.');
} catch (NotSupportedException) {
- $this->assertTrue(true);
+ continue;
}
+
+ $this->fail('Expected NotSupportedException was not thrown.');
}
}
@@ -427,7 +428,7 @@ protected function event(object $event): void
parent::event($event);
}
};
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(false);
$dispatcher->expects('dispatch')->never();
$cache->setEventDispatcher($dispatcher);
@@ -696,17 +697,18 @@ public function testTaggedReadAndDeleteOperationsThrow(): void
] as $operation) {
try {
$operation();
- $this->fail('Expected BadMethodCallException was not thrown.');
} catch (BadMethodCallException) {
- $this->assertTrue(true);
+ continue;
}
+
+ $this->fail('Expected BadMethodCallException was not thrown.');
}
}
public function testClearFlushesTaggableLayersOnly(): void
{
$taggable = $this->anyModeTaggableStore();
- $tagSet = Double::for(TagSet::class);
+ $tagSet = Double::for(TagSet::class)->strict();
$taggedCache = Double::for(TaggedCache::class)->strict();
$taggable->expects('tags')->with(['tag'])->returns($taggedCache);
@@ -726,8 +728,8 @@ public function testClearFlushesEveryTaggableLayerAndAggregatesFalseResults(): v
$secondTaggable = $this->anyModeTaggableStore();
$firstTaggedCache = Double::for(TaggedCache::class)->strict();
$secondTaggedCache = Double::for(TaggedCache::class)->strict();
- $firstTagSet = Double::for(TagSet::class);
- $secondTagSet = Double::for(TagSet::class);
+ $firstTagSet = Double::for(TagSet::class)->strict();
+ $secondTagSet = Double::for(TagSet::class)->strict();
$firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache);
$secondTaggable->expects('tags')->with(['tag'])->returns($secondTaggedCache);
@@ -748,8 +750,8 @@ public function testTagSetFlushAttemptsEveryLayerAndPreservesTheFirstException()
$secondTaggable = $this->anyModeTaggableStore();
$firstTaggedCache = Double::for(TaggedCache::class)->strict();
$secondTaggedCache = Double::for(TaggedCache::class)->strict();
- $firstTagSet = Double::for(TagSet::class);
- $secondTagSet = Double::for(TagSet::class);
+ $firstTagSet = Double::for(TagSet::class)->strict();
+ $secondTagSet = Double::for(TagSet::class)->strict();
$firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache);
$secondTaggable->expects('tags')->with(['tag'])->returns($secondTaggedCache);
@@ -777,7 +779,7 @@ public function testTagSetFlushStopsImmediatelyOnCancellation(bool $cleanupThrow
$firstTaggable = $this->anyModeTaggableStore();
$secondTaggable = $this->anyModeTaggableStore();
$firstTaggedCache = Double::for(TaggedCache::class)->strict();
- $firstTagSet = Double::for(TagSet::class);
+ $firstTagSet = Double::for(TagSet::class)->strict();
$firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache);
$firstTaggedCache->expects('getTags')->returns($firstTagSet);
@@ -799,8 +801,8 @@ public function testClearDispatchesFailureEventWithExactTagSetException(): void
$secondTaggable = $this->anyModeTaggableStore();
$firstTaggedCache = Double::for(TaggedCache::class)->strict();
$secondTaggedCache = Double::for(TaggedCache::class)->strict();
- $firstTagSet = Double::for(TagSet::class);
- $secondTagSet = Double::for(TagSet::class);
+ $firstTagSet = Double::for(TagSet::class)->strict();
+ $secondTagSet = Double::for(TagSet::class)->strict();
$firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache);
$secondTaggable->expects('tags')->with(['tag'])->returns($secondTaggedCache);
$firstTaggedCache->expects('getTags')->returns($firstTagSet);
@@ -834,7 +836,7 @@ public function testClearCancellationSkipsFailureEventAndRemainingTaggableLayers
$firstTaggable = $this->anyModeTaggableStore();
$secondTaggable = $this->anyModeTaggableStore();
$firstTaggedCache = Double::for(TaggedCache::class)->strict();
- $firstTagSet = Double::for(TagSet::class);
+ $firstTagSet = Double::for(TagSet::class)->strict();
$firstTaggable->expects('tags')->with(['tag'])->returns($firstTaggedCache);
$firstTaggedCache->expects('getTags')->returns($firstTagSet);
$firstTagSet->expects('flush')->throws($cancellation);
@@ -891,7 +893,7 @@ private function nonTaggableStore(): Store&DoubleInterface
*/
private function capturingDispatcher(array &$captured): Dispatcher&DoubleInterface
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function (object $event) use (&$captured): void {
diff --git a/tests/Cache/CacheStackStoreTest.php b/tests/Cache/CacheStackStoreTest.php
index 7f29d964b5..bca4a94312 100644
--- a/tests/Cache/CacheStackStoreTest.php
+++ b/tests/Cache/CacheStackStoreTest.php
@@ -157,9 +157,9 @@ public function testAuthoritativeReadRecursesThroughBottomFailoverStore(): void
$bottom->expects('get')->with('key')->returns(['value' => 'fresh']);
$top->expects('get')->never();
- $cache = Double::for(CacheManager::class);
+ $cache = Double::for(CacheManager::class)->strict();
$cache->expects('store')->with('bottom')->returns(new Repository($bottom));
- $failover = new FailoverStore($cache, Double::for(Dispatcher::class), ['bottom']);
+ $failover = new FailoverStore($cache, Double::for(Dispatcher::class)->strict(), ['bottom']);
$this->assertSame('fresh', (new StackStore([$top, $failover]))->getAuthoritativeRaw('key'));
}
diff --git a/tests/Cache/CacheSwooleStoreIntervalTest.php b/tests/Cache/CacheSwooleStoreIntervalTest.php
index 09a89d2070..1b38c6a473 100644
--- a/tests/Cache/CacheSwooleStoreIntervalTest.php
+++ b/tests/Cache/CacheSwooleStoreIntervalTest.php
@@ -594,7 +594,7 @@ public function testStaleCleanupAndEvictionSkipIntervalControlRows(): void
public function testThrowingTimerResolverIsReportedAndCanRetry(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$container->instance(ExceptionHandler::class, $handler);
Container::setInstance($container);
@@ -602,6 +602,10 @@ public function testThrowingTimerResolverIsReportedAndCanRetry(): void
$store = $this->createStore($state);
$readerStore = $this->createStore($state);
$exception = new RuntimeException('refresh failed');
+ $handler->expects('report')->with(Argument::satisfies(
+ static fn (Throwable $e): bool => $e::class === $exception::class
+ && $e->getMessage() === $exception->getMessage()
+ ));
IntervalResolverState::$attempts = 0;
$store->interval('foo', function () use ($exception) {
@@ -618,10 +622,6 @@ public function testThrowingTimerResolverIsReportedAndCanRetry(): void
$store->refreshIntervalCaches();
- $handler->received('report')->with(Argument::satisfies(
- fn (Throwable $e): bool => $e::class === $exception::class
- && $e->getMessage() === $exception->getMessage()
- ))->times(1);
$this->assertFalse($this->userRow($state, $readerStore, 'foo'));
$this->assertNull($this->metadata($state, $metadataKey)['lastRefreshedAt']);
$this->assertNull($this->metadata($state, $metadataKey)['refreshingAt']);
@@ -656,7 +656,7 @@ public function testThrowingSameInstanceFallbackRethrowsAndClearsClaim(): void
public function testCanceledSameInstanceFallbackClearsClaimAndCanRetry(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$container->instance(ExceptionHandler::class, $handler);
Container::setInstance($container);
@@ -683,7 +683,7 @@ public function testCanceledSameInstanceFallbackClearsClaimAndCanRetry(): void
public function testTimerRefreshCleanupCancellationSupersedesOrdinaryFailureWithoutReporting(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$container->instance(ExceptionHandler::class, $handler);
Container::setInstance($container);
@@ -710,7 +710,7 @@ public function testTimerRefreshCleanupCancellationSupersedesOrdinaryFailureWith
public function testRefreshCancellationRemainsPrimaryWhenClaimCleanupFails(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$container->instance(ExceptionHandler::class, $handler);
Container::setInstance($container);
@@ -836,7 +836,7 @@ public function report(Throwable $e): void
public function testFailedPublicValueWriteClearsClaimAndReportsFailure(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$container->instance(ExceptionHandler::class, $handler);
Container::setInstance($container);
@@ -844,14 +844,13 @@ public function testFailedPublicValueWriteClearsClaimAndReportsFailure(): void
$workerStore = $this->createStore($state);
$refresherStore = new FailingIntervalValueSwooleStore($state);
+ $handler->expects('report')->with(Argument::satisfies(
+ static fn (RuntimeException $e): bool => $e->getMessage() === 'Unable to refresh Swoole interval cache [foo].'
+ ));
$workerStore->interval('foo', fn () => 'bar', 5);
$refresherStore->refreshIntervalCaches();
- $handler->received('report')->with(Argument::satisfies(
- fn (RuntimeException $e): bool => $e->getMessage() === 'Unable to refresh Swoole interval cache [foo].'
- ))->times(1);
-
$metadata = $this->metadata($state, $this->metadataKey($workerStore, 'foo'));
$this->assertNull($metadata['refreshingAt']);
diff --git a/tests/Cache/CacheSwooleStoreTest.php b/tests/Cache/CacheSwooleStoreTest.php
index a6358c851f..deb20488d0 100644
--- a/tests/Cache/CacheSwooleStoreTest.php
+++ b/tests/Cache/CacheSwooleStoreTest.php
@@ -53,12 +53,12 @@ public function testMissingItemsReturnNull(): void
public function testMissingSwooleTableConfigThrowsTableNotDefinedException(): void
{
- $config = Double::for(ConfigRepository::class);
+ $config = Double::for(ConfigRepository::class)->strict();
$config->expects('get')
->with('cache.swoole_tables.missing')
->returns(null);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('make')->with('config')->returns($config);
$this->expectException(InvalidArgumentException::class);
@@ -69,7 +69,7 @@ public function testMissingSwooleTableConfigThrowsTableNotDefinedException(): vo
public function testSealingRetainsExistingTablesAndRejectsLateCreation(): void
{
- $config = Double::for(ConfigRepository::class);
+ $config = Double::for(ConfigRepository::class)->strict();
$config->expects('get')
->with('cache.swoole_tables.first')
->returns([
@@ -78,7 +78,7 @@ public function testSealingRetainsExistingTablesAndRejectsLateCreation(): void
'conflict_proportion' => 0.2,
]);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('make')->with('config')->returns($config);
$manager = new SwooleTableManager($container->instance());
diff --git a/tests/Cache/CacheTaggedCacheTest.php b/tests/Cache/CacheTaggedCacheTest.php
index da029792bb..c0e9bc1ccd 100644
--- a/tests/Cache/CacheTaggedCacheTest.php
+++ b/tests/Cache/CacheTaggedCacheTest.php
@@ -110,7 +110,7 @@ public function testCacheSavedWithMultipleTagsCanBeFlushed(): void
public function testVersionedTagResetAttemptsEveryTagAndAggregatesFalseResults(): void
{
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forever')
->with('tag:users:key', Argument::type('string'))
->returns(false);
@@ -123,7 +123,7 @@ public function testVersionedTagResetAttemptsEveryTagAndAggregatesFalseResults()
public function testVersionedTagFlushAttemptsEveryTagAndTreatsMissingTagKeysAsSuccess(): void
{
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forget')->with('tag:users:key')->returns(false);
$store->expects('forget')->with('tag:posts:key')->returns(true);
@@ -132,7 +132,7 @@ public function testVersionedTagFlushAttemptsEveryTagAndTreatsMissingTagKeysAsSu
public function testVersionedTagFlushUsesThePerTagExtensionPoint(): void
{
- $tagSet = new class(Double::for(Store::class), ['users', 'posts']) extends VersionedTagSet {
+ $tagSet = new class(Double::for(Store::class)->strict(), ['users', 'posts']) extends VersionedTagSet {
public array $flushed = [];
public function flushTag(string $name): string
@@ -149,7 +149,7 @@ public function flushTag(string $name): string
public function testVersionedFlushTagReturnsItsKeyWhenTheTagDoesNotExist(): void
{
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forget')->with('tag:users:key')->returns(false);
$this->assertSame('tag:users:key', (new VersionedTagSet($store))->flushTag('users'));
@@ -157,7 +157,7 @@ public function testVersionedFlushTagReturnsItsKeyWhenTheTagDoesNotExist(): void
public function testVersionedTagResetUsesTheWriteExtensionPoint(): void
{
- $tagSet = new class(Double::for(Store::class), ['users', 'posts']) extends VersionedTagSet {
+ $tagSet = new class(Double::for(Store::class)->strict(), ['users', 'posts']) extends VersionedTagSet {
public array $written = [];
protected function writeTagId(string $name, string $id): bool
@@ -175,7 +175,7 @@ protected function writeTagId(string $name, string $id): bool
public function testVersionedTagResetAttemptsLaterTagsAndRethrowsTheFirstException(): void
{
$firstException = new RuntimeException('users failed');
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forever')
->with('tag:users:key', Argument::type('string'))
->throws($firstException);
@@ -197,7 +197,7 @@ public function testVersionedTagResetAttemptsLaterTagsAndRethrowsTheFirstExcepti
public function testVersionedTagFlushAttemptsLaterTagsAndRethrowsTheFirstException(): void
{
$firstException = new RuntimeException('users failed');
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forget')->with('tag:users:key')->throws($firstException);
$store->expects('forget')
->with('tag:posts:key')
@@ -220,7 +220,7 @@ public function testVersionedTagResetStopsImmediatelyOnCancellation(bool $cleanu
if ($cleanupThrows) {
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('forever')
->with('tag:users:key', Argument::type('string'))
->throws($cancellation);
@@ -242,7 +242,7 @@ public function testVersionedTagFlushStopsImmediatelyOnCancellation(bool $cleanu
if ($cleanupThrows) {
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$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');
diff --git a/tests/Cache/ClearCommandTest.php b/tests/Cache/ClearCommandTest.php
index c056fe0144..c0ab79a1a7 100644
--- a/tests/Cache/ClearCommandTest.php
+++ b/tests/Cache/ClearCommandTest.php
@@ -44,8 +44,8 @@ protected function setUp(): void
$app = new Application;
$app->instance('path.storage', __DIR__);
- $this->cacheManager = Double::for(CacheManager::class);
- $this->files = Double::for(Filesystem::class);
+ $this->cacheManager = Double::for(CacheManager::class)->strict();
+ $this->files = Double::for(Filesystem::class)->strict();
$this->cacheRepository = new Repository(new ArrayStore);
$this->command = new ClearCommand($this->cacheManager, $this->files);
$this->command->setHypervel($app);
@@ -65,7 +65,7 @@ public function testClearWithNoStoreArgument(): void
public function testClearWillFailWhenFlushFails(): void
{
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('flush')->returns(false);
$this->cacheManager->expects('store')->with(null)->returns(new Repository($store));
$this->files->expects('deleteDirectory');
@@ -182,7 +182,7 @@ public function testClearLocksCannotBeUsedWithTags(): void
public function testClearLocksWillFailWhenNotSupportedByStore(): void
{
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('flush')->never();
$this->cacheManager->expects('store')->with(null)->returns(new Repository($store));
@@ -204,7 +204,7 @@ public function testClearLocksWillFailWhenFlushLocksFails(): void
*/
protected function lockFlushingStore(): Store&CanFlushLocks&DoubleInterface
{
- $store = Double::for(Store::class, CanFlushLocks::class);
+ $store = Double::for(Store::class, CanFlushLocks::class)->strict();
$store->allows('supportsFlushingLocks')->returns(true);
return $store;
diff --git a/tests/Cache/ConcurrencyLimiterTest.php b/tests/Cache/ConcurrencyLimiterTest.php
index 07d1a5f686..5f0276d2e3 100644
--- a/tests/Cache/ConcurrencyLimiterTest.php
+++ b/tests/Cache/ConcurrencyLimiterTest.php
@@ -647,7 +647,7 @@ protected function failingReleaseStore(
?LimiterFailingReleaseLock &$lock = null,
?Throwable $releaseFailure = null,
): Store&LockProvider {
- $store = Double::for(Store::class, LockProvider::class);
+ $store = Double::for(Store::class, LockProvider::class)->strict();
$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 a37e4199e0..179995bc35 100644
--- a/tests/Cache/ForgetCommandTest.php
+++ b/tests/Cache/ForgetCommandTest.php
@@ -20,8 +20,8 @@ class ForgetCommandTest extends TestCase
public function testForgetKeyFromDefaultStore(): void
{
- $cacheManager = Double::for(CacheManager::class);
- $repository = Double::for(Repository::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
+ $repository = Double::for(Repository::class)->strict();
$cacheManager->expects('store')->with(null)->returns($repository);
$repository->expects('forget')->with('my-key');
@@ -40,8 +40,8 @@ public function testForgetKeyFromDefaultStore(): void
public function testForgetKeyFromSpecifiedStore(): void
{
- $cacheManager = Double::for(CacheManager::class);
- $repository = Double::for(Repository::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
+ $repository = Double::for(Repository::class)->strict();
$cacheManager->expects('store')->with('redis')->returns($repository);
$repository->expects('forget')->with('my-key');
diff --git a/tests/Cache/ModelCacheCoordinatorTest.php b/tests/Cache/ModelCacheCoordinatorTest.php
index 3738667880..6f73d1bfa4 100644
--- a/tests/Cache/ModelCacheCoordinatorTest.php
+++ b/tests/Cache/ModelCacheCoordinatorTest.php
@@ -104,9 +104,9 @@ public function testColdFillDoubleChecksAfterLockAcquisition(): void
$coordinator->fill($seedRepository, $this->source, 'seed', 300, fn (): string => 'published');
$envelope = $seedRepository->getStore()->get('seed');
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(RefreshableLock::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(RefreshableLock::class)->strict();
$repository->expects('get')->times(2)->with('key')->returns(null, $envelope);
$repository->expects('getStore')->returns($store);
@@ -293,9 +293,9 @@ function () use (&$reads): null {
public function testNonPublishingNullReadDoesNotRefreshTheLease(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(RefreshableLock::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(RefreshableLock::class)->strict();
$repository->expects('get')->times(2)->with('key')->returns(null);
$repository->expects('getStore')->returns($store);
@@ -319,9 +319,9 @@ public function testNonPublishingNullReadDoesNotRefreshTheLease(): void
public function testFailedLockAcquisitionReadsWithoutPublishingOrResolvingWriter(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(RefreshableLock::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(RefreshableLock::class)->strict();
$writerResolutions = 0;
$repository->expects('get')->with('key')->returns(null);
@@ -348,9 +348,9 @@ public function testFailedLockAcquisitionReadsWithoutPublishingOrResolvingWriter
public function testColdFillRefreshesAfterReadingAndBeforeResolvingWriterOrPublishing(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(RefreshableLock::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(RefreshableLock::class)->strict();
$operations = [];
$repository->expects('get')->times(2)->with('key')->returns(null);
@@ -398,9 +398,9 @@ function () use (&$operations): string {
public function testColdFillThatLostItsLeaseReturnsTheReadValueWithoutPublishing(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(RefreshableLock::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(RefreshableLock::class)->strict();
$operations = [];
$repository->expects('get')->times(2)->with('key')->returns(null);
@@ -440,9 +440,9 @@ function () use (&$operations): string {
public function testFalseCallbackResultIsNotMistakenForFailedAcquisition(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(RefreshableLock::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(RefreshableLock::class)->strict();
$repository->expects('get')->times(2)->with('key')->returns(null);
$repository->expects('getStore')->returns($store);
@@ -475,8 +475,8 @@ function () use (&$reads): false {
public function testFillPropagatesSourceFailureAndReleasesTheLock(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
$lock = new CoordinatorTestLock;
$repository->expects('get')->times(2)->with('key')->returns(null);
@@ -504,10 +504,10 @@ public function testFillPropagatesSourceFailureAndReleasesTheLock(): void
public function testInvalidationUsesTheSameBoundedLockAndForgetsInsideIt(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $fillLock = Double::for(RefreshableLock::class);
- $invalidateLock = Double::for(RefreshableLock::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $fillLock = Double::for(RefreshableLock::class)->strict();
+ $invalidateLock = Double::for(RefreshableLock::class)->strict();
$lockNames = [];
$repository->expects('get')->with('a-very-long-data-key')->returns(null);
@@ -587,8 +587,8 @@ public function testInvalidationRetriesBriefLockCollisionAfterTwentyFiveMillisec
Sleep::fake();
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
$lock = new CoordinatorTestLock(failFirstAcquisition: true);
$repository->expects('getStore')->returns($store);
@@ -608,9 +608,9 @@ public function testInvalidationRetriesBriefLockCollisionAfterTwentyFiveMillisec
public function testInvalidationPropagatesLockTimeoutWithoutForgetting(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(RefreshableLock::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(RefreshableLock::class)->strict();
$repository->expects('getStore')->returns($store);
$repository->expects('forget')->never();
@@ -630,7 +630,7 @@ public function testUnsupportedStoreIsRejectedOnlyAfterAMiss(): void
$coordinator->fill($seedRepository, $this->source, 'seed', 300, fn (): string => 'cached');
$envelope = $seedRepository->getStore()->get('seed');
- $hitRepository = Double::for(CacheRepository::class);
+ $hitRepository = Double::for(CacheRepository::class)->strict();
$hitRepository->expects('get')->with('key')->returns($envelope);
$hitRepository->expects('getStore')->never();
@@ -642,8 +642,8 @@ public function testUnsupportedStoreIsRejectedOnlyAfterAMiss(): void
fn () => throw new RuntimeException('The source must not be read on a cache hit.'),
));
- $missRepository = Double::for(CacheRepository::class);
- $unsupportedStore = Double::for(Store::class);
+ $missRepository = Double::for(CacheRepository::class)->strict();
+ $unsupportedStore = Double::for(Store::class)->strict();
$missRepository->expects('get')->with('key')->returns(null);
$missRepository->expects('getStore')->returns($unsupportedStore);
@@ -654,7 +654,7 @@ public function testUnsupportedStoreIsRejectedOnlyAfterAMiss(): void
public function testStackAndFailoverTopologiesAreRejectedThroughDirectAndMemoizedStores(): void
{
- $failoverStore = Double::for(FailoverStore::class);
+ $failoverStore = Double::for(FailoverStore::class)->strict();
$failoverStore->expects('getRaw')->times(2)->with('key')->returns(null);
$failoverStore->expects('getPrefix')->returns('');
@@ -696,9 +696,9 @@ public function testStackAndFailoverTopologiesAreRejectedThroughDirectAndMemoize
public function testNonRefreshableLockIsRejectedOnlyAfterAMiss(): void
{
$coordinator = new ModelCacheCoordinator($this->container);
- $repository = Double::for(CacheRepository::class);
- $store = Double::for(Store::class, LockProvider::class);
- $lock = Double::for(LockContract::class);
+ $repository = Double::for(CacheRepository::class)->strict();
+ $store = Double::for(Store::class, LockProvider::class)->strict();
+ $lock = Double::for(LockContract::class)->strict();
$repository->expects('get')->with('key')->returns(null);
$repository->expects('getStore')->returns($store);
diff --git a/tests/Cache/ModelCacheStoreValidatorTest.php b/tests/Cache/ModelCacheStoreValidatorTest.php
index be4b6a8f31..63f057544a 100644
--- a/tests/Cache/ModelCacheStoreValidatorTest.php
+++ b/tests/Cache/ModelCacheStoreValidatorTest.php
@@ -38,13 +38,12 @@ public function testAcceptsSupportedStoresAndSubclasses(): void
$validator = $this->validator();
foreach ([
- Double::for(DatabaseStore::class),
- Double::for(FileStore::class),
- Double::for(SwooleStore::class),
+ Double::for(DatabaseStore::class)->strict(),
+ Double::for(FileStore::class)->strict(),
+ Double::for(SwooleStore::class)->strict(),
$this->redisStore(),
] as $store) {
$validator->validate($this->repository($store), 'Auth user cache');
- $this->assertTrue(true);
}
}
@@ -56,14 +55,12 @@ public function testAcceptsAnyModeTags(): void
$this->repository($store),
'Auth user cache',
);
-
- $this->assertTrue(true);
}
public function testAcceptsAnyModeTagsThroughAValidStack(): void
{
$store = new StackStore([
- Double::for(FileStore::class),
+ Double::for(FileStore::class)->strict(),
$this->redisStore()->setTagMode(TagMode::Any),
]);
@@ -71,8 +68,6 @@ public function testAcceptsAnyModeTagsThroughAValidStack(): void
$this->repository($store),
'Auth user cache',
);
-
- $this->assertTrue(true);
}
public function testRejectsAllModeTags(): void
@@ -90,7 +85,7 @@ public function testRejectsAllModeTags(): void
public function testRejectsStoresWithoutTagSupportBeforeReadingTheMode(): void
{
- $store = Double::for(StackStore::class);
+ $store = Double::for(StackStore::class)->strict();
$store->expects('supportsTags')->returns(false);
$store->expects('getTagMode')->never();
@@ -111,9 +106,9 @@ public function testRejectsEveryUnsupportedStoreType(): void
new ArrayStore,
new WorkerArrayStore,
new NullStore,
- Double::for(SessionStore::class),
- Double::for(FailoverStore::class),
- Double::for(StorageStore::class),
+ Double::for(SessionStore::class)->strict(),
+ Double::for(FailoverStore::class)->strict(),
+ Double::for(StorageStore::class)->strict(),
] as $store) {
try {
$validator->validate($this->repository($store), 'Sanctum token cache');
@@ -128,7 +123,7 @@ public function testRejectsEveryUnsupportedStoreType(): void
public function testRejectsStacksBecauseOtherWorkersAndNodesCanRetainUpperLayerCopies(): void
{
$stack = new StackStore([
- Double::for(FileStore::class),
+ Double::for(FileStore::class)->strict(),
$this->redisStore(),
]);
@@ -146,7 +141,7 @@ public function testAcceptsAbsentAndDisabledRedisSerializersWithoutOpeningAConne
['SeRiAlIzEr' => Redis::SERIALIZER_NONE, 'compression' => 1],
[Redis::OPT_SERIALIZER => Redis::SERIALIZER_NONE],
] as $options) {
- $redis = Double::for(RedisFactory::class);
+ $redis = Double::for(RedisFactory::class)->strict();
$redis->expects('connection')->never();
$store = new RedisStore($redis, connection: 'cache');
@@ -154,8 +149,6 @@ public function testAcceptsAbsentAndDisabledRedisSerializersWithoutOpeningAConne
$this->repository($store),
'Auth user cache',
);
-
- $this->assertTrue(true);
}
}
@@ -164,8 +157,6 @@ public function testAcceptsTheNativePhpSerializer(): void
$this->validator(
connectionOptions: ['serializer' => Redis::SERIALIZER_PHP],
)->validate($this->repository($this->redisStore()), 'Auth user cache');
-
- $this->assertTrue(true);
}
public function testAcceptsIgbinaryWhenTheRedisBuildSupportsIt(): void
@@ -179,8 +170,6 @@ public function testAcceptsIgbinaryWhenTheRedisBuildSupportsIt(): void
'serializer' => (int) constant(Redis::class . '::SERIALIZER_IGBINARY'),
],
)->validate($this->repository($this->redisStore()), 'Auth user cache');
-
- $this->assertTrue(true);
}
public function testAcceptsMsgpackOnlyInPhpOnlyMode(): void
@@ -201,8 +190,6 @@ public function testAcceptsMsgpackOnlyInPhpOnlyMode(): void
'serializer' => (int) constant(Redis::class . '::SERIALIZER_MSGPACK'),
],
)->validate($this->repository($this->redisStore()), 'Sanctum token cache');
-
- $this->assertTrue(true);
} finally {
if (is_string($previous)) {
ini_set('msgpack.php_only', $previous);
@@ -271,8 +258,6 @@ public function testConnectionOptionsOverrideSharedOptions(): void
sharedOptions: ['serializer' => Redis::SERIALIZER_JSON],
connectionOptions: ['serializer' => Redis::SERIALIZER_PHP],
)->validate($this->repository($this->redisStore()), 'Auth user cache');
-
- $this->assertTrue(true);
}
public function testLastNumericRedisSerializerOptionWinsOverStringOption(): void
@@ -281,8 +266,6 @@ public function testLastNumericRedisSerializerOptionWinsOverStringOption(): void
'serializer' => Redis::SERIALIZER_JSON,
Redis::OPT_SERIALIZER => Redis::SERIALIZER_PHP,
])->validate($this->repository($this->redisStore()), 'Auth user cache');
-
- $this->assertTrue(true);
}
public function testLastStringRedisSerializerOptionWinsOverNumericOption(): void
@@ -327,7 +310,7 @@ private function validator(
*/
private function redisStore(): RedisStore
{
- $redis = Double::for(RedisFactory::class);
+ $redis = Double::for(RedisFactory::class)->strict();
$redis->expects('connection')->never();
return new RedisStore($redis, connection: 'cache');
diff --git a/tests/Cache/PruneStaleTagsCommandTest.php b/tests/Cache/PruneStaleTagsCommandTest.php
index 34d143de7b..f637190b17 100644
--- a/tests/Cache/PruneStaleTagsCommandTest.php
+++ b/tests/Cache/PruneStaleTagsCommandTest.php
@@ -22,7 +22,7 @@ class PruneStaleTagsCommandTest extends TestCase
public function testPruneCallsFlushStaleTagsOnStore(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('flushStaleTags')
->returns([
'tags_scanned' => 10,
@@ -30,11 +30,11 @@ public function testPruneCallsFlushStaleTagsOnStore(): void
'empty_sets_deleted' => 2,
]);
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->expects('getStore')
->returns($store);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->expects('store')
->with(null)
->returns($repository);
@@ -50,7 +50,7 @@ public function testPruneCallsFlushStaleTagsOnStore(): void
public function testPruneUsesSpecifiedStore(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('flushStaleTags')
->returns([
'tags_scanned' => 0,
@@ -58,11 +58,11 @@ public function testPruneUsesSpecifiedStore(): void
'empty_sets_deleted' => 0,
]);
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->expects('getStore')
->returns($store);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->expects('store')
->with('custom-redis')
->returns($repository);
@@ -78,13 +78,13 @@ public function testPruneUsesSpecifiedStore(): void
public function testPruneHandlesNonSupportedStoreGracefully(): void
{
- $nonRedisStore = Double::for(Store::class);
+ $nonRedisStore = Double::for(Store::class)->strict();
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->expects('getStore')
->returns($nonRedisStore);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->expects('store')
->with('file')
->returns($repository);
diff --git a/tests/Cache/Redis/AllTaggedCacheTest.php b/tests/Cache/Redis/AllTaggedCacheTest.php
index 00ab99e286..c0939a2985 100644
--- a/tests/Cache/Redis/AllTaggedCacheTest.php
+++ b/tests/Cache/Redis/AllTaggedCacheTest.php
@@ -261,7 +261,7 @@ public function testManyFiresTaggedManyEvents(): void
->with(["prefix:{$key}profile", "prefix:{$key}missing"])
->returns([serialize('cached'), null]);
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(true);
$dispatcher->allows('dispatch')->resolves(function (object $event) use (&$events): void {
$events[] = $event;
@@ -401,19 +401,15 @@ public function testTouchUpdatesKeyAndTagScores(bool $succeeded): void
$key = hash('xxh128', '_all:tag:users:entries') . ':name';
$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;
- }))
+ ->with(Argument::type('string'), ["prefix:{$key}", 'prefix:_all:tag:users:entries'], Argument::capture($args))
->returns($succeeded);
$store = $this->createStore($connection);
$result = $store->tags(['users'])->touch('name', 60);
$this->assertSame($succeeded, $result);
+ $this->assertSame(60, $args[0]);
+ $this->assertSame($key, $args[2]);
}
public function testTouchWithDatetimeInPastOrZeroSecondsRemovesOldItem(): void
@@ -528,7 +524,7 @@ public function testRememberNormalizesEnumKeyForRedisAndEvents(): void
$connection->client()->expects('exec')->returns([true, 1]);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function (object $event) use (&$captured): void {
@@ -645,7 +641,7 @@ public function testRememberNullableFiresCacheHitWithNullPayloadOnSentinelHit():
->returns(serialize(NullSentinel::VALUE));
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -677,7 +673,7 @@ public function testRememberNullableFiresKeyWrittenWithNullPayloadOnCacheMiss():
$connection->client()->expects('exec')->returns([true, 1]);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -747,7 +743,7 @@ public function testRememberForeverNormalizesEnumKeyForRedisAndEvents(): void
->returns(serialize('cached_settings'));
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function (object $event) use (&$captured): void {
@@ -946,13 +942,13 @@ public function testFlexibleNullableReturnsNullOnFreshSentinelHit(): void
public function testAllTaggedCacheSkipsEventDispatchSeamWithoutListenersAndEntersItWithListeners(): void
{
- $put = Double::for(Put::class);
+ $put = Double::for(Put::class)->strict();
$put->expects('execute')->times(2)->returns(true);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('put')->times(2)->returns($put);
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('allTagOps')->times(2)->returns($operations);
- $tags = Double::for(AllTagSet::class);
+ $tags = Double::for(AllTagSet::class)->strict();
$tags->allows('getNamespace')->returns('namespace');
$tags->allows('tagIds')->returns([]);
$tags->allows('getNames')->returns(['users']);
@@ -967,7 +963,7 @@ protected function event(object $event): void
parent::event($event);
}
};
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(false);
$events->expects('dispatch')->never();
$cache->setEventDispatcher($events);
@@ -1078,10 +1074,10 @@ public function testPutDispatchesTheRepositoryFailureEventWithStoreNameAndTags()
public function testPutDispatchesTheRepositoryFailureEventWhenTheOperationThrows(): void
{
$exception = new RuntimeException('write failed');
- $put = Double::for(Put::class);
+ $put = Double::for(Put::class)->strict();
$put->expects('execute')->throws($exception);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('put')->returns($put);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -1106,10 +1102,10 @@ public function testPutDoesNotDispatchFailureEventWhenTheOperationIsCanceled(boo
if ($cleanupThrows) {
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
- $put = Double::for(Put::class);
+ $put = Double::for(Put::class)->strict();
$put->expects('execute')->throws($cancellation);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('put')->returns($put);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -1128,10 +1124,10 @@ public function testPutManyDispatchesRepositoryFailureEventsWhenTheOperationThro
{
$exception = new RuntimeException('batch write failed');
$values = ['name' => 'John', 'age' => 30];
- $putMany = Double::for(PutMany::class);
+ $putMany = Double::for(PutMany::class)->strict();
$putMany->expects('execute')->throws($exception);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('putMany')->returns($putMany);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -1161,10 +1157,10 @@ public function testPutManyDoesNotDispatchFailureEventsWhenTheOperationIsCancele
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
$values = ['name' => 'John', 'age' => 30];
- $putMany = Double::for(PutMany::class);
+ $putMany = Double::for(PutMany::class)->strict();
$putMany->expects('execute')->throws($cancellation);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('putMany')->returns($putMany);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -1181,10 +1177,10 @@ public function testPutManyDoesNotDispatchFailureEventsWhenTheOperationIsCancele
public function testEmptyPutManyReturnsTrueWithoutOperationOrEvents(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('allTagOps')->never();
- $tags = Double::for(AllTagSet::class);
- $events = Double::for(Dispatcher::class);
+ $tags = Double::for(AllTagSet::class)->strict();
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never();
$events->expects('dispatch')->never();
$tagged = new AllTaggedCache($store, $tags);
@@ -1196,10 +1192,10 @@ public function testEmptyPutManyReturnsTrueWithoutOperationOrEvents(): void
public function testForeverDispatchesTheRepositoryFailureEventWhenTheOperationThrows(): void
{
$exception = new RuntimeException('forever write failed');
- $forever = Double::for(Forever::class);
+ $forever = Double::for(Forever::class)->strict();
$forever->expects('execute')->throws($exception);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('forever')->returns($forever);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -1224,10 +1220,10 @@ public function testForeverDoesNotDispatchFailureEventWhenTheOperationIsCanceled
if ($cleanupThrows) {
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
- $forever = Double::for(Forever::class);
+ $forever = Double::for(Forever::class)->strict();
$forever->expects('execute')->throws($cancellation);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('forever')->returns($forever);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -1309,10 +1305,10 @@ public function testFlushDispatchesTheRepositoryEventsWithStoreNameAndTags(): vo
public function testFlushDispatchesFailureEventWithExactOperationException(): void
{
$exception = new RuntimeException('flush failed');
- $flush = Double::for(Flush::class);
+ $flush = Double::for(Flush::class)->strict();
$flush->expects('execute')->throws($exception);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('flush')->returns($flush);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -1336,10 +1332,10 @@ public function testFlushDoesNotDispatchFailureEventWhenTheOperationIsCanceled(b
if ($cleanupThrows) {
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
- $flush = Double::for(Flush::class);
+ $flush = Double::for(Flush::class)->strict();
$flush->expects('execute')->throws($cancellation);
- $operations = Double::for(AllTagOperations::class);
+ $operations = Double::for(AllTagOperations::class)->strict();
$operations->expects('flush')->returns($flush);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -1361,7 +1357,7 @@ public function testFlushDoesNotDispatchFailureEventWhenTheOperationIsCanceled(b
*/
private function capturingDispatcher(array &$captured): Dispatcher
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(true);
$dispatcher->allows('dispatch')
->resolves(function (object $event) use (&$captured): void {
@@ -1373,10 +1369,10 @@ private function capturingDispatcher(array &$captured): Dispatcher
private function taggedCacheWithOperations(AllTagOperations $operations, array &$captured): AllTaggedCache
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('allTagOps')->returns($operations);
- $tags = Double::for(AllTagSet::class);
+ $tags = Double::for(AllTagSet::class)->strict();
$tags->allows('getNames')->returns(['users']);
$tags->allows('getNamespace')->returns('users');
$tags->allows('tagIds')->returns(['users-id']);
diff --git a/tests/Cache/Redis/AnyTaggedCacheTest.php b/tests/Cache/Redis/AnyTaggedCacheTest.php
index 7f6bcfc3fd..99ad6b4e15 100644
--- a/tests/Cache/Redis/AnyTaggedCacheTest.php
+++ b/tests/Cache/Redis/AnyTaggedCacheTest.php
@@ -242,7 +242,7 @@ public function testPutWithZeroTtlDeletesPlainKey(): void
->returns(1);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function (object $event) use (&$captured): void {
@@ -373,7 +373,7 @@ public function testAddStoresValueIfNotExists(): void
$connection->expects('evalWithShaCache')
->returns(true);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never();
$events->expects('dispatch')->never();
@@ -390,17 +390,14 @@ public function testAddWithNullTtlStoresPermanently(): void
$connection = $this->mockConnection();
$connection->expects('evalWithShaCache')
- ->with(Argument::all(function ($script, $keys, $args): bool {
- $this->assertSame(0, $args[1]);
-
- return true;
- }))
+ ->with(Argument::any(), Argument::any(), Argument::capture($args))
->returns(true);
$store = $this->createStore($connection);
$result = $store->setTagMode('any')->tags(['users'])->add('mykey', 'myvalue', null);
$this->assertTrue($result);
+ $this->assertSame(0, $args[1]);
}
public function testAddWithZeroTtlReturnsFalse(): void
@@ -547,7 +544,7 @@ public function testRememberRetrievesExistingValueFromStore(): void
public function testRememberHandlesIncompleteClassBeforeDispatchingHitEvent(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('get')->with('mykey')->returns(
unserialize(serialize(new stdClass), ['allowed_classes' => false])
);
@@ -558,7 +555,7 @@ public function testRememberHandlesIncompleteClassBeforeDispatchingHitEvent(): v
$sequence[] = ['handler', $key, $class];
});
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function (object $event) use (&$sequence): void {
@@ -613,16 +610,11 @@ public function testRememberNormalizesEnumKeyForRedisAndEvents(): void
->returns(null);
$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;
- }))
+ ->with(Argument::type('string'), Argument::capture($keys), Argument::capture($args))
->returns(true);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function (object $event) use (&$captured): void {
@@ -636,6 +628,9 @@ public function testRememberNormalizesEnumKeyForRedisAndEvents(): void
$result = $tagged->remember(AnyTaggedCacheTestKey::Profile, 60, fn () => 'computed_value');
+ $this->assertSame('prefix:0', $keys[0]);
+ $this->assertSame('0', $args[5]);
+
$this->assertSame('computed_value', $result);
$this->assertSame(
@@ -652,25 +647,25 @@ public function testRememberNormalizesEnumKeyForRedisAndEvents(): void
public function testPutDispatchesTheRepositoryFailureEvent(): void
{
- $put = Double::for(Put::class);
+ $put = Double::for(Put::class)->strict();
$put->expects('execute')
->with('mykey', 'myvalue', 60, ['users'])
->returns(false);
- $operations = Double::for(AnyTagOperations::class);
+ $operations = Double::for(AnyTagOperations::class)->strict();
$operations->expects('put')->returns($put);
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('anyTagOps')->returns($operations);
- $tags = Double::for(AnyTagSet::class);
+ $tags = Double::for(AnyTagSet::class)->strict();
$tags->allows('getNames')->returns(['users']);
$cache = new AnyTaggedCache($store, $tags);
$store->expects('tags')->with(['users'])->returns($cache);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function (object $event) use (&$captured): void {
@@ -691,13 +686,13 @@ public function testPutDispatchesTheRepositoryFailureEvent(): void
public function testAnyTaggedCacheSkipsEventDispatchSeamWithoutListenersAndEntersItWithListeners(): void
{
- $put = Double::for(Put::class);
+ $put = Double::for(Put::class)->strict();
$put->expects('execute')->times(2)->returns(true);
- $operations = Double::for(AnyTagOperations::class);
+ $operations = Double::for(AnyTagOperations::class)->strict();
$operations->expects('put')->times(2)->returns($put);
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('anyTagOps')->times(2)->returns($operations);
- $tags = Double::for(AnyTagSet::class);
+ $tags = Double::for(AnyTagSet::class)->strict();
$tags->allows('getNames')->returns(['users']);
$cache = new class($store, $tags) extends AnyTaggedCache {
@@ -710,7 +705,7 @@ protected function event(object $event): void
parent::event($event);
}
};
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(false);
$events->expects('dispatch')->never();
$cache->setEventDispatcher($events);
@@ -719,7 +714,7 @@ protected function event(object $event): void
$this->assertSame(0, $cache->eventCalls);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->expects('dispatch')->times(2)->resolves(function (object $event) use (&$captured): void {
$captured[] = $event;
@@ -738,12 +733,12 @@ protected function event(object $event): void
public function testPutDispatchesTheRepositoryFailureEventWhenTheOperationThrows(): void
{
$exception = new RuntimeException('write failed');
- $put = Double::for(Put::class);
+ $put = Double::for(Put::class)->strict();
$put->expects('execute')
->with('mykey', 'myvalue', 60, ['users'])
->throws($exception);
- $operations = Double::for(AnyTagOperations::class);
+ $operations = Double::for(AnyTagOperations::class)->strict();
$operations->expects('put')->returns($put);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -768,12 +763,12 @@ public function testPutDoesNotDispatchFailureEventWhenTheOperationIsCanceled(boo
if ($cleanupThrows) {
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
- $put = Double::for(Put::class);
+ $put = Double::for(Put::class)->strict();
$put->expects('execute')
->with('mykey', 'myvalue', 60, ['users'])
->throws($cancellation);
- $operations = Double::for(AnyTagOperations::class);
+ $operations = Double::for(AnyTagOperations::class)->strict();
$operations->expects('put')->returns($put);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -792,12 +787,12 @@ public function testPutManyDispatchesRepositoryFailureEventsWhenTheOperationThro
{
$exception = new RuntimeException('batch write failed');
$values = ['first' => 'one', 'second' => 'two'];
- $putMany = Double::for(PutMany::class);
+ $putMany = Double::for(PutMany::class)->strict();
$putMany->expects('execute')
->with($values, 60, ['users'])
->throws($exception);
- $operations = Double::for(AnyTagOperations::class);
+ $operations = Double::for(AnyTagOperations::class)->strict();
$operations->expects('putMany')->returns($putMany);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -826,12 +821,12 @@ public function testPutManyDoesNotDispatchFailureEventsWhenTheOperationIsCancele
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
$values = ['first' => 'one', 'second' => 'two'];
- $putMany = Double::for(PutMany::class);
+ $putMany = Double::for(PutMany::class)->strict();
$putMany->expects('execute')
->with($values, 60, ['users'])
->throws($cancellation);
- $operations = Double::for(AnyTagOperations::class);
+ $operations = Double::for(AnyTagOperations::class)->strict();
$operations->expects('putMany')->returns($putMany);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -848,10 +843,10 @@ public function testPutManyDoesNotDispatchFailureEventsWhenTheOperationIsCancele
public function testEmptyPutManyReturnsTrueWithoutOperationOrEvents(): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('anyTagOps')->never();
- $tags = Double::for(AnyTagSet::class);
- $events = Double::for(Dispatcher::class);
+ $tags = Double::for(AnyTagSet::class)->strict();
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never();
$events->expects('dispatch')->never();
$tagged = new AnyTaggedCache($store, $tags);
@@ -863,12 +858,12 @@ public function testEmptyPutManyReturnsTrueWithoutOperationOrEvents(): void
public function testForeverDispatchesTheRepositoryFailureEventWhenTheOperationThrows(): void
{
$exception = new RuntimeException('forever write failed');
- $forever = Double::for(Forever::class);
+ $forever = Double::for(Forever::class)->strict();
$forever->expects('execute')
->with('mykey', 'myvalue', ['users'])
->throws($exception);
- $operations = Double::for(AnyTagOperations::class);
+ $operations = Double::for(AnyTagOperations::class)->strict();
$operations->expects('forever')->returns($forever);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -893,12 +888,12 @@ public function testForeverDoesNotDispatchFailureEventWhenTheOperationIsCanceled
if ($cleanupThrows) {
$cancellation = new RuntimeException('Cleanup failed.', previous: $cancellation);
}
- $forever = Double::for(Forever::class);
+ $forever = Double::for(Forever::class)->strict();
$forever->expects('execute')
->with('mykey', 'myvalue', ['users'])
->throws($cancellation);
- $operations = Double::for(AnyTagOperations::class);
+ $operations = Double::for(AnyTagOperations::class)->strict();
$operations->expects('forever')->returns($forever);
$captured = [];
$tagged = $this->taggedCacheWithOperations($operations, $captured);
@@ -977,7 +972,7 @@ public function testRememberNullableFiresCacheHitWithNullPayloadOnSentinelHit():
->returns(serialize(NullSentinel::VALUE));
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -1004,7 +999,7 @@ public function testRememberNullableFiresKeyWrittenWithNullPayloadOnCacheMiss():
$connection->expects('evalWithShaCache')->returns(true);
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function ($event) use (&$captured) {
@@ -1070,7 +1065,7 @@ public function testRememberForeverNormalizesEnumKeyForRedisAndEvents(): void
->returns(serialize('cached_settings'));
$captured = [];
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
$events->allows('dispatch')
->resolves(function (object $event) use (&$captured): void {
@@ -1311,16 +1306,16 @@ public function testFlexibleNullableThrowsBadMethodCallException(): void
private function taggedCacheWithOperations(AnyTagOperations $operations, array &$captured): AnyTaggedCache
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('anyTagOps')->returns($operations);
- $tags = Double::for(AnyTagSet::class);
+ $tags = Double::for(AnyTagSet::class)->strict();
$tags->allows('getNames')->returns(['users']);
$cache = new AnyTaggedCache($store, $tags);
$store->expects('tags')->with(['users'])->returns($cache);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$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 970ebb6bc4..d188999075 100644
--- a/tests/Cache/Redis/Console/BenchmarkCommandTest.php
+++ b/tests/Cache/Redis/Console/BenchmarkCommandTest.php
@@ -79,7 +79,7 @@ public function testSetupFailsGracefullyWhenNoRedisStoreCanBeDetected(): void
'file' => ['driver' => 'file'],
]);
- $cache = Double::for(CacheContract::class);
+ $cache = Double::for(CacheContract::class)->strict();
$cache->expects('store')->never();
$this->app->instance(CacheContract::class, $cache);
@@ -102,7 +102,7 @@ public function testMemoryRecoveryGuidanceIncludesEveryCleanupPattern(): void
'all-tag-pattern:*',
];
- $context = Double::for(BenchmarkContext::class);
+ $context = Double::for(BenchmarkContext::class)->strict();
$context->expects('getCleanupPatterns')->returns($patterns);
$command = $this->createCommand();
@@ -171,7 +171,7 @@ public function testValidTagModeIsPassedThroughAsAnEnum(): void
{
$this->mockFullCacheStore('redis');
$context = $this->mockBenchmarkContext();
- $context->expects('getStoreInstance')->returns(Double::for(RedisStore::class));
+ $context->expects('getStoreInstance')->returns(Double::for(RedisStore::class)->strict());
$command = $this->createFullCommand($context);
$this->assertSame(Command::SUCCESS, $command->run(new ArrayInput([
@@ -287,13 +287,13 @@ public function testSystemInformationFailureIsReportedWithoutStoppingBenchmark()
*/
private function mockCacheStore(string $name): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->expects('getStore')->returns($store);
$repository->expects('get')->with('test')->returns(null);
- $cache = Double::for(CacheContract::class);
+ $cache = Double::for(CacheContract::class)->strict();
$cache->expects('store')->times(2)->with($name)->returns($repository);
$this->app->instance(CacheContract::class, $cache);
@@ -304,10 +304,10 @@ private function mockCacheStore(string $name): void
*/
private function mockFullCacheStore(string $name, ?Throwable $displayException = null): void
{
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
if ($displayException === null) {
- $storeContext = Double::for(StoreContext::class);
+ $storeContext = Double::for(StoreContext::class)->strict();
$storeContext->expects('withConnection')
->returns(['redis_version' => '8.0.0']);
@@ -318,7 +318,7 @@ private function mockFullCacheStore(string $name, ?Throwable $displayException =
$store->expects('getTagMode')->never();
}
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
if ($displayException === null) {
$repository->expects('getStore')->times(2)->returns($store);
@@ -339,7 +339,7 @@ private function mockFullCacheStore(string $name, ?Throwable $displayException =
$repository->expects('get')->with('test')->returns(null);
- $cacheManager = Double::for(CacheContract::class);
+ $cacheManager = Double::for(CacheContract::class)->strict();
$cacheManager->expects('store')->times(3)->with($name)->returns($repository);
$this->app->instance(CacheContract::class, $cacheManager);
@@ -350,7 +350,7 @@ private function mockFullCacheStore(string $name, ?Throwable $displayException =
*/
private function mockBenchmarkContext(?Throwable $cleanupException = null): BenchmarkContext
{
- $context = Double::for(BenchmarkContext::class);
+ $context = Double::for(BenchmarkContext::class)->strict();
$context->allows('getCleanupPatterns')->returns(['cache:_bench:*']);
$cleanup = $context->expects('cleanup');
diff --git a/tests/Cache/Redis/Console/Doctor/Checks/CleanupVerificationCheckTest.php b/tests/Cache/Redis/Console/Doctor/Checks/CleanupVerificationCheckTest.php
index 3658a2b0d6..f431c3d7ca 100644
--- a/tests/Cache/Redis/Console/Doctor/Checks/CleanupVerificationCheckTest.php
+++ b/tests/Cache/Redis/Console/Doctor/Checks/CleanupVerificationCheckTest.php
@@ -21,8 +21,8 @@ class CleanupVerificationCheckTest extends TestCase
public function testVerificationScansLogicalPatternsThroughTheClusterAwareHelper(): void
{
- $connection = Double::for(PhpRedisClusterConnection::class);
- $store = Double::for(RedisStore::class);
+ $connection = Double::for(PhpRedisClusterConnection::class)->strict();
+ $store = Double::for(RedisStore::class)->strict();
$store->allows('getTagMode')->returns(TagMode::All);
$context = new DoctorContext(
cache: new Repository($store),
diff --git a/tests/Cache/Redis/Console/DoctorCommandTest.php b/tests/Cache/Redis/Console/DoctorCommandTest.php
index 4189aaa509..37ba737e89 100644
--- a/tests/Cache/Redis/Console/DoctorCommandTest.php
+++ b/tests/Cache/Redis/Console/DoctorCommandTest.php
@@ -329,20 +329,20 @@ public function testSystemInformationErrorIsVisibleAndDoesNotStopDiagnostics():
config()->set('cache.default', 'redis');
$displayException = new Error('system information failed');
$connection = $this->mockConnection()->shouldTransform(false);
- $storeContext = Double::for(StoreContext::class);
+ $storeContext = Double::for(StoreContext::class)->strict();
$storeContext->expects('withConnection')
->resolves(fn (callable $callback): mixed => $callback($connection));
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->expects('getContext')->returns($storeContext);
$store->expects('getTagMode')->returns(TagMode::Any);
$store->expects('getPrefix')->returns('cache:');
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->expects('getStore')->returns($store);
$storeCalls = 0;
- $cacheManager = Double::for(CacheContract::class);
+ $cacheManager = Double::for(CacheContract::class)->strict();
$cacheManager->expects('store')
->times(2)
->with('redis')
@@ -373,13 +373,13 @@ public function testSystemInformationErrorIsVisibleAndDoesNotStopDiagnostics():
public function testDoctorFailsForNonRedisStore(): void
{
- $nonRedisStore = Double::for(Store::class);
+ $nonRedisStore = Double::for(Store::class)->strict();
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->allows('getStore')
->returns($nonRedisStore);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->allows('store')
->with('file')
->returns($repository);
@@ -396,7 +396,7 @@ public function testDoctorFailsForNonRedisStore(): void
public function testDoctorDetectsRedisStoreFromConfig(): void
{
// Set up config with a redis store
- $config = Double::for(ConfigRepository::class);
+ $config = Double::for(ConfigRepository::class)->strict();
$config->allows('array')
->with('cache.stores')
->returns([
@@ -413,7 +413,7 @@ public function testDoctorDetectsRedisStoreFromConfig(): void
$this->app->instance('config', $config);
// Mock Redis store
- $context = Double::for(StoreContext::class);
+ $context = Double::for(StoreContext::class)->strict();
$context->allows('withConnection')
->resolves(function (callable $callback): mixed {
$connection = $this->mockConnection()->shouldTransform(false);
@@ -421,15 +421,15 @@ public function testDoctorDetectsRedisStoreFromConfig(): void
return $callback($connection);
});
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->allows('getTagMode')->returns(TagMode::Any);
$store->allows('getContext')->returns($context);
$store->allows('getPrefix')->returns('cache:');
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->allows('getStore')->returns($store);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->allows('store')
->with('redis')
->returns($repository);
@@ -459,7 +459,7 @@ public function testDoctorUsesZeroNamedStore(): void
return;
}
- $config = Double::for(ConfigRepository::class);
+ $config = Double::for(ConfigRepository::class)->strict();
$config->allows('string')
->with('cache.default')
->returns('file');
@@ -470,7 +470,7 @@ public function testDoctorUsesZeroNamedStore(): void
$this->app->instance('config', $config);
// Mock Redis store
- $context = Double::for(StoreContext::class);
+ $context = Double::for(StoreContext::class)->strict();
$context->allows('withConnection')
->resolves(function (callable $callback): mixed {
$connection = $this->mockConnection()->shouldTransform(false);
@@ -478,15 +478,15 @@ public function testDoctorUsesZeroNamedStore(): void
return $callback($connection);
});
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->allows('getTagMode')->returns(TagMode::All);
$store->allows('getContext')->returns($context);
$store->allows('getPrefix')->returns('cache:');
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->allows('getStore')->returns($store);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->allows('store')
->with('0')
->returns($repository);
@@ -518,7 +518,7 @@ protected function runCleanupVerification(DoctorContext $context): void
public function testDoctorRunsChecksWhileRedisConnectionIsBorrowed(): void
{
- $config = Double::for(ConfigRepository::class);
+ $config = Double::for(ConfigRepository::class)->strict();
$config->allows('string')
->with('cache.default')
->returns('redis');
@@ -535,7 +535,7 @@ public function testDoctorRunsChecksWhileRedisConnectionIsBorrowed(): void
->with('server')
->returns(['redis_version' => '7.0.0']);
- $context = Double::for(StoreContext::class);
+ $context = Double::for(StoreContext::class)->strict();
$context->expects('withConnection')
->times(2)
->resolves(function (callable $callback) use (&$borrowedConnection, $connection): mixed {
@@ -548,15 +548,15 @@ public function testDoctorRunsChecksWhileRedisConnectionIsBorrowed(): void
}
});
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->allows('getTagMode')->returns(TagMode::Any);
$store->allows('getContext')->returns($context);
$store->allows('getPrefix')->returns('cache:');
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->allows('getStore')->returns($store);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->allows('store')
->with('redis')
->returns($repository);
@@ -604,7 +604,7 @@ protected function cleanup(DoctorContext $context, bool $silent = false): void
public function testDoctorDisplaysTagMode(): void
{
- $config = Double::for(ConfigRepository::class);
+ $config = Double::for(ConfigRepository::class)->strict();
$config->allows('string')
->with('cache.default')
->returns('redis');
@@ -615,7 +615,7 @@ public function testDoctorDisplaysTagMode(): void
$this->app->instance('config', $config);
// Mock Redis store with 'all' mode
- $context = Double::for(StoreContext::class);
+ $context = Double::for(StoreContext::class)->strict();
$context->allows('withConnection')
->resolves(function (callable $callback): mixed {
$connection = $this->mockConnection()->shouldTransform(false);
@@ -623,15 +623,15 @@ public function testDoctorDisplaysTagMode(): void
return $callback($connection);
});
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->allows('getTagMode')->returns(TagMode::All);
$store->allows('getContext')->returns($context);
$store->allows('getPrefix')->returns('cache:');
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->allows('getStore')->returns($store);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->allows('store')
->with('redis')
->returns($repository);
@@ -665,7 +665,7 @@ protected function runCleanupVerification(DoctorContext $context): void
public function testDoctorFailsWhenNoRedisStoreDetected(): void
{
// Set up config with NO redis stores
- $config = Double::for(ConfigRepository::class);
+ $config = Double::for(ConfigRepository::class)->strict();
$config->allows('array')
->with('cache.stores')
->returns([
@@ -690,7 +690,7 @@ public function testDoctorFailsWhenNoRedisStoreDetected(): void
public function testDoctorDisplaysSystemInformation(): void
{
- $config = Double::for(ConfigRepository::class);
+ $config = Double::for(ConfigRepository::class)->strict();
$config->allows('array')
->with('cache.stores')
->returns([
@@ -705,7 +705,7 @@ public function testDoctorDisplaysSystemInformation(): void
$this->app->instance('config', $config);
- $context = Double::for(StoreContext::class);
+ $context = Double::for(StoreContext::class)->strict();
$context->allows('withConnection')
->resolves(function (callable $callback): mixed {
$connection = $this->mockConnection()->shouldTransform(false);
@@ -713,15 +713,15 @@ public function testDoctorDisplaysSystemInformation(): void
return $callback($connection);
});
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->allows('getTagMode')->returns(TagMode::Any);
$store->allows('getContext')->returns($context);
$store->allows('getPrefix')->returns('cache:');
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->allows('getStore')->returns($store);
- $cacheManager = Double::for(CacheManager::class);
+ $cacheManager = Double::for(CacheManager::class)->strict();
$cacheManager->allows('store')
->with('redis')
->returns($repository);
@@ -753,7 +753,7 @@ private function createCleanupContext(
?Throwable $registryException = null,
int $cleanupInvocations = 1,
): DoctorContext {
- $taggedCache = Double::for(TaggedCache::class);
+ $taggedCache = Double::for(TaggedCache::class)->strict();
$tagFlushCalls = 0;
$taggedCache->expects('flush')
->times(self::CLEANUP_TEST_TAG_COUNT * $cleanupInvocations)
@@ -767,7 +767,7 @@ private function createCleanupContext(
return true;
});
- $repository = Double::for(Repository::class);
+ $repository = Double::for(Repository::class)->strict();
$repository->expects('tags')
->times(self::CLEANUP_TEST_TAG_COUNT * $cleanupInvocations)
->returns($taggedCache);
@@ -796,12 +796,12 @@ private function createCleanupContext(
$connection->client()->expects('del')->never();
}
- $storeContext = Double::for(StoreContext::class);
+ $storeContext = Double::for(StoreContext::class)->strict();
$storeContext->allows('registryKey')->returns('cache:_any:tag_registry');
$storeContext->allows('withConnection')
->resolves(fn (callable $callback): mixed => $callback($connection));
- $store = Double::for(RedisStore::class);
+ $store = Double::for(RedisStore::class)->strict();
$store->allows('getContext')->returns($storeContext);
$store->allows('getTagMode')->returns(TagMode::Any);
$store->allows('getPrefix')->returns('cache:');
@@ -822,7 +822,7 @@ private function bindDoctorContext(DoctorContext $context): void
{
$context->cache->expects('getStore')->returns($context->store);
- $cacheManager = Double::for(CacheContract::class);
+ $cacheManager = Double::for(CacheContract::class)->strict();
$cacheManager->expects('store')->with('redis')->returns($context->cache);
$this->app->instance(CacheContract::class, $cacheManager);
}
diff --git a/tests/Cache/Redis/Operations/AllTag/FlushTest.php b/tests/Cache/Redis/Operations/AllTag/FlushTest.php
index 9b661e88a1..ff1fb7898f 100644
--- a/tests/Cache/Redis/Operations/AllTag/FlushTest.php
+++ b/tests/Cache/Redis/Operations/AllTag/FlushTest.php
@@ -26,7 +26,7 @@ public function testFlushDeletesCacheEntriesAndScannedMemberships(): void
$connection = $this->mockConnection();
// Mock GetEntries to return cache keys
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:users:entries'])
->returns(new LazyCollection(['key1', 'key2']));
@@ -45,7 +45,7 @@ public function testFlushWithMultipleTagsOnlyRemovesEntriesFromTheirOwnTag(): vo
{
$connection = $this->mockConnection();
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:people:entries'])
->returns(new LazyCollection(['person-1', 'person-2']));
@@ -76,7 +76,7 @@ public function testFlushWithNoEntriesDoesNotDeleteTagSets(): void
$connection = $this->mockConnection();
// Mock GetEntries to return empty collection
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:users:entries'])
->returns(new LazyCollection([]));
@@ -101,7 +101,7 @@ public function testFlushChunksLargeEntrySets(): void
}
// Mock GetEntries to return many cache keys
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:users:entries'])
->returns(new LazyCollection($entries));
@@ -152,7 +152,7 @@ public function testFlushReleasesScanConnectionsBeforeCheckingOutEachDeletionChu
}
$active = false;
- $proxy = Double::for(RedisProxy::class);
+ $proxy = Double::for(RedisProxy::class)->strict();
$proxy->expects('isCluster')->returns(false);
$proxy->expects('withConnection')
->times(3)
@@ -168,7 +168,7 @@ public function testFlushReleasesScanConnectionsBeforeCheckingOutEachDeletionChu
}
});
- $redis = Double::for(RedisFactory::class);
+ $redis = Double::for(RedisFactory::class)->strict();
$redis->expects('connection')
->times(4)
->with('default')
@@ -199,7 +199,7 @@ public function testFlushUsesCorrectPrefix(): void
$connection = $this->mockConnection();
// Mock GetEntries to return cache keys
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:users:entries'])
->returns(new LazyCollection(['mykey']));
@@ -218,7 +218,7 @@ public function testFlushWithEmptyTagIds(): void
{
$connection = $this->mockConnection();
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')->never();
$connection->client()->expects('del')->never();
@@ -235,7 +235,7 @@ public function testFlushTagKeyFormat(): void
$connection = $this->mockConnection();
// Mock GetEntries
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->returns(new LazyCollection(['key']));
@@ -254,7 +254,7 @@ public function testFlushInClusterModeUsesSequentialDel(): void
[$store, $client] = $this->createClusterStore();
// Mock GetEntries to return cache keys
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:users:entries'])
->returns(new LazyCollection(['key1', 'key2']));
@@ -282,7 +282,7 @@ public function testFlushInClusterModeChunksLargeSets(): void
}
// Mock GetEntries to return many cache keys
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:users:entries'])
->returns(new LazyCollection($entries));
@@ -319,7 +319,7 @@ public function testFlushInClusterModeWithMultipleTags(): void
{
[$store, $client] = $this->createClusterStore();
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:users:entries'])
->returns(new LazyCollection(['user_key1', 'shared_key']));
@@ -349,7 +349,7 @@ public function testFlushInClusterModeWithNoEntries(): void
[$store, $client] = $this->createClusterStore();
// Mock GetEntries to return empty collection
- $getEntries = Double::for(GetEntries::class);
+ $getEntries = Double::for(GetEntries::class)->strict();
$getEntries->expects('execute')
->with(['_all:tag:users:entries'])
->returns(new LazyCollection([]));
diff --git a/tests/Cache/Redis/Operations/AllTag/GetEntriesTest.php b/tests/Cache/Redis/Operations/AllTag/GetEntriesTest.php
index cd2883e210..93b63c6ec5 100644
--- a/tests/Cache/Redis/Operations/AllTag/GetEntriesTest.php
+++ b/tests/Cache/Redis/Operations/AllTag/GetEntriesTest.php
@@ -163,13 +163,13 @@ public function testGetEntriesContinuesAfterAnEmptyNonterminalPageAndChecksOutPe
]);
$connection = (new PhpRedisConnectionStub)->setActiveConnection($client)->shouldTransform(false);
- $proxy = Double::for(RedisProxy::class);
+ $proxy = Double::for(RedisProxy::class)->strict();
$proxy->expects('withConnection')
->times(2)
->with(Argument::type('callable'), false)
->resolves(fn (callable $callback) => $callback($connection));
- $redis = Double::for(RedisFactory::class);
+ $redis = Double::for(RedisFactory::class)->strict();
$redis->expects('connection')
->times(2)
->with('default')
diff --git a/tests/Cache/Redis/Operations/AnyTag/AddTest.php b/tests/Cache/Redis/Operations/AnyTag/AddTest.php
index c864f1a583..b31654111d 100644
--- a/tests/Cache/Redis/Operations/AnyTag/AddTest.php
+++ b/tests/Cache/Redis/Operations/AnyTag/AddTest.php
@@ -16,21 +16,18 @@ public function testAddWithTagsReturnsTrueWhenKeyAdded(): void
// evalWithShaCache returns true (key added)
$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);
- $this->assertCount(2, $keys);
- $this->assertSame(60, $args[1]);
-
- return true;
- }))
+ ->with(Argument::capture($script), Argument::capture($keys), Argument::capture($args))
->returns(true);
$redis = $this->createStore($connection);
$redis->setTagMode('any');
$result = $redis->anyTagOps()->add()->execute('foo', 'bar', 60, ['users']);
$this->assertTrue($result);
+ $this->assertStringContainsString('SET', $script);
+ $this->assertStringContainsString('NX', $script);
+ $this->assertStringContainsString("redis.call('HSETEX', tagHash, 'EX', ttl, 'FIELDS', 1, rawKey, '1')", $script);
+ $this->assertCount(2, $keys);
+ $this->assertSame(60, $args[1]);
}
public function testAddWithTagsReturnsFalseWhenKeyExists(): void
@@ -85,36 +82,28 @@ public function testAddNormalizesExpiringMetadataInClusterMode(): void
->with('prefix:_any:tag:users:entries', ['foo' => '1'], ['EX' => 1])
->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;
- }))
+ ->with('prefix:_any:tag:registry', ['GT'], Argument::capture($expiresAt), 'users')
->returns(1);
$this->assertTrue($redis->anyTagOps()->add()->execute('foo', 'bar', -60, ['users']));
+ $this->assertIsInt($expiresAt);
+ $this->assertGreaterThan($startedAt, $expiresAt);
}
public function testAddWithoutTtlUsesPermanentLuaBranch(): void
{
$connection = $this->mockConnection();
$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);
- $this->assertCount(2, $keys);
- $this->assertSame(0, $args[1]);
-
- return true;
- }))
+ ->with(Argument::capture($script), Argument::capture($keys), Argument::capture($args))
->returns(true);
$redis = $this->createStore($connection, tagMode: 'any');
$this->assertTrue($redis->anyTagOps()->add()->execute('foo', 'bar', null, ['users']));
+ $this->assertStringContainsString("redis.call('SET', key, val, 'NX')", $script);
+ $this->assertStringContainsString('if not permanent then', $script);
+ $this->assertStringContainsString((string) StoreContext::MAX_EXPIRY, $script);
+ $this->assertCount(2, $keys);
+ $this->assertSame(0, $args[1]);
}
}
diff --git a/tests/Cache/Redis/Operations/AnyTag/DecrementTest.php b/tests/Cache/Redis/Operations/AnyTag/DecrementTest.php
index 087ef28525..7ae5e102f4 100644
--- a/tests/Cache/Redis/Operations/AnyTag/DecrementTest.php
+++ b/tests/Cache/Redis/Operations/AnyTag/DecrementTest.php
@@ -18,20 +18,17 @@ public function testDecrementWithTagsReturnsNewValue(): void
$connection = $this->mockConnection();
$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;
- }))
+ ->with(Argument::capture($script), Argument::capture($keys), Argument::any())
->returns(5); // New value after decrement
$redis = $this->createStore($connection);
$redis->setTagMode('any');
$result = $redis->anyTagOps()->decrement()->execute('counter', 5, ['stats']);
$this->assertSame(5, $result);
+ $this->assertStringContainsString('DECRBY', $script);
+ $this->assertStringContainsString('TTL', $script);
+ $this->assertStringContainsString((string) StoreContext::MAX_EXPIRY, $script);
+ $this->assertCount(2, $keys);
}
public function testDecrementWithTagsUpdatesMetadataAfterAClusterCounterSucceeds(): void
diff --git a/tests/Cache/Redis/Operations/AnyTag/FlushTest.php b/tests/Cache/Redis/Operations/AnyTag/FlushTest.php
index 869a415c6f..82f5f67bc7 100644
--- a/tests/Cache/Redis/Operations/AnyTag/FlushTest.php
+++ b/tests/Cache/Redis/Operations/AnyTag/FlushTest.php
@@ -23,7 +23,7 @@ public function testFlushDeletesCacheEntriesReverseIndexesAndScannedFields(): vo
$connection = $this->mockConnection();
// Mock GetTaggedKeys to return cache keys
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')
->with('users')
->returns($this->arrayToGenerator(['key1', 'key2']));
@@ -50,7 +50,7 @@ public function testFlushWithMultipleTagsOnlyRemovesKeysFromTheirOwnTag(): void
{
$connection = $this->mockConnection();
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')
->with('users')
->returns($this->arrayToGenerator(['shared_key', 'user_only']));
@@ -87,7 +87,7 @@ public function testFlushWithNoEntriesChecksForEmptyTags(): void
$connection = $this->mockConnection();
// Mock GetTaggedKeys to return empty
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')
->with('users')
->returns($this->arrayToGenerator([]));
@@ -109,7 +109,7 @@ public function testFlushWithNoTagsDoesNotSendCommands(): void
{
$connection = $this->mockConnection();
$connection->expects('evalWithShaCache')->never();
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')->never();
$store = $this->createStore($connection);
$operation = new Flush($store->getContext(), $getTaggedKeys, new RemoveEmptyTags($store->getContext()));
@@ -121,7 +121,7 @@ public function testFlushUsesCorrectPrefix(): void
{
$connection = $this->mockConnection();
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')
->with('users')
->returns($this->arrayToGenerator(['mykey']));
@@ -145,7 +145,7 @@ public function testFlushClusterModeUsesSequentialCommands(): void
{
[$store, $client] = $this->createClusterStore(tagMode: 'any');
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')
->with('users')
->returns($this->arrayToGenerator(['key1', 'key2']));
@@ -204,7 +204,7 @@ public function testFlushClusterModeWithMultipleTags(): void
{
[$store, $client] = $this->createClusterStore(tagMode: 'any');
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')
->with('users')
->returns($this->arrayToGenerator(['user_key', 'shared_key']));
@@ -257,7 +257,7 @@ public function testFlushViaRedisStoreMethod(): void
public function testClusterFlushPreservesRegistrationWhenTheHashWasRepopulated(): void
{
[$store, $client] = $this->createClusterStore(tagMode: 'any');
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')->with('users')->returns($this->arrayToGenerator([]));
$client->expects('hlen')->with('prefix:_any:tag:users:entries')->returns(1);
@@ -271,7 +271,7 @@ public function testClusterFlushPreservesRegistrationWhenTheHashWasRepopulated()
public function testClusterFlushRestoresRegistrationWhenAWriterRacesWithDeregistration(): void
{
[$store, $client] = $this->createClusterStore(tagMode: 'any');
- $getTaggedKeys = Double::for(GetTaggedKeys::class);
+ $getTaggedKeys = Double::for(GetTaggedKeys::class)->strict();
$getTaggedKeys->expects('execute')->with('users')->returns($this->arrayToGenerator([]));
$cleanup = [];
diff --git a/tests/Cache/Redis/Operations/AnyTag/ForeverTest.php b/tests/Cache/Redis/Operations/AnyTag/ForeverTest.php
index 44663d5058..1e212060be 100644
--- a/tests/Cache/Redis/Operations/AnyTag/ForeverTest.php
+++ b/tests/Cache/Redis/Operations/AnyTag/ForeverTest.php
@@ -18,20 +18,16 @@ public function testForeverWithTagsUsesLuaScript(): void
$connection = $this->mockConnection();
$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);
- $this->assertStringContainsString((string) StoreContext::MAX_EXPIRY, $script);
- $this->assertCount(2, $keys);
-
- return true;
- }))
+ ->with(Argument::capture($script), Argument::capture($keys), Argument::any())
->returns(true);
$redis = $this->createStore($connection);
$redis->setTagMode('any');
$result = $redis->anyTagOps()->forever()->execute('foo', 'bar', ['users']);
$this->assertTrue($result);
+ $this->assertStringContainsString("redis.call('SET'", $script);
+ $this->assertStringContainsString('HSET', $script);
+ $this->assertStringContainsString((string) StoreContext::MAX_EXPIRY, $script);
+ $this->assertCount(2, $keys);
}
}
diff --git a/tests/Cache/Redis/Operations/AnyTag/IncrementTest.php b/tests/Cache/Redis/Operations/AnyTag/IncrementTest.php
index aba44eefec..980c12fe9d 100644
--- a/tests/Cache/Redis/Operations/AnyTag/IncrementTest.php
+++ b/tests/Cache/Redis/Operations/AnyTag/IncrementTest.php
@@ -19,20 +19,17 @@ public function testIncrementWithTagsReturnsNewValue(): void
// Lua script returns the incremented value
$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;
- }))
+ ->with(Argument::capture($script), Argument::capture($keys), Argument::any())
->returns(15); // New value after increment
$redis = $this->createStore($connection);
$redis->setTagMode('any');
$result = $redis->anyTagOps()->increment()->execute('counter', 5, ['stats']);
$this->assertSame(15, $result);
+ $this->assertStringContainsString('INCRBY', $script);
+ $this->assertStringContainsString('TTL', $script);
+ $this->assertStringContainsString((string) StoreContext::MAX_EXPIRY, $script);
+ $this->assertCount(2, $keys);
}
public function testIncrementWithTagsUpdatesMetadataAfterAClusterCounterSucceeds(): void
diff --git a/tests/Cache/Redis/Operations/AnyTag/PutManyTest.php b/tests/Cache/Redis/Operations/AnyTag/PutManyTest.php
index c22de72cef..c176ee8e93 100644
--- a/tests/Cache/Redis/Operations/AnyTag/PutManyTest.php
+++ b/tests/Cache/Redis/Operations/AnyTag/PutManyTest.php
@@ -97,18 +97,13 @@ public function testPutManyNormalizesExpiringMetadata(): void
->with('prefix:_any:tag:users:entries', ['foo' => '1'], ['EX' => 1])
->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;
- }))
+ ->with('prefix:_any:tag:registry', ['GT'], Argument::capture($expiresAt), 'users')
->returns($connection->client());
$redis = $this->createStore($connection, tagMode: 'any');
$this->assertTrue($redis->anyTagOps()->putMany()->execute(['foo' => 'bar'], -60, ['users']));
+ $this->assertIsInt($expiresAt);
+ $this->assertGreaterThan($startedAt, $expiresAt);
}
}
diff --git a/tests/Cache/Redis/Operations/AnyTag/PutTest.php b/tests/Cache/Redis/Operations/AnyTag/PutTest.php
index b789381a59..492147d824 100644
--- a/tests/Cache/Redis/Operations/AnyTag/PutTest.php
+++ b/tests/Cache/Redis/Operations/AnyTag/PutTest.php
@@ -18,23 +18,19 @@ public function testPutWithTagsUsesLuaScriptInStandardMode(): void
// Standard mode uses Lua script via evalWithShaCache
$connection->expects('evalWithShaCache')
- ->with(Argument::all(function ($script, $keys, $args) {
- // Verify Lua script contains expected commands
- $this->assertStringContainsString('SETEX', $script);
- $this->assertStringContainsString('HSETEX', $script);
- $this->assertStringContainsString('ZADD', $script);
- $this->assertStringContainsString('SMEMBERS', $script);
- // 2 keys: cache key + reverse index key
- $this->assertCount(2, $keys);
-
- return true;
- }))
+ ->with(Argument::capture($script), Argument::capture($keys), Argument::any())
->returns(true);
$redis = $this->createStore($connection);
$redis->setTagMode('any');
$result = $redis->anyTagOps()->put()->execute('foo', 'bar', 60, ['users', 'posts']);
$this->assertTrue($result);
+ $this->assertStringContainsString('SETEX', $script);
+ $this->assertStringContainsString('HSETEX', $script);
+ $this->assertStringContainsString('ZADD', $script);
+ $this->assertStringContainsString('SMEMBERS', $script);
+
+ $this->assertCount(2, $keys);
}
public function testPutWithTagsUsesSequentialCommandsInClusterMode(): void
@@ -78,17 +74,12 @@ public function testPutNormalizesExpiringMetadataInClusterMode(): void
->with('prefix:_any:tag:users:entries', ['foo' => '1'], ['EX' => 1])
->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;
- }))
+ ->with('prefix:_any:tag:registry', ['GT'], Argument::capture($expiresAt), 'users')
->returns(1);
$this->assertTrue($redis->anyTagOps()->put()->execute('foo', 'bar', -60, ['users']));
+ $this->assertIsInt($expiresAt);
+ $this->assertGreaterThan($startedAt, $expiresAt);
}
public function testPutWithTagsHandlesEmptyTags(): void
@@ -109,17 +100,13 @@ public function testPutWithTagsWithNumericValue(): void
$connection = $this->mockConnection();
$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;
- }))
+ ->with(Argument::any(), Argument::any(), Argument::capture($args))
->returns(true);
$redis = $this->createStore($connection);
$redis->setTagMode('any');
$result = $redis->anyTagOps()->put()->execute('foo', 42, 60, ['numbers']);
$this->assertTrue($result);
+ $this->assertIsString($args[0]);
}
}
diff --git a/tests/Cache/Redis/Operations/FlushTest.php b/tests/Cache/Redis/Operations/FlushTest.php
index e1b57c80f2..11e1e729ca 100644
--- a/tests/Cache/Redis/Operations/FlushTest.php
+++ b/tests/Cache/Redis/Operations/FlushTest.php
@@ -29,7 +29,7 @@ public function testFlushEnablesTransformsAndPropagatesFailure(): void
{
$connection = $this->mockConnection();
$connection->client()->expects('flushdb')->returns(false);
- $context = Double::for(StoreContext::class);
+ $context = Double::for(StoreContext::class)->strict();
$context->expects('withConnection')
->with(Argument::type('callable'), true)
->resolves(fn (callable $callback) => $callback($connection->shouldTransform(true)));
diff --git a/tests/Cache/Redis/Operations/PutManyTest.php b/tests/Cache/Redis/Operations/PutManyTest.php
index 9edf8d3437..5331d6fe62 100644
--- a/tests/Cache/Redis/Operations/PutManyTest.php
+++ b/tests/Cache/Redis/Operations/PutManyTest.php
@@ -19,19 +19,11 @@ public function testPutManyUsesLuaScriptInStandardMode(): void
// Standard mode (not cluster) uses Lua script via evalWithShaCache
$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
- $this->assertCount(3, $keys);
- $this->assertSame('prefix:foo', $keys[0]);
- $this->assertSame('prefix:baz', $keys[1]);
- $this->assertSame('prefix:bar', $keys[2]);
- // Args: [ttl, val1, val2, val3]
- $this->assertSame([60, serialize('bar'), serialize('qux'), serialize('norf')], $args);
-
- return true;
- }))
+ ->with(
+ Argument::capture($script),
+ ['prefix:foo', 'prefix:baz', 'prefix:bar'],
+ [60, serialize('bar'), serialize('qux'), serialize('norf')],
+ )
->returns(true);
$redis = $this->createStore($connection);
@@ -41,6 +33,7 @@ public function testPutManyUsesLuaScriptInStandardMode(): void
'bar' => 'norf',
], 60);
$this->assertTrue($result);
+ $this->assertStringContainsString('SETEX', $script);
}
public function testPutManyUsesSequentialCommandsInClusterMode(): void
@@ -103,15 +96,12 @@ public function testPutManyEnforcesMinimumTtlOfOne(): void
$connection = $this->mockConnection();
$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;
- }))
+ ->with(Argument::any(), Argument::any(), Argument::capture($args))
->returns(true);
$redis = $this->createStore($connection);
$result = $redis->putMany(['foo' => 'bar'], 0);
$this->assertTrue($result);
+ $this->assertSame(1, $args[0]);
}
}
diff --git a/tests/Cache/Redis/RedisCacheTestCase.php b/tests/Cache/Redis/RedisCacheTestCase.php
index 331372e814..9d1d92478b 100644
--- a/tests/Cache/Redis/RedisCacheTestCase.php
+++ b/tests/Cache/Redis/RedisCacheTestCase.php
@@ -74,7 +74,7 @@ protected function createRedisFactory(
RedisConnection $connection,
string $connectionName = 'default'
): RedisFactory&DoubleInterface {
- $redisProxy = Double::for(RedisProxy::class);
+ $redisProxy = Double::for(RedisProxy::class)->strict();
$redisProxy->allows('withConnection')
->resolves(static fn (callable $callback, bool $transform = true): mixed => $callback($connection->shouldTransform($transform)));
$redisProxy->allows('isCluster')->returns($connection->isCluster());
diff --git a/tests/Cache/Redis/RedisStoreTest.php b/tests/Cache/Redis/RedisStoreTest.php
index 5a0a75b3cc..9c81b330eb 100644
--- a/tests/Cache/Redis/RedisStoreTest.php
+++ b/tests/Cache/Redis/RedisStoreTest.php
@@ -86,11 +86,11 @@ public function testSetConnectionClearsCachedInstances(): void
$connection2 = $this->mockConnection();
$connection2->client()->expects('get')->with('prefix:foo')->returns(serialize('value2'));
- $redisProxy1 = Double::for(RedisProxy::class);
+ $redisProxy1 = Double::for(RedisProxy::class)->strict();
$redisProxy1->expects('withConnection')
->resolves(fn (callable $callback) => $callback($connection1->shouldTransform(false)));
- $redisProxy2 = Double::for(RedisProxy::class);
+ $redisProxy2 = Double::for(RedisProxy::class)->strict();
$redisProxy2->expects('withConnection')
->resolves(fn (callable $callback) => $callback($connection2->shouldTransform(false)));
@@ -335,7 +335,7 @@ public function testForgetUsesAnyTagMetadataOperationInAnyMode(): void
public function testLockReturnsRedisLockInstance(): void
{
- $redisProxy = Double::for(RedisProxy::class);
+ $redisProxy = Double::for(RedisProxy::class)->strict();
$redisFactory = Double::for(Redis::class)->strict();
$redisFactory->allows('connection')->with('default')->returns($redisProxy);
@@ -352,7 +352,7 @@ public function testLockReturnsRedisLockInstance(): void
public function testLockWithOwner(): void
{
- $redisProxy = Double::for(RedisProxy::class);
+ $redisProxy = Double::for(RedisProxy::class)->strict();
$redisFactory = Double::for(Redis::class)->strict();
$redisFactory->allows('connection')->with('default')->returns($redisProxy);
@@ -369,7 +369,7 @@ public function testLockWithOwner(): void
public function testRestoreLockReturnsRedisLockInstance(): void
{
- $redisProxy = Double::for(RedisProxy::class);
+ $redisProxy = Double::for(RedisProxy::class)->strict();
$redisFactory = Double::for(Redis::class)->strict();
$redisFactory->allows('connection')->with('default')->returns($redisProxy);
@@ -396,8 +396,8 @@ public function testSetLockConnectionReturnsSelf(): void
public function testLockUsesLockConnectionWhenSet(): void
{
- $redisProxy = Double::for(RedisProxy::class);
- $lockProxy = Double::for(RedisProxy::class);
+ $redisProxy = Double::for(RedisProxy::class)->strict();
+ $lockProxy = Double::for(RedisProxy::class)->strict();
$redisFactory = Double::for(Redis::class)->strict();
$redisFactory->allows('connection')->with('default')->returns($redisProxy);
$redisFactory->allows('connection')->with('locks')->returns($lockProxy);
@@ -429,7 +429,7 @@ public function testGetRedisReturnsRedis(): void
public function testConnectionReturnsRedisProxy(): void
{
- $redisProxy = Double::for(RedisProxy::class);
+ $redisProxy = Double::for(RedisProxy::class)->strict();
$redisFactory = Double::for(Redis::class)->strict();
$redisFactory->allows('connection')->with('default')->returns($redisProxy);
diff --git a/tests/Cache/Redis/Support/StoreContextTest.php b/tests/Cache/Redis/Support/StoreContextTest.php
index a68ac5245c..f4b8c1b259 100644
--- a/tests/Cache/Redis/Support/StoreContextTest.php
+++ b/tests/Cache/Redis/Support/StoreContextTest.php
@@ -81,7 +81,7 @@ public function testExpirationScoreNeverPrecedesRequestedLifetime(): void
public function testWithConnectionExecutesCallbackAndReturnsResult(): void
{
- $connection = Double::for(PhpRedisConnection::class);
+ $connection = Double::for(PhpRedisConnection::class)->strict();
$context = $this->createContextWithRedisFactory('default', function ($callback) use ($connection) {
return $callback($connection);
});
@@ -97,7 +97,7 @@ public function testWithConnectionExecutesCallbackAndReturnsResult(): void
public function testWithConnectionCanEnableLaravelStyleTransforms(): void
{
- $connection = Double::for(PhpRedisConnection::class);
+ $connection = Double::for(PhpRedisConnection::class)->strict();
$transform = null;
$context = $this->createContextWithRedisFactory(
'default',
@@ -117,7 +117,7 @@ function ($callback, bool $shouldTransform) use ($connection, &$transform) {
public function testWithConnectionPropagatesExceptions(): void
{
$context = $this->createContextWithRedisFactory('default', function ($callback) {
- return $callback(Double::for(PhpRedisConnection::class));
+ return $callback(Double::for(PhpRedisConnection::class)->strict());
});
$this->expectException(RuntimeException::class);
@@ -131,7 +131,7 @@ public function testWithConnectionPropagatesExceptions(): void
public function testIsClusterReturnsTrueForRedisCluster(): void
{
$context = $this->createContextWithRedisFactory('default', function ($callback) {
- return $callback(Double::for(PhpRedisConnection::class));
+ return $callback(Double::for(PhpRedisConnection::class)->strict());
}, isCluster: true);
$this->assertTrue($context->isCluster());
@@ -140,7 +140,7 @@ public function testIsClusterReturnsTrueForRedisCluster(): void
public function testIsClusterReturnsFalseForRegularRedis(): void
{
$context = $this->createContextWithRedisFactory('default', function ($callback) {
- return $callback(Double::for(PhpRedisConnection::class));
+ return $callback(Double::for(PhpRedisConnection::class)->strict());
}, isCluster: false);
$this->assertFalse($context->isCluster());
diff --git a/tests/Cache/RegisterSwooleMaintenanceTimersTest.php b/tests/Cache/RegisterSwooleMaintenanceTimersTest.php
index 9d4895a44d..45c7b45722 100644
--- a/tests/Cache/RegisterSwooleMaintenanceTimersTest.php
+++ b/tests/Cache/RegisterSwooleMaintenanceTimersTest.php
@@ -55,7 +55,7 @@ public function testRegistersEvictionAndIntervalRefreshTimersForEachSwooleStoreO
public function testDoesNotRegisterTimersOnOtherWorkers(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$timer = new FakeCoordinatorTimer;
(new RegisterSwooleMaintenanceTimers($container->instance(), $timer, $this->config([])))
@@ -67,7 +67,7 @@ public function testDoesNotRegisterTimersOnOtherWorkers(): void
public function testDoesNotRegisterTimersOnTaskWorkers(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$timer = new FakeCoordinatorTimer;
(new RegisterSwooleMaintenanceTimers($container->instance(), $timer, $this->config([])))
@@ -87,17 +87,17 @@ public function testTimerCallbacksCallTheConfiguredStore(): void
],
]);
- $store = Double::for(SwooleStore::class);
+ $store = Double::for(SwooleStore::class)->strict();
$store->expects('evictRecords');
$store->expects('refreshIntervalCaches');
- $repository = Double::for(CacheRepository::class);
+ $repository = Double::for(CacheRepository::class)->strict();
$repository->expects('getStore')->returns($store);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('fast')->returns($repository);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$timer = new FakeCoordinatorTimer;
@@ -123,15 +123,15 @@ public function testResolvesEveryStoreBeforeRegisteringTimers(): void
'interval_refresh_interval' => 1000,
],
]);
- $firstRepository = Double::for(CacheRepository::class);
- $firstRepository->expects('getStore')->returns(Double::for(SwooleStore::class));
+ $firstRepository = Double::for(CacheRepository::class)->strict();
+ $firstRepository->expects('getStore')->returns(Double::for(SwooleStore::class)->strict());
$failure = new RuntimeException('Store resolution failed.');
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('first')->returns($firstRepository);
$cache->expects('store')->with('second')->throws($failure);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->times(2)->with('cache')->returns($cache);
$timer = new FakeCoordinatorTimer;
@@ -247,7 +247,7 @@ public function testRejectsInvalidIntervalsBeforeTimerRegistration(
...$intervalConfig,
],
]);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$timer = new FakeCoordinatorTimer;
try {
@@ -319,7 +319,7 @@ public function testRejectsAnInvalidLaterStoreBeforeRegisteringEarlierTimers():
'interval_refresh_interval' => 0,
],
]);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$timer = new FakeCoordinatorTimer;
try {
@@ -355,15 +355,15 @@ private function config(array $stores): Repository
*/
private function containerWithSwooleStores(string ...$names): Container
{
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
foreach ($names as $name) {
- $repository = Double::for(CacheRepository::class);
- $repository->expects('getStore')->returns(Double::for(SwooleStore::class));
+ $repository = Double::for(CacheRepository::class)->strict();
+ $repository->expects('getStore')->returns(Double::for(SwooleStore::class)->strict());
$cache->expects('store')->with($name)->returns($repository);
}
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->times(count($names))->with('cache')->returns($cache);
return $container->instance();
@@ -371,7 +371,7 @@ private function containerWithSwooleStores(string ...$names): Container
private function workerEvent(int $workerId, bool $taskworker = false): AfterWorkerStart
{
- $server = Double::for(SwooleServer::class);
+ $server = Double::for(SwooleServer::class)->strict();
$server->taskworker = $taskworker;
return new AfterWorkerStart($server, $workerId);
diff --git a/tests/ConnectionPool/ConnectionPoolTest.php b/tests/ConnectionPool/ConnectionPoolTest.php
index 69342cef4b..522795d0d3 100644
--- a/tests/ConnectionPool/ConnectionPoolTest.php
+++ b/tests/ConnectionPool/ConnectionPoolTest.php
@@ -214,7 +214,7 @@ public function testWarmPoolDoesNotScheduleMaintenanceUntilStarted(): void
public function testCloseContinuesAfterMonitorCleanupFails(): void
{
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('error')
->with(Argument::satisfies(static fn (string $message): bool => str_contains($message, 'monitor cleanup failed')));
$container = $this->createContainer();
@@ -224,7 +224,7 @@ public function testCloseContinuesAfterMonitorCleanupFails(): void
$pool->replaceChannel($channel);
$connection = $pool->borrow();
$pool->release($connection);
- $timer = Double::for(Timer::class);
+ $timer = Double::for(Timer::class)->strict();
$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);
@@ -687,7 +687,7 @@ static function () use (&$connections): Connection {
public function testThrowingIdleCheckIsReportedDestroyedAndFreesCapacity(): void
{
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('error')
->with(Argument::satisfies(static fn (string $message): bool => str_contains($message, 'check failed')));
$container = $this->createContainer();
@@ -742,7 +742,7 @@ public function testCanceledIdleCheckDisposesOnceAndPreservesCancellation(?strin
default => null,
};
$container = $this->createContainer();
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
if ($cleanupFailure === 'failed') {
$logger->expects('error')->with((string) $secondary);
@@ -823,13 +823,13 @@ public function testHealthyIdleConnectionIsDisposedWhenPoolClosesDuringCheck():
public function testUsageTrackerFailureIsReportedWithoutLosingBorrow(): void
{
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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 = Double::for(UsageTracker::class);
+ $tracker = Double::for(UsageTracker::class)->strict();
$tracker->expects('recordBorrow')->throws(new RuntimeException('recording failed'));
$pool->useUsageTracker($tracker);
@@ -889,7 +889,7 @@ public function shouldTrimExcessIdle(): bool
public function testUsageTrackerFactoryRunsOnceAfterSubclassConstruction(): void
{
- $tracker = Double::for(UsageTracker::class);
+ $tracker = Double::for(UsageTracker::class)->strict();
$tracker->expects('recordBorrow')->times(2);
$tracker->expects('shouldTrimExcessIdle')->times(2)->returns(false);
$pool = new UsageTrackerPool($this->createContainer(), static fn () => $tracker);
@@ -1014,7 +1014,7 @@ public function trimExcessIdle(): void
$this->close();
}
};
- $tracker = Double::for(UsageTracker::class);
+ $tracker = Double::for(UsageTracker::class)->strict();
$tracker->expects('recordBorrow');
$tracker->expects('shouldTrimExcessIdle')->returns(true);
$pool->useUsageTracker($tracker);
diff --git a/tests/ConnectionPool/ConnectionTest.php b/tests/ConnectionPool/ConnectionTest.php
index a670d564de..6ad0f9c520 100644
--- a/tests/ConnectionPool/ConnectionTest.php
+++ b/tests/ConnectionPool/ConnectionTest.php
@@ -33,14 +33,14 @@ class ConnectionTest extends TestCase
public function testGetConnectionReturnsTheActiveConnection(): void
{
- $container = Double::for(ContainerContract::class, override: true);
- $logger = Double::for(StdoutLoggerInterface::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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));
+ $connection = new ActiveConnectionStub($container->instance(), Double::for(ConnectionPool::class)->strict());
$this->assertSame($connection, $connection->getConnection());
}
@@ -48,15 +48,15 @@ public function testGetConnectionReturnsTheActiveConnection(): void
public function testGetConnectionDoesNotRetryFailure(string $exceptionClass): void
{
$failure = new $exceptionClass('acquisition failed');
- $container = Double::for(ContainerContract::class, override: true);
- $logger = Double::for(StdoutLoggerInterface::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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->instance(),
- Double::for(ConnectionPool::class),
+ Double::for(ConnectionPool::class)->strict(),
static fn (): mixed => throw $failure,
);
$caught = null;
@@ -82,15 +82,15 @@ public static function acquisitionFailures(): array
public function testGetConnectionDoesNotRetryCancellation(): void
{
$cancellation = new CanceledException('connection canceled');
- $container = Double::for(ContainerContract::class, override: true);
- $logger = Double::for(StdoutLoggerInterface::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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->instance(),
- Double::for(ConnectionPool::class),
+ Double::for(ConnectionPool::class)->strict(),
static fn (): mixed => throw $cancellation,
);
@@ -107,16 +107,16 @@ public function testGetConnectionDoesNotRetryCancellation(): void
public function testConnectionReleasingEvent(): void
{
$assert = 0;
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$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));
+ $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)->strict());
$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->instance(), $pool = Double::for(ConnectionPool::class));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$pool->allows('release')->returns(null);
$pool->allows('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]]));
@@ -131,12 +131,12 @@ public function testConnectionReleasingEvent(): void
public function testReleaseUsesTheCurrentEventDispatcher(): void
{
$container = new Container;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->with(ConnectionReleasing::class)->returns(true);
$dispatcher->expects('dispatch')->never();
$container->instance('events', $dispatcher);
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]]));
$connection = new ActiveConnectionStub($container, $pool);
$pool->expects('release')->with(Argument::same($connection));
@@ -154,13 +154,13 @@ public function testReleaseListenerCancellationStillReturnsTheConnectionOnce(boo
{
$cancellation = new CanceledException('listener canceled');
$failure = $cleanupThrows ? new RuntimeException('Listener cleanup failed.', previous: $cancellation) : $cancellation;
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$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));
+ $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)->strict());
$dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true);
$dispatcher->expects('dispatch')->throws($failure);
- $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]]));
$pool->expects('release')->with(Argument::same($connection));
@@ -179,13 +179,13 @@ public function testReleaseListenerCancellationRemainsPrimaryOverCleanupCancella
$cancellation = new CanceledException('listener canceled');
$failure = $cleanupThrows ? new RuntimeException('Listener cleanup failed.', previous: $cancellation) : $cancellation;
$cleanupCancellation = new CanceledException('release canceled');
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$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));
+ $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)->strict());
$dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true);
$dispatcher->expects('dispatch')->throws($failure);
- $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]]));
$pool->expects('release')->with(Argument::same($connection))->throws($cleanupCancellation);
@@ -200,16 +200,16 @@ public function testReleaseListenerCancellationRemainsPrimaryOverCleanupCancella
public function testCancellationWhileLoggingAListenerFailureStillReturnsTheConnectionOnce(): void
{
$cancellation = new CanceledException('logging canceled');
- $container = Double::for(ContainerContract::class, override: true);
- $logger = Double::for(StdoutLoggerInterface::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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));
+ $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)->strict());
$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));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]]));
$pool->expects('release')->with(Argument::same($connection));
@@ -223,17 +223,17 @@ public function testCancellationWhileLoggingAListenerFailureStillReturnsTheConne
public function testOrdinaryReleaseListenerFailureIsLoggedAndTheConnectionIsReturned(): void
{
- $container = Double::for(ContainerContract::class, override: true);
- $logger = Double::for(StdoutLoggerInterface::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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));
+ $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)->strict());
$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));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]]));
$pool->expects('release')->with(Argument::same($connection));
@@ -245,16 +245,16 @@ public function testLoggerFailureStillReleasesTheConnectionAndPreservesFailurePr
{
$loggingFailure = new RuntimeException('logger failed');
$cleanupFailure = $cleanupExceptionClass === null ? null : new $cleanupExceptionClass('cleanup failed');
- $container = Double::for(ContainerContract::class, override: true);
- $logger = Double::for(StdoutLoggerInterface::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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));
+ $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)->strict());
$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));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$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) {
@@ -285,16 +285,16 @@ public static function cleanupFailures(): array
public function testReleaseCancellationSurvivesCleanupAndReportingFailures(string $reportingExceptionClass): void
{
$cancellation = new CanceledException('listener canceled');
- $container = Double::for(ContainerContract::class, override: true);
- $logger = Double::for(StdoutLoggerInterface::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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));
+ $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)->strict());
$dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(true);
$dispatcher->expects('dispatch')->throws($cancellation);
- $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]]));
$pool->expects('release')->with(Argument::same($connection))->throws(new RuntimeException('cleanup failed'));
$caught = null;
@@ -318,13 +318,13 @@ public static function secondaryReportingFailures(): array
public function testConfiguredReleaseEventIsNotDispatchedWithoutListeners(): void
{
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$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));
+ $container->allows('make')->with('events')->returns($dispatcher = Double::for(Dispatcher::class)->strict());
$dispatcher->expects('hasListeners')->with(ConnectionReleasing::class)->returns(false);
$dispatcher->expects('dispatch')->never();
- $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$pool->expects('getOptions')->returns(PoolOptions::fromArray(['events' => [ConnectionReleasing::class]]));
$pool->expects('release')->with(Argument::same($connection));
@@ -333,12 +333,12 @@ public function testConfiguredReleaseEventIsNotDispatchedWithoutListeners(): voi
public function testDontHaveEvents(): void
{
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('has')->with(StdoutLoggerInterface::class)->returns(false);
$container->expects('bound')->never()->with('events');
$container->expects('make')->never()->with('events');
- $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class));
+ $connection = new ActiveConnectionStub($container->instance(), $pool = Double::for(ConnectionPool::class)->strict());
$pool->allows('release')->returns(null);
$pool->allows('getOptions')->returns(PoolOptions::fromArray([]));
@@ -347,10 +347,10 @@ public function testDontHaveEvents(): void
public function testDiscardDelegatesToOwningPool(): void
{
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('has')->with(StdoutLoggerInterface::class)->returns(false);
$container->allows('bound')->with('events')->returns(false);
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$connection = new ActiveConnectionStub($container->instance(), $pool);
$pool->expects('discard')->with(Argument::same($connection));
@@ -359,10 +359,10 @@ public function testDiscardDelegatesToOwningPool(): void
public function testCheckDoesNotResetActivityTimestamp(): void
{
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('has')->with(StdoutLoggerInterface::class)->returns(false);
$container->allows('bound')->with('events')->returns(false);
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->expects('release');
$pool->expects('getOptions')->times(2)->returns(PoolOptions::fromArray(['max_idle_time' => 60.0]));
$connection = new ActiveConnectionStub($container->instance(), $pool);
@@ -376,10 +376,10 @@ public function testCheckDoesNotResetActivityTimestamp(): void
public function testNullIdleTimeoutKeepsAnUnusedConnectionValid(): void
{
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('has')->with(StdoutLoggerInterface::class)->returns(false);
$container->allows('bound')->with('events')->returns(false);
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->expects('getOptions')->returns(PoolOptions::fromArray(['max_idle_time' => null]));
$connection = new ActiveConnectionStub($container->instance(), $pool);
diff --git a/tests/ConnectionPool/Fixtures/FooPool.php b/tests/ConnectionPool/Fixtures/FooPool.php
index 465f914617..7a3a6c61ef 100644
--- a/tests/ConnectionPool/Fixtures/FooPool.php
+++ b/tests/ConnectionPool/Fixtures/FooPool.php
@@ -12,6 +12,6 @@ class FooPool extends ConnectionPool
{
protected function createConnection(): Connection
{
- return Double::for(Connection::class);
+ return Double::for(Connection::class)->strict();
}
}
diff --git a/tests/ConnectionPool/IdleConnectionMonitorTest.php b/tests/ConnectionPool/IdleConnectionMonitorTest.php
index 69dced08de..61676354ca 100644
--- a/tests/ConnectionPool/IdleConnectionMonitorTest.php
+++ b/tests/ConnectionPool/IdleConnectionMonitorTest.php
@@ -26,7 +26,7 @@ class IdleConnectionMonitorTest extends TestCase
public function testMonitorChecksIdleConnectionsAtItsInterval(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('isClosed')->returns(false);
$pool->expects('checkIdleConnection')->times(minimum: 1);
$timerCount = Timer::stats()['num'];
@@ -46,9 +46,9 @@ public function testMonitorChecksIdleConnectionsAtItsInterval(): void
public function testStartAndStopAreIdempotentAndPermitRestart(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('isClosed')->returns(false);
- $timer = Double::for(Timer::class);
+ $timer = Double::for(Timer::class)->strict();
$timer->expects('tick')->with(5.0, Argument::type('callable'))->times(2)->returns(1, 2);
$timer->expects('clear')->with(1);
$timer->expects('clear')->with(2);
@@ -64,9 +64,9 @@ public function testStartAndStopAreIdempotentAndPermitRestart(): void
public function testClosedPoolCannotStartAMonitor(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('isClosed')->returns(true);
- $timer = Double::for(Timer::class);
+ $timer = Double::for(Timer::class)->strict();
$timer->expects('tick')->never();
(new IdleConnectionMonitor($pool, 1.0, $timer))->start();
@@ -74,7 +74,7 @@ public function testClosedPoolCannotStartAMonitor(): void
public function testSynchronousStartupReentryDoesNotCreateAnotherTimer(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('isClosed')->returns(false);
$monitor = new IdleConnectionMonitor($pool, 60.0);
$timerCount = Timer::stats()['num'];
@@ -117,10 +117,10 @@ public function testCloseDuringStartupClearsTheUnpublishedTimer(): void
public function testStartupFailureAllowsTheNextStart(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('isClosed')->returns(false);
$failure = new RuntimeException('timer creation failed');
- $timer = Double::for(Timer::class);
+ $timer = Double::for(Timer::class)->strict();
$attempts = 0;
$timer->expects('tick')->with(1.0, Argument::type('callable'))->times(2)->resolves(
static function () use (&$attempts, $failure): int {
@@ -148,7 +148,7 @@ static function () use (&$attempts, $failure): int {
public function testWorkerExitStopsWithoutCheckingIdleConnections(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('isClosed')->returns(false);
$pool->expects('checkIdleConnection')->never();
$monitor = new IdleConnectionMonitor($pool, 60.0);
@@ -166,7 +166,7 @@ public function testWorkerExitStopsWithoutCheckingIdleConnections(): void
public function testEachMonitorOwnsItsTimer(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('isClosed')->returns(false);
$first = new IdleConnectionMonitor($pool, 60.0);
$second = new IdleConnectionMonitor($pool, 60.0);
@@ -208,7 +208,7 @@ public function testEachTickChecksOneIdleConnectionInFifoOrder(): void
$pool->release($first);
$pool->release($second);
$callback = null;
- $timer = Double::for(Timer::class);
+ $timer = Double::for(Timer::class)->strict();
$timer->expects('tick')->with(1.0, Argument::type('callable'))->resolves(
static function (float $interval, callable $check) use (&$callback): int {
$callback = $check;
@@ -239,7 +239,7 @@ public function testInvalidIntervalsAreRejected(float $interval): void
{
$this->expectException(InvalidArgumentException::class);
- new IdleConnectionMonitor(Double::for(ConnectionPool::class), $interval);
+ new IdleConnectionMonitor(Double::for(ConnectionPool::class)->strict(), $interval);
}
public static function invalidIntervals(): array
diff --git a/tests/ConnectionPool/KeepaliveConnectionTest.php b/tests/ConnectionPool/KeepaliveConnectionTest.php
index e1787cdc82..33344a2ddc 100644
--- a/tests/ConnectionPool/KeepaliveConnectionTest.php
+++ b/tests/ConnectionPool/KeepaliveConnectionTest.php
@@ -65,7 +65,7 @@ public function testConnectionConstruct(): void
public function testConnectionAcceptsPoolContract(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$connection = new KeepaliveConnectionStub(
new Container,
$pool,
@@ -401,7 +401,7 @@ public function testSupersededHolderCannotRequeueOrRefreshTheReplacement(): void
public function testConcurrentReconnectKeepsOneSocketAndOneTimer(?Throwable $closeFailure): void
{
$container = new Container;
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$container->instance(StdoutLoggerInterface::class, $logger);
if ($closeFailure !== null && ! $closeFailure instanceof CanceledException) {
@@ -765,14 +765,14 @@ public function testReconnectPublishesIfAnEarlierWinnerHasAlreadyClosed(): void
public function testHeartbeatCancellationRemainsPrimaryWhenProtocolCloseFails(): void
{
$container = new Container;
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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 = Double::for(Timer::class);
+ $timer = Double::for(Timer::class)->strict();
$timer->expects('tick')->resolves(
function (float $interval, callable $heartbeat) use (&$callback): int {
$callback = $heartbeat;
@@ -808,7 +808,7 @@ function (float $interval, callable $heartbeat) use (&$callback): int {
public function testLateHeartbeatFailureDoesNotCloseTheReplacement(Throwable $failure): void
{
$container = new Container;
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$container->instance(StdoutLoggerInterface::class, $logger);
if ($failure instanceof CanceledException) {
@@ -827,7 +827,7 @@ public function testLateHeartbeatFailureDoesNotCloseTheReplacement(Throwable $fa
$connection->createCallback = static fn () => new stdClass;
$callbacks = [];
$cleared = [];
- $timer = Double::for(Timer::class);
+ $timer = Double::for(Timer::class)->strict();
$timer->expects('tick')->times(2)->resolves(
function (float $interval, callable $heartbeat) use (&$callbacks): int {
$callbacks[] = $heartbeat;
diff --git a/tests/Console/CacheCommandMutexTest.php b/tests/Console/CacheCommandMutexTest.php
index f095f69315..0e690da3cb 100644
--- a/tests/Console/CacheCommandMutexTest.php
+++ b/tests/Console/CacheCommandMutexTest.php
@@ -35,8 +35,8 @@ protected function setUp(): void
{
parent::setUp();
- $this->cacheFactory = Double::for(Factory::class);
- $this->cacheRepository = Double::for(Repository::class);
+ $this->cacheFactory = Double::for(Factory::class)->strict();
+ $this->cacheRepository = Double::for(Repository::class)->strict();
$this->mutex = new CacheCommandMutex($this->cacheFactory);
$this->command = new class extends Command {
protected ?string $name = 'command-name';
@@ -134,7 +134,7 @@ public function testCanCreateMutexWithCustomConnectionWithLockProvider(): void
private function mockUsingCacheStore(?string $store = null): void
{
$this->cacheFactory->expects('store')->with($store)->returns($this->cacheRepository);
- $this->cacheRepository->expects('getStore')->returns(Double::for(Store::class));
+ $this->cacheRepository->expects('getStore')->returns(Double::for(Store::class)->strict());
}
public function testCommandMutexNameWithoutIsolatedMutexNameMethod(): void
diff --git a/tests/Console/CommandMutexTest.php b/tests/Console/CommandMutexTest.php
index 0046af83ff..4163fa3802 100644
--- a/tests/Console/CommandMutexTest.php
+++ b/tests/Console/CommandMutexTest.php
@@ -113,8 +113,8 @@ public function testCanRunCommandAgainNonAutomated(): void
public function testCommandReleasesTheExactMutexInstanceThatItAcquired(): void
{
- $acquiredMutex = Double::for(CommandMutex::class);
- $unusedMutex = Double::for(CommandMutex::class);
+ $acquiredMutex = Double::for(CommandMutex::class)->strict();
+ $unusedMutex = Double::for(CommandMutex::class)->strict();
$resolutions = 0;
$acquiredMutex->expects('create')->with(Argument::same($this->command))->returns(true);
@@ -337,7 +337,7 @@ function (AfterExecute $event) use (&$observed): void {
*/
protected function mockCommandMutex(): CommandMutex&DoubleInterface
{
- $commandMutex = Double::for(CommandMutex::class);
+ $commandMutex = Double::for(CommandMutex::class)->strict();
$this->app->instance(CommandMutex::class, $commandMutex);
diff --git a/tests/Console/CommandTest.php b/tests/Console/CommandTest.php
index ff84213bbf..bac048457e 100644
--- a/tests/Console/CommandTest.php
+++ b/tests/Console/CommandTest.php
@@ -64,8 +64,8 @@ public function testHookFlags(): void
public function testExceptionPropagatesFromExecute(): void
{
- $output = Double::for(OutputStyle::class);
- $application = Double::for(ConsoleApplication::class);
+ $output = Double::for(OutputStyle::class)->strict();
+ $application = Double::for(ConsoleApplication::class)->strict();
$application->allows('getHelperSet');
$instance = new FooExceptionCommand('foo');
@@ -73,7 +73,7 @@ public function testExceptionPropagatesFromExecute(): void
$command = new ClassInvoker($instance);
$command->setApplication($application);
$command->setOutput($output);
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->allows('getOption')->returns(true);
$this->expectException(RuntimeException::class);
@@ -82,10 +82,10 @@ public function testExceptionPropagatesFromExecute(): void
public function testExitCodeFromExitExceptionAndNormalCommand(): void
{
- $output = Double::for(OutputStyle::class);
- $application = Double::for(ConsoleApplication::class);
+ $output = Double::for(OutputStyle::class)->strict();
+ $application = Double::for(ConsoleApplication::class)->strict();
$application->allows('getHelperSet');
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->allows('getOption')->returns(true);
/** @var FooExitCommand $command */
@@ -109,10 +109,10 @@ public function testExitCodeFromExitExceptionAndNormalCommand(): void
public function testSetUpTraits(): void
{
- $output = Double::for(OutputStyle::class);
- $application = Double::for(ConsoleApplication::class);
+ $output = Double::for(OutputStyle::class)->strict();
+ $application = Double::for(ConsoleApplication::class)->strict();
$application->allows('getHelperSet');
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->allows('getOption')->returns(false);
$command = new FooTraitCommand;
@@ -125,7 +125,7 @@ public function testSetUpTraits(): void
public function testSignalHandlersAreRemovedWhenTraitSetupFails(): void
{
$command = new CommandTestFailingTraitSetupCommand;
- $registry = Double::for(SignalRegistry::class);
+ $registry = Double::for(SignalRegistry::class)->strict();
$registry->expects('register')->with(Argument::same($command), SIGTERM, Argument::type('callable'));
$registry->expects('unregister')->with(Argument::same($command), null);
@@ -239,30 +239,30 @@ public function handle(): never
public function testProhibitableCommand(): void
{
- $application = Double::for(ConsoleApplication::class);
+ $application = Double::for(ConsoleApplication::class)->strict();
$application->allows('getHelperSet');
- $output = Double::for(OutputStyle::class);
+ $output = Double::for(OutputStyle::class)->strict();
$instance = new FooProhibitableCommand;
$instance->setHypervel($this->app);
$command = new ClassInvoker($instance);
$command->setApplication($application);
$command->setOutput($output);
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->allows('getOption')->returns(true);
$result = $command->execute($input, $output);
$this->assertSame(FooProhibitableCommand::SUCCESS, $result);
FooProhibitableCommand::prohibit(true);
- $output = Double::for(OutputStyle::class);
+ $output = new OutputStyle(new ArrayInput([]), new NullOutput);
$instance = new FooProhibitableCommand;
$instance->setHypervel($this->app);
$instance->setApplication($application);
$instance->setOutput($output);
(fn () => $this->components = new Factory($output))->call($instance);
$command = new ClassInvoker($instance);
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->allows('getOption')->returns(true);
$result = $command->execute($input, $output);
$this->assertSame(FooProhibitableCommand::FAILURE, $result);
@@ -323,7 +323,7 @@ public function handle(): void
}
};
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$hypervel = $application->instance();
$command->setHypervel($hypervel);
@@ -335,7 +335,7 @@ public function handle(): void
$application->allows('bound')->returns(false);
$application->expects('call')->with([$command, 'handle'])->resolves(function () use ($command, $application, $hypervel): void {
- $commandCalled = Double::for(Command::class);
+ $commandCalled = Double::for(Command::class)->strict();
$application->expects('make')->with(Command::class)->returns($commandCalled);
@@ -505,7 +505,7 @@ public function testTheInputSetterOverwrite(): void
public function testTheOutputSetterOverwrite(): void
{
- $output = Double::for(OutputStyle::class);
+ $output = Double::for(OutputStyle::class)->strict();
$output->expects('writeln')->with('foo', Argument::remaining());
$command = new CommandTestStubCommand;
diff --git a/tests/Console/Concerns/InteractsWithIOTest.php b/tests/Console/Concerns/InteractsWithIOTest.php
index d03fbb981e..fad9021e9d 100755
--- a/tests/Console/Concerns/InteractsWithIOTest.php
+++ b/tests/Console/Concerns/InteractsWithIOTest.php
@@ -99,7 +99,7 @@ public function testWithProgressBarSupportsGeneratorsWithoutPrecounting(): void
public function testAskWithCompletionAcceptsGeneratorValues(): void
{
$command = new CommandInteractsWithIO;
- $output = Double::for(OutputStyle::class);
+ $output = Double::for(OutputStyle::class)->strict();
$command->setOutput($output);
$choices = (function () {
@@ -108,14 +108,12 @@ public function testAskWithCompletionAcceptsGeneratorValues(): void
})();
$output->expects('askQuestion')
- ->with(Argument::satisfies(function (Question $question): bool {
- $this->assertSame(['alpha', 'bravo'], $question->getAutocompleterValues());
-
- return true;
- }))
+ ->with(Argument::capture($question))
->returns('bravo');
$this->assertSame('bravo', $command->anticipate('Choose', $choices));
+ $this->assertInstanceOf(Question::class, $question);
+ $this->assertSame(['alpha', 'bravo'], $question->getAutocompleterValues());
}
}
diff --git a/tests/Console/ConfiguresPromptsTest.php b/tests/Console/ConfiguresPromptsTest.php
index dbb919aaa4..484395cafe 100644
--- a/tests/Console/ConfiguresPromptsTest.php
+++ b/tests/Console/ConfiguresPromptsTest.php
@@ -448,18 +448,16 @@ public function testAutoCompleteFallbackNormalizesClosureCollectionOptions(): vo
$value . '/Models/User.php',
$value . '/Http/Kernel.php',
])),
- fn ($components) => $components
- ->expects('askWithCompletion')
- ->with('File?', Argument::satisfies(function ($completion) {
- $this->assertIsCallable($completion);
- $this->assertSame(['app/Models/User.php', 'app/Http/Kernel.php'], $completion('app'));
-
- return true;
- }), null)
- ->returns('app/Models/User.php')
+ function ($components) use (&$completion): void {
+ $components->expects('askWithCompletion')
+ ->with('File?', Argument::capture($completion), null)
+ ->returns('app/Models/User.php');
+ }
);
$this->assertSame('app/Models/User.php', $answer);
+ $this->assertIsCallable($completion);
+ $this->assertSame(['app/Models/User.php', 'app/Http/Kernel.php'], $completion('app'));
}
public function testSuggestFallbackNormalizesClosureCollectionOptions(): void
@@ -471,18 +469,16 @@ public function testSuggestFallbackNormalizesClosureCollectionOptions(): void
$value . ' Taylor',
$value . ' Jess',
])),
- fn ($components) => $components
- ->expects('askWithCompletion')
- ->with('Name?', Argument::satisfies(function ($completion) {
- $this->assertIsCallable($completion);
- $this->assertSame(['T Taylor', 'T Jess'], $completion('T'));
-
- return true;
- }), null)
- ->returns('T Taylor')
+ function ($components) use (&$completion): void {
+ $components->expects('askWithCompletion')
+ ->with('Name?', Argument::capture($completion), null)
+ ->returns('T Taylor');
+ }
);
$this->assertSame('T Taylor', $answer);
+ $this->assertIsCallable($completion);
+ $this->assertSame(['T Taylor', 'T Jess'], $completion('T'));
}
#[DataProvider('datatableDataProvider')]
@@ -676,14 +672,14 @@ public function handle(): void
*/
protected function runCommand(Command $command, Closure $expectations, bool $runningUnitTests = false): int
{
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$command->setHypervel($application->instance());
$input = new ArrayInput([]);
$output = new NullOutput;
$outputStyle = new OutputStyle($input, $output);
$application->expects('make')->with(OutputStyle::class, Argument::remaining())->returns($outputStyle);
- $factory = Double::for(ComponentsFactory::class);
+ $factory = Double::for(ComponentsFactory::class)->strict();
$application->expects('make')->with(Factory::class, Argument::remaining())->returns($factory);
$application->allows('bound')->returns(false);
$application->allows('runningUnitTests')->returns($runningUnitTests);
diff --git a/tests/Console/ConsoleApplicationDeferredCallbacksTest.php b/tests/Console/ConsoleApplicationDeferredCallbacksTest.php
index bfc04c68c0..67c5f32c47 100644
--- a/tests/Console/ConsoleApplicationDeferredCallbacksTest.php
+++ b/tests/Console/ConsoleApplicationDeferredCallbacksTest.php
@@ -53,7 +53,7 @@ public function testCoroutineCommandDrainsAfterObserversAndMutexCleanup(): void
{
$application = $this->createConsoleApplication();
$calls = [];
- $mutex = Double::for(CommandMutex::class);
+ $mutex = Double::for(CommandMutex::class)->strict();
$mutex->expects('create')->resolves(function () use (&$calls): bool {
$calls[] = 'mutex-created';
diff --git a/tests/Console/ConsoleApplicationTest.php b/tests/Console/ConsoleApplicationTest.php
index 768c190a02..dfd8181429 100644
--- a/tests/Console/ConsoleApplicationTest.php
+++ b/tests/Console/ConsoleApplicationTest.php
@@ -231,7 +231,7 @@ public function testAddSetsHypervelInstance(): void
{
$artisan = $this->getMockConsole(['addToParent']);
- $command = Double::for(Command::class);
+ $command = Double::for(Command::class)->strict();
$command->expects('setHypervel')->with(Argument::type(Application::class));
$artisan->expects($this->once())->method('addToParent')->with($command)->willReturn($command);
@@ -579,7 +579,7 @@ private function getCommandLoader(ConsoleApplication $app): ?ContainerCommandLoa
*/
private function getMockConsole(array $methods): ConsoleApplication
{
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->allows('version')->returns('1.0');
$events = new EventsDispatcher;
diff --git a/tests/Console/Events/EventsTest.php b/tests/Console/Events/EventsTest.php
index ddf25896e5..ca406f20a2 100644
--- a/tests/Console/Events/EventsTest.php
+++ b/tests/Console/Events/EventsTest.php
@@ -32,7 +32,7 @@ class EventsTest extends TestCase
public function testArtisanStartingCarriesApplication(): void
{
- $app = Double::for(Application::class);
+ $app = Double::for(Application::class)->strict();
$event = new ArtisanStarting($app);
@@ -73,7 +73,7 @@ public function testCommandFinishedCarriesNonZeroExitCode(): void
public function testBeforeHandleCarriesCommandAndInput(): void
{
- $command = Double::for(Command::class);
+ $command = Double::for(Command::class)->strict();
$input = new ArrayInput([]);
$event = new BeforeHandle($command, $input);
@@ -84,7 +84,7 @@ public function testBeforeHandleCarriesCommandAndInput(): void
public function testAfterHandleCarriesCommand(): void
{
- $command = Double::for(Command::class);
+ $command = Double::for(Command::class)->strict();
$event = new AfterHandle($command);
@@ -93,7 +93,7 @@ public function testAfterHandleCarriesCommand(): void
public function testAfterExecuteCarriesExecutionData(): void
{
- $command = Double::for(Command::class);
+ $command = Double::for(Command::class)->strict();
$throwable = new RuntimeException('Execute failed');
$input = new ArrayInput([]);
$event = new AfterExecute($command, $throwable, $input, 1);
@@ -106,7 +106,7 @@ public function testAfterExecuteCarriesExecutionData(): void
public function testScheduledTaskStartingCarriesTask(): void
{
- $task = new Event(Double::for(EventMutex::class), 'php foo');
+ $task = new Event(Double::for(EventMutex::class)->strict(), 'php foo');
$event = new ScheduledTaskStarting($task);
@@ -115,7 +115,7 @@ public function testScheduledTaskStartingCarriesTask(): void
public function testScheduledTaskFinishedCarriesTaskAndRuntime(): void
{
- $task = new Event(Double::for(EventMutex::class), 'php foo');
+ $task = new Event(Double::for(EventMutex::class)->strict(), 'php foo');
$event = new ScheduledTaskFinished($task, 1.23);
@@ -125,7 +125,7 @@ public function testScheduledTaskFinishedCarriesTaskAndRuntime(): void
public function testScheduledTaskSkippedCarriesTask(): void
{
- $task = new Event(Double::for(EventMutex::class), 'php foo');
+ $task = new Event(Double::for(EventMutex::class)->strict(), 'php foo');
$event = new ScheduledTaskSkipped($task);
@@ -134,7 +134,7 @@ public function testScheduledTaskSkippedCarriesTask(): void
public function testScheduledTaskFailedCarriesTaskAndException(): void
{
- $task = new Event(Double::for(EventMutex::class), 'php foo');
+ $task = new Event(Double::for(EventMutex::class)->strict(), 'php foo');
$exception = new RuntimeException('Task failed');
$event = new ScheduledTaskFailed($task, $exception);
@@ -145,7 +145,7 @@ public function testScheduledTaskFailedCarriesTaskAndException(): void
public function testScheduledBackgroundTaskFinishedCarriesTask(): void
{
- $task = new Event(Double::for(EventMutex::class), 'php foo');
+ $task = new Event(Double::for(EventMutex::class)->strict(), 'php foo');
$event = new ScheduledBackgroundTaskFinished($task);
diff --git a/tests/Console/Fixtures/Commands/FooExceptionCommand.php b/tests/Console/Fixtures/Commands/FooExceptionCommand.php
index 2be12bc948..38aff405c7 100644
--- a/tests/Console/Fixtures/Commands/FooExceptionCommand.php
+++ b/tests/Console/Fixtures/Commands/FooExceptionCommand.php
@@ -18,7 +18,7 @@ public function __construct(?string $name = null)
{
parent::__construct($name);
- $this->eventDispatcher = Double::for(Dispatcher::class);
+ $this->eventDispatcher = Double::for(Dispatcher::class)->strict();
$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 dd9216f2d3..a6a55b2408 100644
--- a/tests/Console/Fixtures/Commands/FooExitCommand.php
+++ b/tests/Console/Fixtures/Commands/FooExitCommand.php
@@ -17,7 +17,7 @@ public function __construct(?string $name = null)
{
parent::__construct($name);
- $this->eventDispatcher = Double::for(Dispatcher::class);
+ $this->eventDispatcher = Double::for(Dispatcher::class)->strict();
$this->eventDispatcher->allows('hasListeners')->returns(true);
$this->eventDispatcher->allows('dispatch')->returns(null);
}
diff --git a/tests/Console/GeneratorCommandTest.php b/tests/Console/GeneratorCommandTest.php
index 04c3084a67..a7817918c3 100644
--- a/tests/Console/GeneratorCommandTest.php
+++ b/tests/Console/GeneratorCommandTest.php
@@ -41,7 +41,7 @@ public function testGetPathWithRelativePath(): void
$command = new GeneratorCommandStub;
$command->setHypervel($this->app);
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-path')
->returns('packages/my-package/src');
@@ -57,7 +57,7 @@ public function testGetPathWithRelativePathWithTrailingSlash(): void
$command = new GeneratorCommandStub;
$command->setHypervel($this->app);
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-path')
->returns('packages/my-package/src/');
@@ -72,7 +72,7 @@ public function testGetPathWithAbsolutePath(): void
{
$command = new GeneratorCommandStub;
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-path')
->returns('/tmp/custom-path');
@@ -87,7 +87,7 @@ public function testGetPathWithAbsolutePathWithTrailingSlash(): void
{
$command = new GeneratorCommandStub;
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-path')
->returns('/tmp/custom-path/');
@@ -103,7 +103,7 @@ public function testGetPathExtractsClassNameFromDeeplyNestedNamespace(): void
$command = new GeneratorCommandStub;
$command->setHypervel($this->app);
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-path')
->returns('src/Controllers');
@@ -123,7 +123,7 @@ public function testGetPathDefaultUsesAppPath(): void
$command = new GeneratorCommandStub;
$command->setHypervel($this->app);
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-path')
->returns(null);
@@ -240,7 +240,7 @@ public function testQualifyClassPrependsDefaultNamespace(): void
{
$command = new GeneratorCommandStub;
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-namespace')
->returns(null);
@@ -253,7 +253,7 @@ public function testQualifyClassReplacesForwardSlashesWithBackslashes(): void
{
$command = new GeneratorCommandStub;
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-namespace')
->returns(null);
@@ -266,7 +266,7 @@ public function testQualifyClassUsesCustomTargetNamespaceOption(): void
{
$command = new GeneratorCommandStub;
- $input = Double::for(InputInterface::class);
+ $input = Double::for(InputInterface::class)->strict();
$input->expects('getOption')->times(minimum: 1)
->with('target-namespace')
->returns('Custom\Namespace');
@@ -277,7 +277,7 @@ public function testQualifyClassUsesCustomTargetNamespaceOption(): void
public function testWriteFailureDoesNotCreateMatchingTestOrReportSuccess(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->allows('exists')->returns(false);
$files->expects('ensureDirectoryExists');
$files->expects('get')->returns('assertNull($invoker->signalRegistry);
- $signalRegistry = Double::for(SignalRegistry::class);
+ $signalRegistry = Double::for(SignalRegistry::class)->strict();
$signalRegistry->expects('register');
+ $signalRegistry->expects('unregister')->with(Argument::same($command));
Container::getInstance()->instance(SignalRegistry::class, $signalRegistry);
$command->callTrap(SIGTERM, fn (int $signo) => null);
@@ -37,7 +38,7 @@ public function testTrapCreatesRegistry(): void
public function testTrapReusesExistingRegistry(): void
{
- $signalRegistry = Double::for(SignalRegistry::class);
+ $signalRegistry = Double::for(SignalRegistry::class)->strict();
$signalRegistry->expects('register')->times(2);
$command = new InteractsWithSignalsTestStub;
@@ -50,7 +51,7 @@ public function testTrapReusesExistingRegistry(): void
public function testUntrapDelegatesToRegistry(): void
{
$command = new InteractsWithSignalsTestStub;
- $signalRegistry = Double::for(SignalRegistry::class);
+ $signalRegistry = Double::for(SignalRegistry::class)->strict();
$signalRegistry->expects('register');
$signalRegistry->expects('unregister')->with(Argument::same($command), SIGTERM);
@@ -72,7 +73,7 @@ public function testUntrapWithNoRegistryIsNoop(): void
public function testUntrapAllSignals(): void
{
$command = new InteractsWithSignalsTestStub;
- $signalRegistry = Double::for(SignalRegistry::class);
+ $signalRegistry = Double::for(SignalRegistry::class)->strict();
$signalRegistry->expects('register');
$signalRegistry->expects('unregister')->with(Argument::same($command), null);
@@ -91,8 +92,9 @@ public function testTrapResolvesLazyIterableSignals(): void
yield SIGINT;
})();
$callback = static fn (int $signal): null => null;
- $registry = Double::for(SignalRegistry::class);
+ $registry = Double::for(SignalRegistry::class)->strict();
$registry->expects('register')->with(Argument::same($command), Argument::same($signals), Argument::same($callback));
+ $registry->expects('unregister')->with(Argument::same($command));
Container::getInstance()->instance(SignalRegistry::class, $registry);
$calls = 0;
diff --git a/tests/Console/MigrationGeneratorCommandTest.php b/tests/Console/MigrationGeneratorCommandTest.php
index ec8846dba1..aea4f00471 100644
--- a/tests/Console/MigrationGeneratorCommandTest.php
+++ b/tests/Console/MigrationGeneratorCommandTest.php
@@ -17,7 +17,7 @@ class MigrationGeneratorCommandTest extends TestCase
public function testGlobFailureIsReported(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('glob')->with('/app/database/migrations/*.php')->returns(false);
$command = new TestMigrationGeneratorCommand($files);
diff --git a/tests/Console/Scheduling/EventTest.php b/tests/Console/Scheduling/EventTest.php
index 333ad71d3d..d995416e25 100644
--- a/tests/Console/Scheduling/EventTest.php
+++ b/tests/Console/Scheduling/EventTest.php
@@ -24,6 +24,7 @@
use Hypervel\Tests\Console\Fixtures\FakeEventMutex;
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
+use JMac\Testing\DoubleInterface;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\TestWith;
@@ -79,10 +80,10 @@ protected function setUp(): void
public function testSendOutputToWithIsNotFile(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -v');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -v');
$event->sendOutputTo($output = 'test.log');
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')
->with($output)
->returns(false);
@@ -93,15 +94,15 @@ public function testSendOutputToWithIsNotFile(): void
public function testSendOutputTo(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -v');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -v');
$event->sendOutputTo($output = 'test.log');
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('output')
->returns($result = 'PHP 8.3.17 (cli) (built: Feb 11 2025 22:03:03) (NTS)');
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')
->with($output)
->returns(true);
@@ -117,17 +118,17 @@ public function testSendOutputTo(): void
public function testSendOutputToWithSystemProcess(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -v');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -v');
$event->isSystem = true;
$event->sendOutputTo($output = 'test.log');
- $process = Double::for(Process::class);
+ $process = $this->mockProcess();
$process->expects('getOutput')
->returns($result = 'PHP 8.3.17 (cli) (built: Feb 11 2025 22:03:03) (NTS)');
CoroutineContext::set($key = '__console.scheduling_process.' . spl_object_id($event), $process);
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('put')
->with($output, $result)
->returns(strlen($result));
@@ -168,7 +169,7 @@ public function testEventRunsWhenMarkedAsEvenWhenPaused(): void
public function testNeverCheckedRepeatableEventIsNotReadyToRepeat(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -i');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -i');
$event->repeatSeconds = 1;
$this->assertFalse($event->shouldRepeatNow());
@@ -204,7 +205,7 @@ protected function execute(ContainerContract $container): int
public function testRunResetsSkippedBecauseOverlapping(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$event = new class($eventMutex, 'php -i') extends Event {
public int $executions = 0;
@@ -234,7 +235,7 @@ protected function execute(ContainerContract $container): int
public function testReleaseMutexOnTerminationSignalReleasesOwnedMutex(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->expects('create')->returns(true);
$eventMutex->expects('forget');
@@ -248,7 +249,7 @@ public function testReleaseMutexOnTerminationSignalReleasesOwnedMutex(): void
public function testReleaseMutexOnTerminationSignalDoesNotReleaseUnownedMutex(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->expects('forget')->never();
$event = new Event($eventMutex, 'php -i');
@@ -259,7 +260,7 @@ public function testReleaseMutexOnTerminationSignalDoesNotReleaseUnownedMutex():
public function testReleaseMutexOnTerminationSignalHonorsReleaseFlag(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->expects('create')->returns(true);
$eventMutex->expects('forget')->never();
@@ -273,7 +274,7 @@ public function testReleaseMutexOnTerminationSignalHonorsReleaseFlag(): void
public function testStartFailureRemainsPrimaryWhenMutexCleanupFails(): void
{
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$mutex->expects('create')->returns(true);
$mutex->expects('forget')->throws(new RuntimeException('mutex cleanup failed'));
@@ -294,7 +295,7 @@ public function testStartFailureRemainsPrimaryWhenMutexCleanupFails(): void
public function testOutputFailureStillRunsAfterCallbacksAndReleasesMutex(): void
{
$afterCalled = false;
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$mutex->expects('create')->returns(true);
$mutex->expects('forget');
@@ -305,7 +306,7 @@ public function testOutputFailureStillRunsAfterCallbacksAndReleasesMutex(): void
$afterCalled = true;
});
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')->with($output)->returns(true);
$filesystem->expects('put')->with($output, 'output')->returns(false);
$this->container->instance(Filesystem::class, $filesystem);
@@ -323,7 +324,7 @@ public function testOutputFailureStillRunsAfterCallbacksAndReleasesMutex(): void
public function testAfterCallbackFailureRemainsPrimaryWhenMutexCleanupFails(): void
{
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$mutex->expects('create')->returns(true);
$mutex->expects('forget')->throws(new RuntimeException('mutex cleanup failed'));
@@ -360,14 +361,14 @@ public function testCancellationDuringCleanupSupersedesAnEarlierFailure(string $
}
}
};
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$mutex->expects('create')->returns(true);
$event = new EventTestExecutableEvent($mutex);
$event->withoutOverlapping();
if ($failurePhase === 'output') {
$event->sendOutputTo('test.log')->after($cancel);
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')->with('test.log')->returns(true);
$filesystem->expects('put')->with('test.log', 'output')->returns(false);
$this->container->instance(Filesystem::class, $filesystem);
@@ -390,7 +391,7 @@ public function testCancellationDuringCleanupSupersedesAnEarlierFailure(string $
public function testExitPublicationFailureStillRunsCallbacksAndReleasesMutex(): void
{
$afterCalled = false;
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$mutex->expects('forget');
$event = new EventTestFailingExitCodeEvent($mutex);
@@ -412,15 +413,15 @@ public function testExitPublicationFailureStillRunsCallbacksAndReleasesMutex():
public function testAppendOutput(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -v');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -v');
$event->appendOutputTo($output = 'test.log');
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('output')
->returns($result = 'PHP 8.3.17 (cli) (built: Feb 11 2025 22:03:03) (NTS)');
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')
->with($output)
->returns(true);
@@ -436,13 +437,13 @@ public function testAppendOutput(): void
public function testWriteOutputRejectsFailedWrites(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -v');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -v');
$event->sendOutputTo($output = 'test.log');
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('output')->returns($result = 'output');
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')->with($output)->returns(true);
$filesystem->expects('put')->with($output, $result)->returns(false);
@@ -457,13 +458,13 @@ public function testWriteOutputRejectsFailedWrites(): void
public function testWriteOutputRejectsPartialWrites(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -v');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -v');
$event->appendOutputTo($output = 'test.log');
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('output')->returns($result = 'output');
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')->with($output)->returns(true);
$filesystem->expects('append')->with($output, $result)->returns(3);
@@ -478,11 +479,11 @@ public function testWriteOutputRejectsPartialWrites(): void
public function testOutputCallbackSurfacesReadFailureAfterFileCheck(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -v');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -v');
$event->sendOutputTo($output = 'test.log');
$event->thenWithOutput(fn (Stringable $output) => $output);
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')->with($output)->returns(true);
$filesystem->expects('get')->with($output)->throws(
new FileNotFoundException("Unable to read file at path {$output}.")
@@ -498,16 +499,16 @@ public function testOutputCallbackSurfacesReadFailureAfterFileCheck(): void
public function testEmailOutputUsesTheMailContractCallback(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -v');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -v');
$event->sendOutputTo($output = 'test.log');
$event->description('Daily report');
$event->emailOutputTo($addresses = ['taylor@example.com']);
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')->with($output)->returns(true);
$filesystem->expects('get')->with($output)->returns('captured output');
- $mailer = Double::for(Mailer::class);
+ $mailer = Double::for(Mailer::class)->strict();
$mailer->expects('raw')
->with('captured output', Argument::type(Closure::class))
->resolves(function (string $text, Closure $callback) use ($addresses) {
@@ -533,10 +534,10 @@ public function testEmailOutputUsesTheMailContractCallback(): void
public function testProcessIsRetainedThroughAfterCallbacksAndReleasedAfterSuccess(): void
{
$outputDuringCallback = null;
- $process = Double::for(Process::class);
+ $process = $this->mockProcess();
$process->expects('getOutput')->returns('process output');
- $event = new EventTestProcessEvent(Double::for(EventMutex::class), $process);
+ $event = new EventTestProcessEvent(Double::for(EventMutex::class)->strict(), $process);
$event->after(function (Event $event) use (&$outputDuringCallback): void {
$outputDuringCallback = $event->getOutput($this->container);
});
@@ -550,8 +551,8 @@ public function testProcessIsRetainedThroughAfterCallbacksAndReleasedAfterSucces
public function testProcessIsReleasedAfterExecutionFailure(): void
{
$event = new EventTestProcessEvent(
- Double::for(EventMutex::class),
- Double::for(Process::class),
+ Double::for(EventMutex::class)->strict(),
+ $this->mockProcess(),
new RuntimeException('execution failed')
);
@@ -568,16 +569,16 @@ public function testProcessIsReleasedAfterExecutionFailure(): void
public function testProcessIsReleasedAfterOutputFailure(): void
{
$afterCalled = false;
- $process = Double::for(Process::class);
+ $process = $this->mockProcess();
$process->expects('getOutput')->returns('process output');
- $event = new EventTestProcessEvent(Double::for(EventMutex::class), $process);
+ $event = new EventTestProcessEvent(Double::for(EventMutex::class)->strict(), $process);
$event->sendOutputTo($output = 'test.log');
$event->after(function () use (&$afterCalled): void {
$afterCalled = true;
});
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('put')->with($output, 'process output')->returns(false);
$this->container->instance(Filesystem::class, $filesystem);
@@ -599,9 +600,9 @@ public function testOutputCancellationReleasesTheMutexAndProcessWithoutRunningAf
$cancellation = new CanceledException('Output write canceled.');
$cleanup = $cleanupThrows ? new RuntimeException('Output cleanup failed.') : null;
$afterCalled = false;
- $process = Double::for(Process::class);
+ $process = $this->mockProcess();
$process->expects('getOutput')->returns('process output');
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$mutex->expects('create')->returns(true);
$mutex->expects('forget');
$event = new EventTestProcessEvent($mutex, $process);
@@ -609,7 +610,7 @@ public function testOutputCancellationReleasesTheMutexAndProcessWithoutRunningAf
$event->after(static function () use (&$afterCalled): void {
$afterCalled = true;
});
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('put')->with('test.log', 'process output')->resolves(
static function () use ($cancellation, $cleanup): never {
try {
@@ -637,7 +638,7 @@ static function () use ($cancellation, $cleanup): never {
public function testProcessIsReleasedAfterAfterCallbackFailure(): void
{
- $event = new EventTestProcessEvent(Double::for(EventMutex::class), Double::for(Process::class));
+ $event = new EventTestProcessEvent(Double::for(EventMutex::class)->strict(), $this->mockProcess());
$event->after(fn () => throw new RuntimeException('after callback failed'));
try {
@@ -775,10 +776,10 @@ public function testSuccessFailureAndOutputCallbacksCanReceiveEvent(): void
$failureEvent = null;
$outputEvent = null;
$outputValue = null;
- $event = new Event(Double::for(EventMutex::class), 'php -i');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -i');
$event->sendOutputTo($output = 'test.log');
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('isFile')->times(2)->with($output)->returns(true);
$filesystem->expects('get')->times(2)->with($output)->returns('captured output');
$this->container->instance(Filesystem::class, $filesystem);
@@ -808,7 +809,7 @@ public function testSuccessFailureAndOutputCallbacksCanReceiveEvent(): void
public function testTimezoneAcceptsStringBackedEnum(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -i');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -i');
$event->timezone(EventTestTimezoneStringEnum::NewYork);
@@ -818,7 +819,7 @@ public function testTimezoneAcceptsStringBackedEnum(): void
public function testTimezoneAcceptsUnitEnum(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -i');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -i');
$event->timezone(EventTestTimezoneUnitEnum::UTC);
@@ -828,7 +829,7 @@ public function testTimezoneAcceptsUnitEnum(): void
public function testTimezoneAcceptsIntBackedEnum(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -i');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -i');
$event->timezone(EventTestTimezoneIntEnum::Zone1);
@@ -837,7 +838,7 @@ public function testTimezoneAcceptsIntBackedEnum(): void
public function testTimezoneAcceptsDateTimeZoneObject(): void
{
- $event = new Event(Double::for(EventMutex::class), 'php -i');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php -i');
$tz = new DateTimeZone('UTC');
$event->timezone($tz);
@@ -848,7 +849,7 @@ public function testTimezoneAcceptsDateTimeZoneObject(): void
public function testBasicCronCompilation(): void
{
- $appDouble = Double::for(ApplicationContract::class, override: true);
+ $appDouble = Double::for(ApplicationContract::class, override: true)->strict();
$app = $appDouble->instance();
$appDouble->expects('isDownForMaintenance')->times(3)->returns(false);
$appDouble->expects('environment')->times(3)->returns('production');
@@ -896,7 +897,7 @@ public function testBasicCronCompilation(): void
public function testEventIsDueCheck(): void
{
- $appDouble = Double::for(ApplicationContract::class, override: true);
+ $appDouble = Double::for(ApplicationContract::class, override: true)->strict();
$app = $appDouble->instance();
$appDouble->expects('isDownForMaintenance')->times(2)->returns(false);
$appDouble->expects('environment')->times(2)->returns('production');
@@ -913,14 +914,14 @@ public function testEventIsDueCheck(): void
public function testEventIsDueAtUsesGivenTime(): void
{
- $appDouble = Double::for(ApplicationContract::class, override: true);
+ $appDouble = Double::for(ApplicationContract::class, override: true)->strict();
$app = $appDouble->instance();
$appDouble->allows('isDownForMaintenance')->returns(false);
$appDouble->allows('environment')->returns('production');
CarbonImmutable::setTestNow(CarbonImmutable::parse('2026-05-29 13:00:00'));
- $event = new Event(Double::for(EventMutex::class), 'php foo');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php foo');
$event->dailyAt('13:00');
$this->assertFalse($event->isDueAt($app, CarbonImmutable::parse('2026-05-29 12:59:59')));
@@ -929,12 +930,12 @@ public function testEventIsDueAtUsesGivenTime(): void
public function testEventIsDueAtUsesEventTimezone(): void
{
- $appDouble = Double::for(ApplicationContract::class, override: true);
+ $appDouble = Double::for(ApplicationContract::class, override: true)->strict();
$app = $appDouble->instance();
$appDouble->allows('isDownForMaintenance')->returns(false);
$appDouble->allows('environment')->returns('production');
- $event = new Event(Double::for(EventMutex::class), 'php foo');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php foo');
$event->dailyAt('09:00')->timezone('America/New_York');
$this->assertTrue($event->isDueAt($app, CarbonImmutable::parse('2026-05-29 13:00:00', 'UTC')));
@@ -968,13 +969,13 @@ public function testTimeBetweenChecks(): void
public function testTimeBetweenIsEvaluatedUsingTheCurrentTime(): void
{
- $appDouble = Double::for(ApplicationContract::class, override: true);
+ $appDouble = Double::for(ApplicationContract::class, override: true)->strict();
$app = $appDouble->instance();
$appDouble->allows('call')->resolves(fn (callable $callback): bool => $callback());
CarbonImmutable::setTestNow('2026-05-29 09:00:00');
- $event = new Event(Double::for(EventMutex::class), 'php foo', 'UTC');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'php foo', 'UTC');
$event->between('8:00', '10:00');
$this->assertTrue($event->filtersPass($app));
@@ -1043,6 +1044,17 @@ public function testEnvironmentsWithEnums(): void
$event->environments(ScheduledEventTestEnvironment::Local, ScheduledEventTestEnvironment::Production);
$this->assertSame(['local', 'production'], $event->environments);
}
+
+ /**
+ * Create a process double that tolerates Symfony's destructor calling stop(0).
+ */
+ private function mockProcess(): Process&DoubleInterface
+ {
+ $process = Double::for(Process::class)->strict();
+ $process->allows('stop')->with(0.0)->returns(0);
+
+ return $process;
+ }
}
class EventTestInvokableFilter
diff --git a/tests/Console/Scheduling/ScheduleRunCommandTest.php b/tests/Console/Scheduling/ScheduleRunCommandTest.php
index 115e9dff60..8407ce7eb3 100644
--- a/tests/Console/Scheduling/ScheduleRunCommandTest.php
+++ b/tests/Console/Scheduling/ScheduleRunCommandTest.php
@@ -74,7 +74,7 @@ protected function setUp(): void
$this->dispatched = [];
- $this->dispatcher = Double::for(Dispatcher::class);
+ $this->dispatcher = Double::for(Dispatcher::class)->strict();
$this->dispatcher->allows('hasListeners')
->returns(true);
$this->dispatcher->allows('dispatch')
@@ -87,7 +87,7 @@ protected function setUp(): void
public function testForegroundCallbackDispatchesStartingAndFinishedEvents(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -127,7 +127,7 @@ public function testScheduledCommandDefersNestedCommandWorkUntilTheTaskFinishes(
$this->call('test:deferred-child');
$calls[] = 'parent finished';
});
- $event = new Event(Double::for(EventMutex::class), 'test:deferred-parent');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'test:deferred-parent');
$event->after(function () use (&$calls): void {
$calls[] = 'after';
});
@@ -150,7 +150,7 @@ public function testDeferredCallbacksRespectTheWholeTaskOutcome(string $outcome,
{
$calls = [];
$exception = new RuntimeException('Task failed');
- $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls, $outcome, $exception): bool {
+ $event = new CallbackEvent(Double::for(EventMutex::class)->strict(), function () use (&$calls, $outcome, $exception): bool {
defer(function () use (&$calls): void {
$calls[] = 'ordinary';
});
@@ -172,7 +172,7 @@ public function testDeferredCallbacksRespectTheWholeTaskOutcome(string $outcome,
if ($outcome !== 'success') {
$this->handler->expects('report');
}
- $nextEvent = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls): void {
+ $nextEvent = new CallbackEvent(Double::for(EventMutex::class)->strict(), function () use (&$calls): void {
defer(function () use (&$calls): void {
$calls[] = 'next task';
});
@@ -203,7 +203,7 @@ public function testCanceledCallbackReleasesItsMutexAndPublishesOnlyTheCancellat
$calls = [];
$cancellation = new CanceledException('Task canceled');
$cleanup = $cleanupThrows ? new RuntimeException('Task cleanup failed.') : null;
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$mutex->expects('exists')->returns(false);
$mutex->expects('create')->returns(true);
$mutex->expects('forget');
@@ -260,7 +260,7 @@ public function testStartingListenerFailureIsPublishedWithoutARuntimeAndRunsOnly
$this->dispatcher->listen(ScheduledTaskFailed::class, function (ScheduledTaskFailed $event) use (&$failed): void {
$failed[] = $event;
});
- $event = new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true);
+ $event = new CallbackEvent(Double::for(EventMutex::class)->strict(), static fn (): bool => true);
$caught = null;
try {
@@ -282,7 +282,7 @@ public function testPreRunCancellationIsPublishedWithAnyEarlierFailure(bool $aft
{
$cancellation = new CanceledException;
$failure = $afterFailure ? new RuntimeException('Starting listener failed') : null;
- $this->dispatcher = Double::for(Dispatcher::class);
+ $this->dispatcher = Double::for(Dispatcher::class)->strict();
$this->dispatcher->allows('hasListeners')->returns(true);
$this->dispatcher->allows('dispatch')->resolves(function (object $event) use ($cancellation, $failure): void {
$this->dispatched[] = $event;
@@ -298,7 +298,7 @@ public function testPreRunCancellationIsPublishedWithAnyEarlierFailure(bool $aft
$this->handler->expects('report')->never();
try {
- $this->invokeRunEvents($this->makeCommand(), [new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true)]);
+ $this->invokeRunEvents($this->makeCommand(), [new CallbackEvent(Double::for(EventMutex::class)->strict(), static fn (): bool => true)]);
$this->fail('Expected the owned task to report cancellation.');
} catch (ChildCancellationException $exception) {
$this->assertSame($cancellation, $exception->getPrevious());
@@ -317,16 +317,16 @@ public function testCanceledListenerFailureIsReportedWithoutReplacingTheCancella
{
$cancellation = new CanceledException;
$listenerFailure = new RuntimeException('Canceled listener failed');
- $this->dispatcher = Double::for(Dispatcher::class);
+ $this->dispatcher = Double::for(Dispatcher::class)->strict();
$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->expects('report')->with($listenerFailure);
+ $this->handler->expects('report')->with(Argument::same($listenerFailure));
try {
- $this->invokeRunEvents($this->makeCommand(), [new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true)]);
+ $this->invokeRunEvents($this->makeCommand(), [new CallbackEvent(Double::for(EventMutex::class)->strict(), static fn (): bool => true)]);
$this->fail('Expected the owned task to report cancellation.');
} catch (ChildCancellationException $exception) {
$this->assertSame($cancellation, $exception->getPrevious());
@@ -340,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(Double::for(EventMutex::class), function () use (&$calls, $cancellation, $cleanup): void {
+ $event = new CallbackEvent(Double::for(EventMutex::class)->strict(), function () use (&$calls, $cancellation, $cleanup): void {
defer(function () use ($cancellation, $cleanup): void {
try {
throw $cancellation;
@@ -389,7 +389,7 @@ public function testDeferredCancellationSupersedesAnEarlierTaskFailure(bool $cle
throw new RuntimeException('Starting listener failed.');
});
- $event = new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true);
+ $event = new CallbackEvent(Double::for(EventMutex::class)->strict(), static fn (): bool => true);
try {
$this->invokeRunEvents($this->makeCommand(), [$event]);
@@ -417,7 +417,7 @@ public function testBackgroundTaskDrainsItsCallbacksAfterBackgroundFinishedListe
$calls[] = 'deferred listener';
});
});
- $event = new Event(Double::for(EventMutex::class), 'test:background-defer');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'test:background-defer');
$event->runInBackground();
$command = $this->makeCommand();
$concurrent = new Concurrent(1);
@@ -435,15 +435,15 @@ public function testBackgroundTaskDrainsItsCallbacksAfterBackgroundFinishedListe
#[DataProvider('skippedBackgroundTasks')]
public function testSkippedBackgroundTaskDoesNotDispatchCompletion(bool $onAnotherServer): void
{
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$event = new Event($mutex, 'test:skipped-background');
$event->runInBackground();
$command = $this->makeCommand();
$output = $this->captureOutput($command);
if ($onAnotherServer) {
$event->onOneServer();
- $schedule = Double::for(Schedule::class);
- $schedule->expects('serverShouldRun')->with($event, Argument::type(CarbonInterface::class))->returns(false);
+ $schedule = Double::for(Schedule::class)->strict();
+ $schedule->expects('serverShouldRun')->with(Argument::same($event), Argument::type(CarbonInterface::class))->returns(false);
(new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule);
} else {
$event->withoutOverlapping();
@@ -482,7 +482,7 @@ public static function skippedBackgroundTasks(): array
public function testFinishedOutputUsesTheSharedRuntimeFormatterWithoutAppendingUnits(): void
{
- $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 0, 'test:duration');
+ $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class)->strict(), 0, 'test:duration');
$command = $this->makeCommand(command: new ScheduleRunCommandWithFixedRuntime);
$output = $this->captureOutput($command);
@@ -505,7 +505,7 @@ public function testForegroundTaskEvaluationsUseFiniteCoroutinesWithSelectedLogC
$events = [];
foreach (['first', 'second'] as $name) {
- $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$observations, &$deferred, $name): int {
+ $event = new CallbackEvent(Double::for(EventMutex::class)->strict(), function () use (&$observations, &$deferred, $name): int {
$observations[$name]['run'] = [Coroutine::getCid(), count($deferred)];
return 0;
@@ -552,7 +552,7 @@ public function testRunOncePreservesLogContextAcrossItsOuterCoroutine(): void
{
ContextRepository::getInstance()->add('trace_id', 'parent-trace');
$observedTraceId = null;
- $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$observedTraceId): int {
+ $event = new CallbackEvent(Double::for(EventMutex::class)->strict(), function () use (&$observedTraceId): int {
$context = CoroutineContext::get(ContextRepository::CONTEXT_KEY);
$observedTraceId = $context instanceof ContextRepository
? $context->get('trace_id')
@@ -561,9 +561,9 @@ public function testRunOncePreservesLogContextAcrossItsOuterCoroutine(): void
return 0;
});
- $schedule = Double::for(Schedule::class);
+ $schedule = Double::for(Schedule::class)->strict();
$schedule->expects('dueEventsAt')
- ->with($this->app, Argument::type(CarbonInterface::class))
+ ->with(Argument::same($this->app), Argument::type(CarbonInterface::class))
->returns(new Collection([$event]));
$command = $this->makeCommand();
@@ -582,7 +582,7 @@ public function testTaskLifecycleEventsAreNotDispatchedWithoutListeners(): void
$this->dispatcher = Double::for(Dispatcher::class)->strict();
$this->dispatcher->expects('dispatch')->never();
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -608,7 +608,7 @@ public function testTaskLifecycleEventsRemainVisibleToEventFakes(): void
ScheduledTaskFinished::class,
]);
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -625,7 +625,7 @@ public function testTaskLifecycleEventsRemainVisibleToEventFakes(): void
public function testBackgroundTaskDispatchesAllThreeEvents(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -653,7 +653,7 @@ public function testBackgroundTaskDispatchesAllThreeEvents(): void
public function testBackgroundTaskStillDispatchesBackgroundFinishedOnFailure(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$exception = new RuntimeException('Task exploded');
@@ -662,7 +662,7 @@ public function testBackgroundTaskStillDispatchesBackgroundFinishedOnFailure():
$event->expects('run')->throws($exception);
$event->runInBackground();
- $this->handler->expects('report')->with($exception);
+ $this->handler->expects('report')->with(Argument::same($exception));
$command = $this->makeCommand();
$concurrent = new Concurrent(10);
@@ -683,11 +683,11 @@ public function testBackgroundTaskStillDispatchesBackgroundFinishedOnFailure():
public function testThrownRunIsRenderedAsFailedWhenTheEventRetainsAZeroExitCode(): void
{
$exception = new RuntimeException('Task exploded after an earlier successful run.');
- $event = Double::for(new Event(Double::for(EventMutex::class), 'test:stale-exit', null, false))->passthru();
+ $event = Double::for(new Event(Double::for(EventMutex::class)->strict(), 'test:stale-exit', null, false))->passthru();
$event->finish($this->app, 0);
$event->expects('run')->throws($exception);
- $this->handler->expects('report')->with($exception);
+ $this->handler->expects('report')->with(Argument::same($exception));
$command = $this->makeCommand();
$output = $this->captureOutput($command);
@@ -711,9 +711,9 @@ public function testFinishedListenerFailureIsRenderedAsFailed(): void
});
$this->dispatcher = $dispatcher;
- $this->handler->expects('report')->with($exception);
+ $this->handler->expects('report')->with(Argument::same($exception));
- $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 0, 'test:listener-failure');
+ $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class)->strict(), 0, 'test:listener-failure');
$command = $this->makeCommand();
$output = $this->captureOutput($command);
@@ -733,7 +733,7 @@ public function testNonZeroExitDispatchesAndReportsFailure(): void
->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(Double::for(EventMutex::class), 1, 'test:non-zero');
+ $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class)->strict(), 1, 'test:non-zero');
$command = $this->makeCommand();
$output = $this->captureOutput($command);
@@ -771,7 +771,7 @@ public function testFailureAfterTheTaskFinishesReportsTheTaskRuntime(): void
$command = $this->makeCommand();
$this->captureOutput($command);
- $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 1, 'test:slow-listener'));
+ $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class)->strict(), 1, 'test:slow-listener'));
$this->assertInstanceOf(ScheduledTaskFinished::class, $finishedEvent);
$this->assertInstanceOf(ScheduledTaskFailed::class, $failedEvent);
@@ -793,7 +793,7 @@ public function testDurationHandlerReportsAFailingCommandOnce(): void
$command = $this->makeCommand();
$this->captureOutput($command);
- $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 1, 'test:slow-failure'));
+ $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class)->strict(), 1, 'test:slow-failure'));
$this->assertCount(1, $runtimes);
}
@@ -802,7 +802,7 @@ public function testDurationHandlerThatThrowsIsNotCalledAgainForTheFailedEvent()
{
$exception = new RuntimeException('Alert transport failed.');
$this->dispatcher = $this->app->make(Dispatcher::class);
- $this->handler->expects('report')->with($exception);
+ $this->handler->expects('report')->with(Argument::same($exception));
$schedule = new Schedule;
$throwingCalls = 0;
@@ -821,7 +821,7 @@ public function testDurationHandlerThatThrowsIsNotCalledAgainForTheFailedEvent()
$command = $this->makeCommand();
$this->captureOutput($command);
- $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class), 0, 'test:throwing-handler'));
+ $this->invokeRunEvent($command, new ScheduleRunExitCodeEvent(Double::for(EventMutex::class)->strict(), 0, 'test:throwing-handler'));
$this->assertSame(1, $throwingCalls);
@@ -835,7 +835,7 @@ public function testBackgroundNonZeroExitDispatchesAndReportsFailureBeforeBackgr
->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(Double::for(EventMutex::class), 1, 'test:background-non-zero');
+ $event = new ScheduleRunExitCodeEvent(Double::for(EventMutex::class)->strict(), 1, 'test:background-non-zero');
$event->runInBackground();
$command = $this->makeCommand();
@@ -856,7 +856,7 @@ public function testBackgroundNonZeroExitDispatchesAndReportsFailureBeforeBackgr
public function testOverlapSkipDoesNotReportThePreviousNonZeroExitAgain(): void
{
- $mutex = Double::for(EventMutex::class);
+ $mutex = Double::for(EventMutex::class)->strict();
$mutex->expects('create')->returns(false);
$event = new ScheduleRunExitCodeEvent($mutex, 1, 'test:overlap-skip');
@@ -937,7 +937,7 @@ public function testBackgroundFinishedEventIsNotDispatchedWithoutListeners(): vo
$this->dispatcher = Double::for(Dispatcher::class)->strict();
$this->dispatcher->expects('dispatch')->never();
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$event = Double::for(new Event($eventMutex, 'test:background', null, false))->passthru();
$event->expects('run');
@@ -967,7 +967,7 @@ public function testBackgroundFinishedEventIsNotDispatchedWithoutListeners(): vo
public function testSkippedNonRepeatableTaskIsOnlyEvaluatedOncePerMinute(): void
{
$deferred = [];
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$callbackEvent = new CallbackEvent($eventMutex, function () {
return 0;
@@ -997,7 +997,7 @@ public function testSkippedTaskEventIsGuardedByRegisteredListeners(): void
$this->dispatcher = Double::for(Dispatcher::class)->strict();
$this->dispatcher->expects('dispatch')->never();
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$callbackEvent = new CallbackEvent($eventMutex, function () {
return 0;
@@ -1016,14 +1016,14 @@ public function testSkippedTaskEventIsGuardedByRegisteredListeners(): void
public function testPausedTaskIsSkippedWithoutRunningFilters(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$callbackEvent = Double::for(new CallbackEvent($eventMutex, function () {
return 0;
}))->passthru();
$callbackEvent->expects('filtersPass')->never();
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('get')
->with('hypervel:schedule:paused', false)
->returns(true);
@@ -1048,9 +1048,9 @@ public function testPausedTaskListenerDefersWorkWithinItsOwnCoroutine(): void
$calls[] = 'deferred';
});
});
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('get')->with('hypervel:schedule:paused', false)->returns(true);
- $event = new CallbackEvent(Double::for(EventMutex::class), static fn (): bool => true);
+ $event = new CallbackEvent(Double::for(EventMutex::class)->strict(), static fn (): bool => true);
$this->invokeRunEvents($this->makeCommand($cache), [$event]);
@@ -1063,7 +1063,7 @@ public function testTaskMarkedEvenWhenPausedRunsWhileSchedulerIsPaused(): void
{
$runCount = 0;
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -1074,7 +1074,7 @@ public function testTaskMarkedEvenWhenPausedRunsWhileSchedulerIsPaused(): void
});
$callbackEvent->evenWhenPaused();
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('get')
->with('hypervel:schedule:paused', false)
->returns(true);
@@ -1090,13 +1090,13 @@ public function testTaskMarkedEvenWhenPausedRunsWhileSchedulerIsPaused(): void
public function testPausedNonRepeatableTaskIsOnlyEvaluatedOncePerMinute(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$callbackEvent = new CallbackEvent($eventMutex, function () {
return 0;
});
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('get')
->with('hypervel:schedule:paused', false)
->returns(true);
@@ -1118,7 +1118,7 @@ public function testPauseAndInterruptChecksDoNotReadTheCacheWhenPollingIsDisable
$runCount = 0;
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -1128,7 +1128,7 @@ public function testPauseAndInterruptChecksDoNotReadTheCacheWhenPollingIsDisable
return 0;
});
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('get')->never();
$command = $this->makeCommand($cache);
@@ -1145,7 +1145,7 @@ public function testNonRepeatableEventOnlyRunsOncePerMinute(): void
{
$runCount = 0;
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -1172,7 +1172,7 @@ public function testRepeatableEventIsThrottledByLastChecked(): void
{
$runCount = 0;
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -1197,15 +1197,15 @@ public function testRepeatableEventIsThrottledByLastChecked(): void
public function testSingleServerEventClaimedElsewhereDoesNotReportThatNoCommandsWereReady(): void
{
- $event = new Event(Double::for(EventMutex::class), 'test:single-server');
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'test:single-server');
$event->onOneServer();
- $schedule = Double::for(Schedule::class);
+ $schedule = Double::for(Schedule::class)->strict();
$schedule->expects('dueEventsAt')
- ->with($this->app, Argument::type(CarbonInterface::class))
+ ->with(Argument::same($this->app), Argument::type(CarbonInterface::class))
->returns(new Collection([$event]));
$schedule->expects('serverShouldRun')
- ->with($event, Argument::type(CarbonInterface::class))
+ ->with(Argument::same($event), Argument::type(CarbonInterface::class))
->returns(false);
$command = $this->makeCommand();
@@ -1234,7 +1234,7 @@ public function testRepeatEventsPreservesOriginalStartForSingleServerMutex(strin
$startedAt = Date::now()->startOfMinute();
$expectedStartedAt = $startedAt->format('Y-m-d H:i:s');
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$callbackEvent = new CallbackEvent($eventMutex, function () use ($startedAt): int {
Date::setTestNow($startedAt->copy()->addMinute());
@@ -1244,14 +1244,12 @@ public function testRepeatEventsPreservesOriginalStartForSingleServerMutex(strin
$callbackEvent->repeatSeconds = 1;
$callbackEvent->lastChecked = $startedAt->copy()->subSecond();
- $schedule = Double::for(Schedule::class);
+ $schedule = Double::for(Schedule::class)->strict();
$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;
- }))
+ ->with(
+ Argument::same($callbackEvent),
+ Argument::satisfies(static fn (CarbonInterface $time): bool => $time->format('Y-m-d H:i:s') === $expectedStartedAt),
+ )
->returns(true);
$command = $this->makeCommand();
@@ -1281,7 +1279,7 @@ public function testRepeatEventsUseTheBackgroundDispatchPath(): void
Date::setTestNow('2026-05-28 12:34:00');
$startedAt = Date::now()->startOfMinute();
- $event = Double::for(new Event(Double::for(EventMutex::class), 'test:repeating-background', null, false))->passthru();
+ $event = Double::for(new Event(Double::for(EventMutex::class)->strict(), 'test:repeating-background', null, false))->passthru();
$event->expects('run')
->resolves(function () use ($startedAt): void {
Date::setTestNow($startedAt->addMinute());
@@ -1309,7 +1307,7 @@ public function testRepeatEventsUseTheBackgroundDispatchPath(): void
public function testConcurrentFinishesUseRunLocalExitCodeForSuccessAndFailureCallbacks(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$event = new Event($eventMutex, 'test:overlap');
$channel = new Channel(2);
@@ -1380,9 +1378,9 @@ public function testInFlightExecutionsFinishBeforeTheWorkerQuits(): void
$finished = true;
});
$event = (new Event($mutex, 'test:shutdown-drain'))->withoutOverlapping()->runInBackground();
- $schedule = Double::for(Schedule::class);
+ $schedule = Double::for(Schedule::class)->strict();
$schedule->expects('dueEventsAt')->returns(new Collection([$event]));
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('get')->never();
$command = $this->makeCommand($cache);
$command->setInput(new ArrayInput([], $command->getDefinition()));
@@ -1419,7 +1417,7 @@ public function testNoNewExecutionsAreStartedAfterAStopSignal(string $phase): vo
$command = $this->makeCommand();
(new ReflectionMethod($command, 'listenForSignals'))->invoke($command);
$calls = [];
- $event = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls, $phase, $signal): void {
+ $event = new CallbackEvent(Double::for(EventMutex::class)->strict(), function () use (&$calls, $phase, $signal): void {
$calls[] = 'first';
if ($phase === 'foreground task') {
$signal(SIGTERM);
@@ -1432,7 +1430,7 @@ public function testNoNewExecutionsAreStartedAfterAStopSignal(string $phase): vo
return true;
});
- $schedule = Double::for(Schedule::class);
+ $schedule = Double::for(Schedule::class)->strict();
$schedule->expects('serverShouldRun')->times($phase === 'filter' ? 0 : 1)->resolves(function () use ($phase, $signal): bool {
if ($phase === 'server claim') {
$signal(SIGTERM);
@@ -1441,7 +1439,7 @@ public function testNoNewExecutionsAreStartedAfterAStopSignal(string $phase): vo
return true;
});
(new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule);
- $next = new CallbackEvent(Double::for(EventMutex::class), function () use (&$calls): void {
+ $next = new CallbackEvent(Double::for(EventMutex::class)->strict(), function () use (&$calls): void {
$calls[] = 'second';
});
$next->when(function () use (&$calls): bool {
@@ -1483,14 +1481,14 @@ public function testBackgroundTaskWaitingForCapacityDoesNotStartAfterShutdown():
throw new RuntimeException('The running task was not released.');
}
});
- $first = (new Event(Double::for(EventMutex::class), 'test:occupy-slot'))->runInBackground();
- $second = (new Event(Double::for(EventMutex::class), 'test:must-not-run'))->runInBackground()->onOneServer();
+ $first = (new Event(Double::for(EventMutex::class)->strict(), 'test:occupy-slot'))->runInBackground();
+ $second = (new Event(Double::for(EventMutex::class)->strict(), 'test:must-not-run'))->runInBackground()->onOneServer();
$second->when(function () use ($waiting): bool {
$waiting->push(true, 5.0);
return true;
});
- $schedule = Double::for(Schedule::class);
+ $schedule = Double::for(Schedule::class)->strict();
$schedule->expects('serverShouldRun')->never();
(new ReflectionProperty($command, 'schedule'))->setValue($command, $schedule);
@@ -1553,7 +1551,7 @@ protected function releaseRunningEventMutexes(): void
public function testSignalCleanupReleasesMutexesForRunningOwnedEvents(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->expects('create')->returns(true);
$eventMutex->expects('forget');
@@ -1573,7 +1571,7 @@ public function testSignalCleanupReleasesMutexesForRunningOwnedEvents(): void
public function testSignalCleanupDoesNotReleaseMutexesForEventsWithoutOwnedMutexes(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->expects('forget')->never();
$event = new Event($eventMutex, 'test:overlap');
@@ -1590,7 +1588,7 @@ public function testSignalCleanupDoesNotReleaseMutexesForEventsWithoutOwnedMutex
public function testSignalCleanupHonorsReleaseOnTerminationSignalsFlag(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->expects('create')->returns(true);
$eventMutex->expects('forget')->never();
@@ -1610,7 +1608,7 @@ public function testSignalCleanupHonorsReleaseOnTerminationSignalsFlag(): void
public function testRunningEventIsRetainedUntilEveryOverlappingInvocationFinishes(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->expects('create')->returns(true);
$eventMutex->expects('forget');
@@ -1640,7 +1638,7 @@ public function testRunningEventIsRetainedUntilEveryOverlappingInvocationFinishe
public function testRunningEventIsForgottenWhenEventThrows(): void
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$exception = new RuntimeException('Task exploded');
@@ -1648,7 +1646,7 @@ public function testRunningEventIsForgottenWhenEventThrows(): void
$event = Double::for(new Event($eventMutex, 'test:failing', null, false))->passthru();
$event->expects('run')->throws($exception);
- $this->handler->expects('report')->with($exception);
+ $this->handler->expects('report')->with(Argument::same($exception));
$command = $this->makeCommand();
$this->invokeRunEvent($command, $event);
@@ -1663,7 +1661,7 @@ public function testRunningEventIsForgottenWhenEventThrows(): void
*/
protected function captureTerminationSignal(?Closure &$callback): void
{
- $registry = Double::for(SignalRegistry::class);
+ $registry = Double::for(SignalRegistry::class)->strict();
$registry->expects('register')
->with(Argument::type(ScheduleRunCommand::class), [SIGTERM, SIGINT, SIGQUIT], Argument::capture($callback));
$registry->allows('unregister');
@@ -1688,7 +1686,7 @@ protected function makeCommand(
}
// Set dependencies that are normally injected via handle().
- (new ReflectionProperty($command, 'schedule'))->setValue($command, Double::for(Schedule::class));
+ (new ReflectionProperty($command, 'schedule'))->setValue($command, Double::for(Schedule::class)->strict());
(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 83800bbe05..5797cc9a5b 100644
--- a/tests/Console/Scheduling/ScheduleRunContextPropagationTest.php
+++ b/tests/Console/Scheduling/ScheduleRunContextPropagationTest.php
@@ -41,7 +41,7 @@ protected function setUp(): void
{
parent::setUp();
- $this->dispatcher = Double::for(Dispatcher::class);
+ $this->dispatcher = Double::for(Dispatcher::class)->strict();
$this->dispatcher->allows('hasListeners')->returns(true);
$this->dispatcher->allows('dispatch');
@@ -135,7 +135,7 @@ public function testForegroundTaskReceivesIndependentCopyOfParentLogContext(): v
ContextRepository::getInstance()->add('parent_key', 'original');
$childValues = [];
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -169,7 +169,7 @@ public function testSystemTaskReceivesContextThroughItsEnvironment(): void
->addHidden('token', 'secret');
$context = null;
- $event = new Event(Double::for(EventMutex::class), 'printf %s "$__HYPERVEL_CONTEXT"', isSystem: true);
+ $event = new Event(Double::for(EventMutex::class)->strict(), 'printf %s "$__HYPERVEL_CONTEXT"', isSystem: true);
$event->thenWithOutput(static function (Stringable $output) use (&$context): void {
$context = (string) $output;
});
@@ -189,7 +189,7 @@ public function testSystemTaskReceivesContextThroughItsEnvironment(): void
*/
protected function makeBackgroundEvent(callable $callback): Event
{
- $eventMutex = Double::for(EventMutex::class);
+ $eventMutex = Double::for(EventMutex::class)->strict();
$eventMutex->allows('create')->returns(true);
$eventMutex->allows('forget');
@@ -226,9 +226,9 @@ protected function makeCommand(): ScheduleRunCommand
$command = new ScheduleRunCommand;
$command->setHypervel($this->app);
- (new ReflectionProperty($command, 'schedule'))->setValue($command, Double::for(Schedule::class));
+ (new ReflectionProperty($command, 'schedule'))->setValue($command, Double::for(Schedule::class)->strict());
(new ReflectionProperty($command, 'dispatcher'))->setValue($command, $this->dispatcher);
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->allows('get')
->with('hypervel:schedule:paused', false)
->returns(false);
diff --git a/tests/Console/Scheduling/ScheduleTest.php b/tests/Console/Scheduling/ScheduleTest.php
index 0c5be3c15d..4a484bf776 100644
--- a/tests/Console/Scheduling/ScheduleTest.php
+++ b/tests/Console/Scheduling/ScheduleTest.php
@@ -87,7 +87,7 @@ protected function setUp(): void
Container::setInstance($this->container);
$this->eventMutex = new FakeEventMutex;
$this->container->instance(EventMutex::class, $this->eventMutex);
- $this->schedulingMutex = Double::for(SchedulingMutex::class);
+ $this->schedulingMutex = Double::for(SchedulingMutex::class)->strict();
$this->container->instance(SchedulingMutex::class, $this->schedulingMutex);
}
@@ -126,7 +126,7 @@ public function testJobIsNotInstantiatedIfSuppliedAsClassname(): void
public function testSynchronousJobResolvesToAFreshInstanceForEachFiring(): void
{
$dispatched = [];
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatchNow')->times(2)
->resolves(function (ScheduleTestMutableJob $job) use (&$dispatched): void {
self::assertFalse($job->handled);
@@ -160,7 +160,7 @@ public function testExplicitlySharedClassStringJobIsDispatchedAsTheRegisteredIns
{
$job = new ScheduleTestMutableJob;
ScheduleTestMutableJob::$constructions = 0;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatchNow')
->resolves(static function (object $dispatched) use ($job): void {
self::assertSame($job, $dispatched);
@@ -176,7 +176,7 @@ public function testExplicitlySharedClassStringJobIsDispatchedAsTheRegisteredIns
public function testSuppliedQueuedJobIsDispatchedAsProvided(): void
{
$job = new ScheduleTestQueuedJob;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')
->resolves(static function (object $dispatched) use ($job): void {
self::assertSame($job, $dispatched);
@@ -193,7 +193,7 @@ public function testSuppliedQueuedJobIsDispatchedAsProvided(): void
public function testQueuedClassStringDoesNotRetainQueueStateAcrossEvents(): void
{
$dispatched = [];
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->times(2)
->resolves(static function (object $job) use (&$dispatched): void {
$dispatched[] = $job;
@@ -244,7 +244,7 @@ public function testItCanFilterEventsByEnvironments(): void
public function testDueEventsAtUsesGivenTime(bool $alwaysOnOneServer): void
{
Schedule::alwaysOnOneServer($alwaysOnOneServer);
- $appDouble = Double::for(ApplicationContract::class, override: true);
+ $appDouble = Double::for(ApplicationContract::class, override: true)->strict();
$app = $appDouble->instance();
$appDouble->allows('isDownForMaintenance')->returns(false);
$appDouble->allows('environment')->returns('production');
@@ -306,10 +306,10 @@ public function testJobAcceptsIntegerBackedEnumForQueueAndConnection(): void
public function testUseCacheAcceptsStringBackedEnum(): void
{
- $eventMutex = Double::for(EventMutex::class, CacheAware::class);
+ $eventMutex = Double::for(EventMutex::class, CacheAware::class)->strict();
$eventMutex->expects('useStore')->with('redis');
- $schedulingMutex = Double::for(SchedulingMutex::class, CacheAware::class);
+ $schedulingMutex = Double::for(SchedulingMutex::class, CacheAware::class)->strict();
$schedulingMutex->expects('useStore')->with('redis');
$this->container->instance(EventMutex::class, $eventMutex);
@@ -321,10 +321,10 @@ public function testUseCacheAcceptsStringBackedEnum(): void
public function testUseCacheAcceptsIntegerBackedEnum(): void
{
- $eventMutex = Double::for(EventMutex::class, CacheAware::class);
+ $eventMutex = Double::for(EventMutex::class, CacheAware::class)->strict();
$eventMutex->expects('useStore')->with('1');
- $schedulingMutex = Double::for(SchedulingMutex::class, CacheAware::class);
+ $schedulingMutex = Double::for(SchedulingMutex::class, CacheAware::class)->strict();
$schedulingMutex->expects('useStore')->with('1');
$this->container->instance(EventMutex::class, $eventMutex);
diff --git a/tests/Console/View/ComponentsTest.php b/tests/Console/View/ComponentsTest.php
index 05523a762a..0cb692b42e 100644
--- a/tests/Console/View/ComponentsTest.php
+++ b/tests/Console/View/ComponentsTest.php
@@ -132,14 +132,10 @@ public function testChoice(): void
public function testAskWithCompletionAcceptsGeneratorValues(): void
{
- $output = Double::for(OutputStyle::class);
+ $output = Double::for(OutputStyle::class)->strict();
$output->expects('askQuestion')
- ->with(Argument::satisfies(function (Question $question): bool {
- $this->assertSame(['a', 'b'], $question->getAutocompleterValues());
-
- return true;
- }))
+ ->with(Argument::capture($question))
->returns('b');
$choices = (function (): Generator {
@@ -150,6 +146,8 @@ public function testAskWithCompletionAcceptsGeneratorValues(): void
$result = (new AskWithCompletion($output))->render('Question?', $choices);
$this->assertSame('b', $result);
+ $this->assertInstanceOf(Question::class, $question);
+ $this->assertSame(['a', 'b'], $question->getAutocompleterValues());
}
public function testTask(): void
diff --git a/tests/Container/ContextualAttributeBindingTest.php b/tests/Container/ContextualAttributeBindingTest.php
index bab66f9d28..92f5eb6166 100644
--- a/tests/Container/ContextualAttributeBindingTest.php
+++ b/tests/Container/ContextualAttributeBindingTest.php
@@ -214,29 +214,29 @@ public function testAuthedAttribute(): void
{
$container = new Container;
$container->singleton('auth', function (): AuthManager {
- $manager = Double::for(AuthManager::class);
+ $manager = Double::for(AuthManager::class)->strict();
$manager->expects('userResolver')->times(4)->returns(fn (UnitEnum|string|null $guard = null): ?AuthenticatableContract => $manager->guard($guard)->user());
$manager->expects('guard')->with('foo')->resolves(function (): GuardContract {
- $guard = Double::for(GuardContract::class);
- $guard->expects('user')->returns(Double::for(AuthenticatableContract::class));
+ $guard = Double::for(GuardContract::class)->strict();
+ $guard->expects('user')->returns(Double::for(AuthenticatableContract::class)->strict());
return $guard;
});
$manager->expects('guard')->with('bar')->resolves(function (): GuardContract {
- $guard = Double::for(GuardContract::class);
- $guard->expects('user')->returns(Double::for(AuthenticatableContract::class));
+ $guard = Double::for(GuardContract::class)->strict();
+ $guard->expects('user')->returns(Double::for(AuthenticatableContract::class)->strict());
return $guard;
});
$manager->expects('guard')->with(AuthGuardUnitEnum::unit)->resolves(function (): GuardContract {
- $guard = Double::for(GuardContract::class);
- $guard->expects('user')->returns(Double::for(AuthenticatableContract::class));
+ $guard = Double::for(GuardContract::class)->strict();
+ $guard->expects('user')->returns(Double::for(AuthenticatableContract::class)->strict());
return $guard;
});
$manager->expects('guard')->with(AuthGuardBackedEnum::Backed)->resolves(function (): GuardContract {
- $guard = Double::for(GuardContract::class);
- $guard->expects('user')->returns(Double::for(AuthenticatableContract::class));
+ $guard = Double::for(GuardContract::class)->strict();
+ $guard->expects('user')->returns(Double::for(AuthenticatableContract::class)->strict());
return $guard;
});
@@ -257,7 +257,7 @@ public function testAuthenticatedAttributesCanExtractPropertyPaths(): void
'profile' => ['id' => 20],
]);
- $manager = Double::for(AuthManager::class);
+ $manager = Double::for(AuthManager::class)->strict();
$manager->expects('userResolver')->times(2)->returns(fn (): GenericUser => $user);
$container->singleton('auth', fn (): AuthManager => $manager);
@@ -271,7 +271,7 @@ public function testAuthenticatedAttributesCanExtractPropertyPaths(): void
public function testAuthenticatedNullIsAuthoritativeForMakeAndCall(): void
{
$container = new Container;
- $manager = Double::for(AuthManager::class);
+ $manager = Double::for(AuthManager::class)->strict();
$manager->expects('userResolver')->times(3)->returns(fn (): null => null);
$container->singleton('auth', fn (): AuthManager => $manager);
@@ -290,14 +290,14 @@ public function testCacheAttribute(): void
{
$container = new Container;
$container->singleton('cache', function (): CacheManager {
- $manager = Double::for(CacheManager::class);
- $manager->expects('store')->with('foo')->returns(Double::for(CacheRepository::class));
- $manager->expects('store')->with('bar')->returns(Double::for(CacheRepository::class));
- $manager->expects('store')->with(CacheStoreUnitEnum::unit)->returns(Double::for(CacheRepository::class));
- $manager->expects('store')->with(CacheStoreBackedEnum::Backed)->returns(Double::for(CacheRepository::class));
- $manager->expects('store')->with(CacheStoreIntegerBackedEnum::Zero)->returns(Double::for(CacheRepository::class));
- $manager->expects('memo')->with('foo')->returns(Double::for(CacheRepository::class));
- $manager->expects('memo')->with('bar')->returns(Double::for(CacheRepository::class));
+ $manager = Double::for(CacheManager::class)->strict();
+ $manager->expects('store')->with('foo')->returns(Double::for(CacheRepository::class)->strict());
+ $manager->expects('store')->with('bar')->returns(Double::for(CacheRepository::class)->strict());
+ $manager->expects('store')->with(CacheStoreUnitEnum::unit)->returns(Double::for(CacheRepository::class)->strict());
+ $manager->expects('store')->with(CacheStoreBackedEnum::Backed)->returns(Double::for(CacheRepository::class)->strict());
+ $manager->expects('store')->with(CacheStoreIntegerBackedEnum::Zero)->returns(Double::for(CacheRepository::class)->strict());
+ $manager->expects('memo')->with('foo')->returns(Double::for(CacheRepository::class)->strict());
+ $manager->expects('memo')->with('bar')->returns(Double::for(CacheRepository::class)->strict());
return $manager;
});
@@ -323,7 +323,7 @@ public function testDatabaseAttribute(): void
{
$container = new Container;
$container->singleton('db', function (): DatabaseManager {
- $manager = Double::for(DatabaseManager::class);
+ $manager = Double::for(DatabaseManager::class)->strict();
$manager->expects('connection')->with('foo')->returns(new PdoConnection(new PDO('sqlite::memory:')));
$manager->expects('connection')->with('bar')->returns(new PdoConnection(new PDO('sqlite::memory:')));
$manager->expects('connection')->with(DatabaseConnectionIntegerBackedEnum::Zero)->returns(new PdoConnection(new PDO('sqlite::memory:')));
@@ -340,12 +340,12 @@ public function testAuthAttribute(): void
{
$container = new Container;
$container->singleton('auth', function (): AuthManager {
- $manager = Double::for(AuthManager::class);
- $manager->expects('guard')->with('foo')->returns(Double::for(GuardContract::class));
- $manager->expects('guard')->with('bar')->returns(Double::for(GuardContract::class));
- $manager->expects('guard')->with(AuthGuardUnitEnum::unit)->returns(Double::for(GuardContract::class));
- $manager->expects('guard')->with(AuthGuardBackedEnum::Backed)->returns(Double::for(GuardContract::class));
- $manager->expects('guard')->with(AuthGuardIntegerBackedEnum::Zero)->returns(Double::for(GuardContract::class));
+ $manager = Double::for(AuthManager::class)->strict();
+ $manager->expects('guard')->with('foo')->returns(Double::for(GuardContract::class)->strict());
+ $manager->expects('guard')->with('bar')->returns(Double::for(GuardContract::class)->strict());
+ $manager->expects('guard')->with(AuthGuardUnitEnum::unit)->returns(Double::for(GuardContract::class)->strict());
+ $manager->expects('guard')->with(AuthGuardBackedEnum::Backed)->returns(Double::for(GuardContract::class)->strict());
+ $manager->expects('guard')->with(AuthGuardIntegerBackedEnum::Zero)->returns(Double::for(GuardContract::class)->strict());
return $manager;
});
@@ -357,18 +357,18 @@ public function testLogAttribute(): void
{
$container = new Container;
$container->singleton('log', function (): LogManager {
- $manager = Double::for(LogManager::class);
- $manager->expects('channel')->with('foo')->returns(Double::for(LoggerInterface::class));
- $manager->expects('channel')->with('bar')->returns(Double::for(LoggerInterface::class));
- $manager->expects('channel')->with('unit_channel')->returns(Double::for(LoggerInterface::class));
- $manager->expects('channel')->with('7')->returns(Double::for(LoggerInterface::class));
-
- $named = Double::for(HypervelLogger::class);
- $named->expects('withName')->with('tenant')->returns(Double::for(HypervelLogger::class));
+ $manager = Double::for(LogManager::class)->strict();
+ $manager->expects('channel')->with('foo')->returns(Double::for(LoggerInterface::class)->strict());
+ $manager->expects('channel')->with('bar')->returns(Double::for(LoggerInterface::class)->strict());
+ $manager->expects('channel')->with('unit_channel')->returns(Double::for(LoggerInterface::class)->strict());
+ $manager->expects('channel')->with('7')->returns(Double::for(LoggerInterface::class)->strict());
+
+ $named = Double::for(HypervelLogger::class)->strict();
+ $named->expects('withName')->with('tenant')->returns(Double::for(HypervelLogger::class)->strict());
$manager->expects('channel')->with('named')->returns($named);
- $integerNamed = Double::for(HypervelLogger::class);
- $integerNamed->expects('withName')->with('9')->returns(Double::for(HypervelLogger::class));
+ $integerNamed = Double::for(HypervelLogger::class)->strict();
+ $integerNamed->expects('withName')->with('9')->returns(Double::for(HypervelLogger::class)->strict());
$manager->expects('channel')->with('integer-named')->returns($integerNamed);
return $manager;
@@ -383,7 +383,7 @@ public function testNamedLogAttributeRejectsCustomNonMonologDriver(): void
$container->make('config')->set('logging.channels.custom', ['driver' => 'custom']);
$manager = new LogManager($container);
- $manager->extend('custom', fn (): LoggerInterface => Double::for(LoggerInterface::class));
+ $manager->extend('custom', fn (): LoggerInterface => Double::for(LoggerInterface::class)->strict());
$container->instance('log', $manager);
$this->expectException(RuntimeException::class);
@@ -396,8 +396,8 @@ public function testRouteParameterAttribute(): void
{
$container = new Container;
$container->singleton('request', function (): Request {
- $request = Double::for(Request::class, override: true);
- $request->expects('route')->with('foo')->returns(Double::for(Model::class));
+ $request = Double::for(Request::class, override: true)->strict();
+ $request->expects('route')->with('foo')->returns(Double::for(Model::class)->strict());
$request->expects('route')->with('bar')->returns('bar');
return $request->instance();
@@ -412,8 +412,8 @@ public function testRouteParameterAttributeWithouthParameterName(): void
{
$container = new Container;
$container->singleton('request', function (): Request {
- $request = Double::for(Request::class, override: true);
- $request->expects('route')->with('foo')->returns(Double::for(Model::class));
+ $request = Double::for(Request::class, override: true)->strict();
+ $request->expects('route')->with('foo')->returns(Double::for(Model::class)->strict());
$request->expects('route')->with('bar')->returns('bar');
return $request->instance();
@@ -428,7 +428,7 @@ public function testRouteParameterCanExtractSupportedPropertyPaths(): void
$model = new ContextualRouteModel;
$model->setAttribute('id', 40);
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->allows('route')->with('array')->returns(['nested' => ['id' => 10]]);
$request->allows('route')->with('array-access')->returns(new ArrayObject(['id' => 20]));
$request->allows('route')->with('object')->returns((object) ['nested' => (object) ['id' => 30]]);
@@ -451,7 +451,7 @@ public function testRouteParameterCanExtractSupportedPropertyPaths(): void
public function testRouteParameterPropertyRejectsScalarValues(): void
{
$container = new Container;
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->allows('route')->with('post')->returns(123);
$container->singleton('request', fn (): Request => $request->instance());
@@ -464,7 +464,7 @@ public function testRouteParameterPropertyRejectsScalarValues(): void
public function testMissingRouteParameterDoesNotConstructAnEmptyModel(): void
{
$container = new Container;
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->allows('route')->with('post')->returns(null);
$container->singleton('request', fn (): Request => $request->instance());
@@ -542,12 +542,12 @@ public function testStorageAttribute(): void
{
$container = new Container;
$container->singleton('filesystem', function (): FilesystemManager {
- $manager = Double::for(FilesystemManager::class);
- $manager->expects('disk')->with('foo')->returns(Double::for(Filesystem::class));
- $manager->expects('disk')->with('bar')->returns(Double::for(Filesystem::class));
- $manager->expects('disk')->with(StorageDiskUnitEnum::unit)->returns(Double::for(Filesystem::class));
- $manager->expects('disk')->with(StorageDiskBackedEnum::Backed)->returns(Double::for(Filesystem::class));
- $manager->expects('disk')->with(StorageDiskIntegerBackedEnum::Zero)->returns(Double::for(Filesystem::class));
+ $manager = Double::for(FilesystemManager::class)->strict();
+ $manager->expects('disk')->with('foo')->returns(Double::for(Filesystem::class)->strict());
+ $manager->expects('disk')->with('bar')->returns(Double::for(Filesystem::class)->strict());
+ $manager->expects('disk')->with(StorageDiskUnitEnum::unit)->returns(Double::for(Filesystem::class)->strict());
+ $manager->expects('disk')->with(StorageDiskBackedEnum::Backed)->returns(Double::for(Filesystem::class)->strict());
+ $manager->expects('disk')->with(StorageDiskIntegerBackedEnum::Zero)->returns(Double::for(Filesystem::class)->strict());
return $manager;
});
diff --git a/tests/Cookie/CookieJarTest.php b/tests/Cookie/CookieJarTest.php
index e3a9c38409..3e94e76c6d 100644
--- a/tests/Cookie/CookieJarTest.php
+++ b/tests/Cookie/CookieJarTest.php
@@ -519,7 +519,7 @@ public function testForgetAcceptsUnitEnum(): void
public function testIntegerBackedEnumNamesAreNormalizedAcrossRequestCreationAndQueuePaths(): void
{
- $request = Double::for(Request::class, override: true);
+ $request = Double::for(Request::class, override: true)->strict();
$request->expects('cookie')->with('0', null)->returns('request-value');
RequestContext::set($request->instance());
diff --git a/tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php b/tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php
index 9c97a8b3a8..931c66947d 100644
--- a/tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php
+++ b/tests/Cookie/Middleware/AddQueuedCookiesToResponseTest.php
@@ -21,7 +21,7 @@ public function testHandle(): void
{
$queuedCookie = new Cookie('foo', 'bar');
- $cookieManager = Double::for(CookieJar::class);
+ $cookieManager = Double::for(CookieJar::class)->strict();
$cookieManager->expects('getQueuedCookies')->returns([$queuedCookie]);
$request = Request::create('/test');
diff --git a/tests/Coordinator/TimerTest.php b/tests/Coordinator/TimerTest.php
index 560e2ab2f2..8ab89c5221 100644
--- a/tests/Coordinator/TimerTest.php
+++ b/tests/Coordinator/TimerTest.php
@@ -20,6 +20,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use Psr\Log\LoggerInterface;
use ReflectionProperty;
@@ -145,7 +146,7 @@ public function testClearAllFromCreationHookDoesNotLeaveTheTimerCoroutineRunning
public function testCancellationDuringStartupReportingRollsBackThePublishedTimer(): void
{
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
Container::getInstance()->instance(ExceptionHandlerContract::class, $handler);
$timer = new Timer;
$hookFailure = new RuntimeException('The startup hook failed.');
@@ -159,7 +160,7 @@ public function testCancellationDuringStartupReportingRollsBackThePublishedTimer
$callbackCalled = false;
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use (
$timer,
$reportStarted,
@@ -429,7 +430,7 @@ public function testTickWhenReturnStop(): void
public function testTickStopsSilentlyWhenItsCallbackIsCancelled(): void
{
$logs = 0;
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->allows('error')->resolves(
static function () use (&$logs): void {
++$logs;
@@ -474,7 +475,7 @@ public function testTickReportsThroughTheConfiguredLoggerAndContinues(): void
{
$this->wait(function (): void {
$exception = new RuntimeException('recurring timer failed');
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->expects('error')->with((string) $exception);
$timer = new Timer($logger);
$calls = 0;
@@ -548,11 +549,10 @@ public function testTickFallsBackToThePhpErrorLogAndContinues(): void
public function testClearDontExistsClosure(): void
{
+ $this->expectNotToPerformAssertions();
$timer = new Timer;
$timer->clear(999);
-
- $this->assertTrue(true);
}
public function testUntil(): void
diff --git a/tests/Core/Bootstrap/LifecycleCallbackTest.php b/tests/Core/Bootstrap/LifecycleCallbackTest.php
index 7399fe68d7..98c37bf35f 100644
--- a/tests/Core/Bootstrap/LifecycleCallbackTest.php
+++ b/tests/Core/Bootstrap/LifecycleCallbackTest.php
@@ -47,13 +47,13 @@ public function testCallbackSkipsEventWithoutListeners(
string $eventClass,
array $arguments,
): void {
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with($eventClass)->returns(false);
$dispatcher->expects('dispatch')->never();
$callback = new $callbackClass($dispatcher);
- $this->assertNull($callback->{$method}(Double::for(Server::class), ...$arguments));
+ $this->assertNull($callback->{$method}(Double::for(Server::class)->strict(), ...$arguments));
}
#[DataProvider('callbacks')]
@@ -63,13 +63,13 @@ public function testCallbackDispatchesEventWhenListenedFor(
string $eventClass,
array $arguments,
): void {
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with($eventClass)->returns(true);
$dispatcher->expects('dispatch')->with(Argument::type($eventClass));
$callback = new $callbackClass($dispatcher);
- $this->assertNull($callback->{$method}(Double::for(Server::class), ...$arguments));
+ $this->assertNull($callback->{$method}(Double::for(Server::class)->strict(), ...$arguments));
}
/**
diff --git a/tests/Core/Bootstrap/TaskCallbackNonCoroutineTest.php b/tests/Core/Bootstrap/TaskCallbackNonCoroutineTest.php
index 243c072d8b..6c22674671 100644
--- a/tests/Core/Bootstrap/TaskCallbackNonCoroutineTest.php
+++ b/tests/Core/Bootstrap/TaskCallbackNonCoroutineTest.php
@@ -28,7 +28,7 @@ public function testEachTaskGetsAnEmptyContextUntilItHasTerminated(): void
{
CoroutineContext::set('worker', 'outer');
$seen = [];
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(true);
$dispatcher->expects('dispatch')->times(2)
->with(Argument::type(OnTask::class))
@@ -43,8 +43,8 @@ public function testEachTaskGetsAnEmptyContextUntilItHasTerminated(): void
});
$callback = $this->makeCallback($dispatcher);
- $callback->onTask(Double::for(Server::class), 1, 0, 'first');
- $callback->onTask(Double::for(Server::class), 2, 0, 'second');
+ $callback->onTask(Double::for(Server::class)->strict(), 1, 0, 'first');
+ $callback->onTask(Double::for(Server::class)->strict(), 2, 0, 'second');
$this->assertSame([[null, null], 'first', [null, null], 'second'], $seen);
$this->assertSame('outer', CoroutineContext::get('worker'));
@@ -56,7 +56,7 @@ public function testTheWorkerContextIsRestoredWhenATaskFails(): void
CoroutineContext::set('worker', 'outer');
$exception = new RuntimeException('Task failed.');
$terminatedWith = null;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -72,7 +72,7 @@ public function testTheWorkerContextIsRestoredWhenATaskFails(): void
});
try {
- $this->makeCallback($dispatcher)->onTask(Double::for(Server::class), 1, 0, 'payload');
+ $this->makeCallback($dispatcher)->onTask(Double::for(Server::class)->strict(), 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 156d458e7a..9053c3e2e1 100644
--- a/tests/Core/Bootstrap/TaskCallbackTest.php
+++ b/tests/Core/Bootstrap/TaskCallbackTest.php
@@ -25,8 +25,8 @@ class TaskCallbackTest extends TestCase
public function testLegacySignatureBuildsTaskEvent(): void
{
- $server = Double::for(Server::class);
- $dispatcher = Double::for(Dispatcher::class);
+ $server = Double::for(Server::class)->strict();
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -45,10 +45,10 @@ public function testLegacySignatureBuildsTaskEvent(): void
public function testMissingTaskListenerSkipsFinishAndStillDispatchesTerminalEvent(): void
{
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->expects('finish')->never();
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(false);
$dispatcher->expects('hasListeners')->with(TaskTerminated::class)->returns(true);
$dispatcher->expects('dispatch')
@@ -66,13 +66,13 @@ public function testMissingTaskListenerSkipsFinishAndStillDispatchesTerminalEven
#[DataProvider('objectModeSettings')]
public function testDedicatedTaskSettingsUseNativeObjectSignature(array $settings): void
{
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$task = new Task;
$task->id = 21;
$task->worker_id = 4;
$task->data = 'payload';
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -104,8 +104,8 @@ public static function objectModeSettings(): array
public function testLegacyAliasPresenceTakesPrecedenceOverTaskObject(): void
{
- $server = Double::for(Server::class);
- $dispatcher = Double::for(Dispatcher::class);
+ $server = Double::for(Server::class)->strict();
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -125,10 +125,10 @@ public function testLegacyAliasPresenceTakesPrecedenceOverTaskObject(): void
public function testLegacyResultIsFinishedThroughServer(): void
{
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->expects('finish')->with('completed');
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -145,7 +145,7 @@ public function testLegacyResultIsFinishedThroughServer(): void
public function testLegacyResultIsFinishedBeforeTerminalDispatch(): void
{
$order = [];
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->expects('finish')
->with('completed')
->resolves(function () use (&$order): bool {
@@ -155,7 +155,7 @@ public function testLegacyResultIsFinishedBeforeTerminalDispatch(): void
});
$task = null;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -183,10 +183,10 @@ public function testLegacyResultIsFinishedBeforeTerminalDispatch(): void
public function testTaskFailureSkipsFinishButStillDispatchesTerminalEvent(): void
{
$exception = new RuntimeException('Task failed.');
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->expects('finish')->never();
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -208,10 +208,10 @@ public function testTaskFailureSkipsFinishButStillDispatchesTerminalEvent(): voi
public function testFinishFailureStillDispatchesTerminalEvent(): void
{
$exception = new RuntimeException('Finish failed.');
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->expects('finish')->throws($exception);
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -235,8 +235,8 @@ public function testFinishFailureStillDispatchesTerminalEvent(): void
public function testTerminalFailurePropagatesAfterSuccessfulTask(): void
{
$exception = new RuntimeException('Terminal dispatch failed.');
- $server = Double::for(Server::class);
- $dispatcher = Double::for(Dispatcher::class);
+ $server = Double::for(Server::class)->strict();
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class));
@@ -259,8 +259,8 @@ public function testTaskFailureRemainsPrimaryWhenTerminalDispatchAlsoFails(): vo
{
$taskException = new RuntimeException('Task failed.');
$terminalException = new RuntimeException('Terminal dispatch failed.');
- $server = Double::for(Server::class);
- $dispatcher = Double::for(Dispatcher::class);
+ $server = Double::for(Server::class)->strict();
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
@@ -284,10 +284,10 @@ public function testFinishFailureRemainsPrimaryWhenTerminalDispatchAlsoFails():
{
$finishException = new RuntimeException('Finish failed.');
$terminalException = new RuntimeException('Terminal dispatch failed.');
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->expects('finish')->throws($finishException);
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(OnTask::class)->returns(true);
$dispatcher->expects('dispatch')
->with(Argument::type(OnTask::class))
diff --git a/tests/Core/Bootstrap/WorkerExitCallbackTest.php b/tests/Core/Bootstrap/WorkerExitCallbackTest.php
index f74fe00fcf..951ab8190f 100644
--- a/tests/Core/Bootstrap/WorkerExitCallbackTest.php
+++ b/tests/Core/Bootstrap/WorkerExitCallbackTest.php
@@ -30,7 +30,7 @@ public function testWorkerExitDoesNotRequireAnotherCoroutineSlot(): void
SwooleCoroutine::set(['max_coroutine' => 1]);
SwooleCoroutine\run(function (): void {
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')
->with(OnWorkerExit::class)
->returns(true);
@@ -38,7 +38,7 @@ public function testWorkerExitDoesNotRequireAnotherCoroutineSlot(): void
->with(Argument::type(OnWorkerExit::class));
$coordinator = CoordinatorManager::until(Constants::WORKER_EXIT);
$callback = new WorkerExitCallback($dispatcher);
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$callback->onWorkerExit($server, 3);
$callback->onWorkerExit($server, 3);
@@ -52,7 +52,7 @@ public function testWorkerExitDoesNotRequireAnotherCoroutineSlot(): void
public function testWorkerExitResumesCoordinationWithoutListeners(): void
{
SwooleCoroutine\run(function (): void {
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')
->with(OnWorkerExit::class)
->returns(false);
@@ -60,8 +60,8 @@ public function testWorkerExitResumesCoordinationWithoutListeners(): void
$coordinator = CoordinatorManager::until(Constants::WORKER_EXIT);
$callback = new WorkerExitCallback($dispatcher);
- $callback->onWorkerExit(Double::for(Server::class), 3);
- $callback->onWorkerExit(Double::for(Server::class), 3);
+ $callback->onWorkerExit(Double::for(Server::class)->strict(), 3);
+ $callback->onWorkerExit(Double::for(Server::class)->strict(), 3);
$this->assertTrue($coordinator->isClosing());
});
@@ -72,14 +72,14 @@ public function testWorkerExitResumesCoordinationWhenAListenerThrows(): void
{
SwooleCoroutine\run(function (): void {
$failure = new RuntimeException('worker exit listener failed');
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')
->with(OnWorkerExit::class)
->returns(true);
$dispatcher->expects('dispatch')->throws($failure);
$coordinator = CoordinatorManager::until(Constants::WORKER_EXIT);
$callback = new WorkerExitCallback($dispatcher);
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
try {
$callback->onWorkerExit($server, 3);
diff --git a/tests/Core/Bootstrap/WorkerStartCallbackTest.php b/tests/Core/Bootstrap/WorkerStartCallbackTest.php
index 6c34137933..2816d27225 100644
--- a/tests/Core/Bootstrap/WorkerStartCallbackTest.php
+++ b/tests/Core/Bootstrap/WorkerStartCallbackTest.php
@@ -30,10 +30,10 @@ class WorkerStartCallbackTest extends TestCase
public function testLifecycleEventsAndStartupLoggingRemainOrdered(): void
{
$sequence = [];
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->taskworker = false;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(BeforeWorkerStart::class)->returns(true);
$dispatcher->expects('hasListeners')->with(MainWorkerStart::class)->returns(true);
$dispatcher->expects('hasListeners')->with(AfterWorkerStart::class)->returns(true);
@@ -56,7 +56,7 @@ public function testLifecycleEventsAndStartupLoggingRemainOrdered(): void
$sequence[] = 'after';
});
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('info')
->with('Worker#0 started.')
->resolves(function () use (&$sequence): void {
@@ -73,16 +73,16 @@ public function testLifecycleEventsAndStartupLoggingRemainOrdered(): void
public function testWorkerStartsAndResumesCoordinationWithoutLifecycleListeners(): void
{
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->taskworker = false;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$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 = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('info')->with('Worker#0 started.');
$coordinator = CoordinatorManager::until(Constants::WORKER_START);
@@ -98,10 +98,10 @@ public function testStartupLoggingUsesConfigurationRefreshedDuringBeforeWorkerSt
]);
$output = new BufferedOutput;
$logger = new StdoutLogger($config, $output);
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->taskworker = false;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(BeforeWorkerStart::class)->returns(true);
$dispatcher->expects('hasListeners')->with(MainWorkerStart::class)->returns(true);
$dispatcher->expects('hasListeners')->with(AfterWorkerStart::class)->returns(true);
@@ -123,10 +123,10 @@ public function testStartupLoggingUsesConfigurationRefreshedDuringBeforeWorkerSt
public function testCustomLoggerOwnsItsConfiguration(): void
{
- $server = Double::for(Server::class);
+ $server = Double::for(Server::class)->strict();
$server->taskworker = true;
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('hasListeners')->with(BeforeWorkerStart::class)->returns(true);
$dispatcher->expects('hasListeners')->with(OtherWorkerStart::class)->returns(true);
$dispatcher->expects('hasListeners')->with(AfterWorkerStart::class)->returns(true);
@@ -134,7 +134,7 @@ public function testCustomLoggerOwnsItsConfiguration(): void
$dispatcher->expects('dispatch')->with(Argument::type(OtherWorkerStart::class));
$dispatcher->expects('dispatch')->with(Argument::type(AfterWorkerStart::class));
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$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 aa1787f0f9..091c9aae85 100644
--- a/tests/Core/StdoutLoggerTest.php
+++ b/tests/Core/StdoutLoggerTest.php
@@ -58,7 +58,7 @@ public function testLogComplexityContext(): void
public function testLogThrowable(): void
{
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$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);
});
@@ -71,7 +71,7 @@ public function testLogThrowable(): void
public function testLevelFiltering(): void
{
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$output->expects('writeln')->never();
$logger = new StdoutLogger(new Repository([
'app' => ['stdout_log' => ['level' => [LogLevel::ERROR], 'format' => 'line']],
@@ -86,7 +86,7 @@ public function testLevelFilteringUsesConstructionTimeConfig(): void
'app' => ['stdout_log' => ['level' => [LogLevel::ERROR], 'format' => 'line']],
]);
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$output->expects('writeln')->with(Argument::any());
$logger = new StdoutLogger($config, $output);
@@ -98,7 +98,7 @@ public function testLevelFilteringUsesConstructionTimeConfig(): void
public function testLineFormat(): void
{
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$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);
@@ -166,7 +166,7 @@ public function testJsonFormatWithThrowable(): void
public function testJsonFormatLevelFiltering(): void
{
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$output->expects('writeln')->never();
$logger = new StdoutLogger(new Repository([
'app' => ['stdout_log' => ['level' => [LogLevel::ERROR], 'format' => 'json']],
@@ -248,7 +248,7 @@ public function __toString(): string
throw $this->cancellation;
}
};
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$output->expects('writeln')->never();
$logger = new StdoutLogger(new Repository([
'app' => ['stdout_log' => ['level' => [LogLevel::INFO], 'format' => 'line']],
@@ -425,7 +425,7 @@ public function jsonSerialize(): never
throw $this->cancellation;
}
};
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$output->expects('writeln')->never();
$logger = new StdoutLogger(new Repository([
'app' => ['stdout_log' => ['level' => [LogLevel::INFO], 'format' => 'json']],
@@ -445,7 +445,7 @@ public function jsonSerialize(): never
*/
protected function getLineLogger(string $expectedPattern): StdoutLogger
{
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$output->expects('writeln')->with(Argument::any())->resolves(function ($message) use ($expectedPattern) {
$this->assertMatchesRegularExpression($expectedPattern, $message);
});
@@ -460,7 +460,7 @@ protected function getLineLogger(string $expectedPattern): StdoutLogger
protected function logJson(string $level, string|Stringable $message, array $context = []): array
{
$captured = null;
- $output = Double::for(OutputInterface::class);
+ $output = Double::for(OutputInterface::class)->strict();
$output->expects('writeln')
->with(Argument::capture($captured), OutputInterface::OUTPUT_RAW);
diff --git a/tests/Coroutine/ConcurrentTest.php b/tests/Coroutine/ConcurrentTest.php
index 3c70422dc8..3dd5b3ff41 100644
--- a/tests/Coroutine/ConcurrentTest.php
+++ b/tests/Coroutine/ConcurrentTest.php
@@ -15,6 +15,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Swoole\Coroutine;
@@ -140,7 +141,7 @@ public function testWaitForAvailableSlotConvertsNonThrowingCancellation(): void
#[DataProvider('creationMethods')]
public function testCreationCancellationWhileStartupReportingYieldsReleasesItsSlotOnce(string $method): void
{
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
Container::getInstance()->instance(ExceptionHandlerContract::class, $handler);
$concurrent = new ConcurrentTestConcurrent(1);
$hookFailure = new RuntimeException('The startup hook failed.');
@@ -152,7 +153,7 @@ public function testCreationCancellationWhileStartupReportingYieldsReleasesItsSl
$childBodyRan = false;
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
diff --git a/tests/Coroutine/CoroutineTest.php b/tests/Coroutine/CoroutineTest.php
index 4e38f27629..996f88b20d 100644
--- a/tests/Coroutine/CoroutineTest.php
+++ b/tests/Coroutine/CoroutineTest.php
@@ -22,6 +22,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use PHPUnit\Framework\Attributes\TestWith;
@@ -265,12 +266,12 @@ public function testCoroutineParentIdHasBeenDestroyed(): void
public function testCoroutineAndDeferWithException(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$container->instance(ExceptionHandlerContract::class, $handler);
Container::setInstance($container);
$exception = new Exception;
- $handler->expects('report')->with($exception)->times(2);
+ $handler->expects('report')->with(Argument::same($exception))->times(2);
go(static function () use ($exception): never {
Coroutine::defer(static fn () => throw $exception);
@@ -282,7 +283,7 @@ public function testCoroutineAndDeferWithException(): void
public function testTerminalCancellationIsNotReported(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$handler->expects('report')->never();
$container->instance(ExceptionHandlerContract::class, $handler);
Container::setInstance($container);
@@ -299,9 +300,9 @@ public function testTerminalCancellationIsNotReported(): void
public function testTerminalBoundaryReportsCleanupFailureDuringCancellationOnce(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$failure = new RuntimeException('Coroutine cleanup failed.');
- $handler->expects('report')->with($failure);
+ $handler->expects('report')->with(Argument::same($failure));
$container->instance(ExceptionHandlerContract::class, $handler);
Container::setInstance($container);
$blocker = new Channel(1);
@@ -329,13 +330,13 @@ public function testTerminalBoundaryReportsCleanupFailureDuringCancellationOnce(
public function testTerminalBoundaryContainsCancellationDuringReporting(bool $cleanupFails): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$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->expects('report')->with($failure)
+ $handler->expects('report')->with(Argument::same($failure))
->resolves(static function () use ($blocker, $cleanupFails, $cleanupFailure): void {
try {
$blocker->pop();
@@ -511,7 +512,7 @@ public function testExceptionReportingCanBeRestored(bool $flushState): void
{
try {
$container = new Container;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$container->instance(ExceptionHandlerContract::class, $handler);
Container::setInstance($container);
@@ -539,7 +540,7 @@ public function testExceptionReportingCanBeRestored(bool $flushState): void
public function testAfterCreatedCallbackExceptionDoesNotStopOthers(): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$container->instance(ExceptionHandlerContract::class, $handler);
Container::setInstance($container);
$handler->expects('report');
@@ -568,7 +569,7 @@ public function testAfterCreatedCallbackExceptionDoesNotStopOthers(): void
public function testOwnedCoroutineTransfersOwnershipBeforeStartupFailureReportingCanSuspend(bool $cleanupFails): void
{
$container = new Container;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$container->instance(ExceptionHandlerContract::class, $handler);
Container::setInstance($container);
CoroutineContext::set('request-id', 'child-request');
@@ -583,7 +584,7 @@ public function testOwnedCoroutineTransfersOwnershipBeforeStartupFailureReportin
$mainCallableRan = false;
$handler->expects('report')
- ->with($exception)
+ ->with(Argument::same($exception))
->resolves(static function () use ($reportStarted, $releaseReport, &$reportedContext, $cleanupFails, $cleanupFailure): void {
$reportedContext = CoroutineContext::get('request-id');
$reportStarted->push(true);
@@ -597,7 +598,7 @@ public function testOwnedCoroutineTransfersOwnershipBeforeStartupFailureReportin
});
if ($cleanupFails) {
- $handler->expects('report')->with($cleanupFailure);
+ $handler->expects('report')->with(Argument::same($cleanupFailure));
}
Coroutine::afterCreated(static function () use ($exception): void {
@@ -660,7 +661,7 @@ public function testExceptionHandlerFailureFallsBackToThePhpErrorLog(): void
try {
$container = new Container;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$handler->expects('report')
->throws(new RuntimeException('The exception reporter failed.'));
$container->instance(ExceptionHandlerContract::class, $handler);
diff --git a/tests/Coroutine/ParallelTest.php b/tests/Coroutine/ParallelTest.php
index a8a39d273b..2240825474 100644
--- a/tests/Coroutine/ParallelTest.php
+++ b/tests/Coroutine/ParallelTest.php
@@ -21,6 +21,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Swoole\Coroutine as SwooleCoroutine;
@@ -567,7 +568,7 @@ public function testNonThrowingCancellationWhileWaitingForCapacityDoesNotStartAn
public function testCreationCancellationWhileStartupReportingYieldsReleasesOwnership(): void
{
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
Container::getInstance()->instance(ExceptionHandlerContract::class, $handler);
$parallel = new Parallel(1);
$hookFailure = new RuntimeException('The startup hook failed.');
@@ -582,7 +583,7 @@ public function testCreationCancellationWhileStartupReportingYieldsReleasesOwner
$failStartup = true;
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
diff --git a/tests/Coroutine/SignalRegistryRollbackTest.php b/tests/Coroutine/SignalRegistryRollbackTest.php
index 73bcf6fe31..6b9aff3345 100644
--- a/tests/Coroutine/SignalRegistryRollbackTest.php
+++ b/tests/Coroutine/SignalRegistryRollbackTest.php
@@ -15,6 +15,7 @@
use Hypervel\Tests\TestCase;
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;
@@ -55,7 +56,7 @@ public function testPartialArrayRegistrationRollsBackHandlersAndWaiters(): void
public function testUnregisterTerminallyCancelsItsWaiterWithoutReporting(): void
{
SwooleCoroutine\run(function (): void {
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$handler->expects('report')->never();
Container::getInstance()->instance(ExceptionHandlerContract::class, $handler);
@@ -134,10 +135,10 @@ protected function cancelOwnerDuringCreation(int $creation): Channel
$releaseReport = new Channel(1);
$parentCoroutineId = EngineCoroutine::id();
$reports = 0;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$handler->expects('report')
->times($creation)
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->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 f50abfa94e..52287182da 100644
--- a/tests/Coroutine/SignalRegistryTest.php
+++ b/tests/Coroutine/SignalRegistryTest.php
@@ -14,6 +14,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use RuntimeException;
use stdClass;
@@ -137,8 +138,8 @@ public function testInterleavedOwnersRetainOrderAndIsolateCallbackFailuresAndCon
$handled = new Channel(1);
$trace = [];
$exception = new RuntimeException('Signal callback failed');
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->times(2)->with($exception);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->times(2)->with(Argument::same($exception));
Container::getInstance()->instance(ExceptionHandler::class, $handler);
try {
diff --git a/tests/Coroutine/WaitConcurrentTest.php b/tests/Coroutine/WaitConcurrentTest.php
index cb96137da7..376e1c7e83 100644
--- a/tests/Coroutine/WaitConcurrentTest.php
+++ b/tests/Coroutine/WaitConcurrentTest.php
@@ -15,6 +15,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Swoole\Coroutine\CanceledException;
@@ -61,7 +62,7 @@ public function testForkBalancesWaitTrackingWhenContextReplicationFails(): void
#[DataProvider('creationMethods')]
public function testCreationCancellationWhileStartupReportingYieldsReleasesOwnershipOnce(string $method): void
{
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
Container::getInstance()->instance(ExceptionHandlerContract::class, $handler);
$concurrent = new WaitConcurrent(1);
$hookFailure = new RuntimeException('The startup hook failed.');
@@ -73,7 +74,7 @@ public function testCreationCancellationWhileStartupReportingYieldsReleasesOwner
$childBodyRan = false;
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
diff --git a/tests/Coroutine/WaiterTest.php b/tests/Coroutine/WaiterTest.php
index c43e1f243d..b26a9cb45b 100644
--- a/tests/Coroutine/WaiterTest.php
+++ b/tests/Coroutine/WaiterTest.php
@@ -20,6 +20,7 @@
use Hypervel\Tests\TestCase;
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;
@@ -171,7 +172,7 @@ public function testWaitException(): void
#[DataProvider('copyContexts')]
public function testParentCancellationDuringStartupReportingCancelsThePublishedChild(bool $copyContext): void
{
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
Container::getInstance()->instance(ExceptionHandlerContract::class, $handler);
$waiter = new Waiter;
$hookFailure = new RuntimeException('The startup hook failed.');
@@ -183,7 +184,7 @@ public function testParentCancellationDuringStartupReportingCancelsThePublishedC
$childBodyRan = false;
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
diff --git a/tests/Data/DataServiceProviderTest.php b/tests/Data/DataServiceProviderTest.php
index c7b5f87579..d776a0380b 100644
--- a/tests/Data/DataServiceProviderTest.php
+++ b/tests/Data/DataServiceProviderTest.php
@@ -57,8 +57,8 @@ public function testProviderWarmsFixedServicesAfterNonTestingApplicationBoot():
$application->instance('config', new Repository);
$application->setRunningInConsole(false);
- $creator = Double::for(DataCreator::class);
- $transformer = Double::for(DataTransformer::class);
+ $creator = Double::for(DataCreator::class)->strict();
+ $transformer = Double::for(DataTransformer::class)->strict();
$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 9703673576..cc8e529e46 100644
--- a/tests/Data/Support/Creation/DataCollectTest.php
+++ b/tests/Data/Support/Creation/DataCollectTest.php
@@ -221,7 +221,7 @@ public function testCollectBuildsExplicitPaginatorWrappersWithoutMutatingTheSour
public function testContractOnlyPaginatorCanTargetANonPaginatorWithoutCollectMethodDispatch(): void
{
- $paginator = Double::for(PaginatorContract::class);
+ $paginator = Double::for(PaginatorContract::class)->strict();
$paginator->expects('items')->returns([
['id' => '1'],
]);
diff --git a/tests/Data/Transformers/ArrayableTransformerTest.php b/tests/Data/Transformers/ArrayableTransformerTest.php
index 0141986e2e..a4bcf8de02 100644
--- a/tests/Data/Transformers/ArrayableTransformerTest.php
+++ b/tests/Data/Transformers/ArrayableTransformerTest.php
@@ -21,7 +21,7 @@ public function testCanTransformAnArrayable(): void
$value = new Collection(['A', 'B']);
$result = (new ArrayableTransformer)->transform(
- Double::for(DataProperty::class),
+ Double::for(DataProperty::class)->strict(),
$value,
new TransformationContext,
);
diff --git a/tests/Data/Transformers/DateTimeInterfaceTransformerTest.php b/tests/Data/Transformers/DateTimeInterfaceTransformerTest.php
index 7cca9c9881..bac858c991 100644
--- a/tests/Data/Transformers/DateTimeInterfaceTransformerTest.php
+++ b/tests/Data/Transformers/DateTimeInterfaceTransformerTest.php
@@ -77,7 +77,7 @@ protected function transform(
DateTimeInterface $date,
): string {
return $transformer->transform(
- Double::for(DataProperty::class),
+ Double::for(DataProperty::class)->strict(),
$date,
new TransformationContext,
);
diff --git a/tests/Data/Transformers/EnumTransformerTest.php b/tests/Data/Transformers/EnumTransformerTest.php
index 3735e4ec63..d6835331f1 100644
--- a/tests/Data/Transformers/EnumTransformerTest.php
+++ b/tests/Data/Transformers/EnumTransformerTest.php
@@ -18,7 +18,7 @@ class EnumTransformerTest extends TestCase
public function testCanTransformEnums(): void
{
$transformer = new EnumTransformer;
- $property = Double::for(DataProperty::class);
+ $property = Double::for(DataProperty::class)->strict();
$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 8cc48ed8bc..a697f0b695 100644
--- a/tests/Data/Transformers/SerializeTransformerTest.php
+++ b/tests/Data/Transformers/SerializeTransformerTest.php
@@ -22,7 +22,7 @@ public function testCanTransformUsingASerializer(): void
$this->assertSame(
serialize(DummyBackedEnum::FOO),
- $transformer->transform(Double::for(DataProperty::class), DummyBackedEnum::FOO, new TransformationContext)
+ $transformer->transform(Double::for(DataProperty::class)->strict(), DummyBackedEnum::FOO, new TransformationContext)
);
}
}
diff --git a/tests/Database/ConnectionResolverTest.php b/tests/Database/ConnectionResolverTest.php
index 377eb2666c..7ff38c0dca 100644
--- a/tests/Database/ConnectionResolverTest.php
+++ b/tests/Database/ConnectionResolverTest.php
@@ -134,16 +134,16 @@ public function testNestedOverrideRestoresExactPriorValue(): void
public function testNonCoroutineConnectionIsRetainedUntilTerminalRelease(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $firstWrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $firstWrapper = Double::for(PooledConnection::class)->strict();
$firstWrapper->allows('recordDateFormat');
$firstWrapper->allows('usesSessionLeases')->returns(false);
- $secondWrapper = Double::for(PooledConnection::class);
+ $secondWrapper = Double::for(PooledConnection::class)->strict();
$secondWrapper->allows('recordDateFormat');
$secondWrapper->allows('usesSessionLeases')->returns(false);
- $firstConnection = Double::for(Connection::class);
- $secondConnection = Double::for(Connection::class);
+ $firstConnection = Double::for(Connection::class)->strict();
+ $secondConnection = Double::for(Connection::class)->strict();
$poolManager->expects('pool')->times(2)->with('mysql')->returns($pool);
$pool->allows('getSharedInMemorySqlitePdo')->returns(null);
@@ -169,15 +169,15 @@ public function testNonCoroutineConnectionIsRetainedUntilTerminalRelease(): void
public function testTerminalReleaseOwnsEveryRequestedConnectionRole(): void
{
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$resolver = $this->makeResolver('mysql', $poolManager);
foreach (['mysql' => null, 'mysql::read' => 'read', 'mysql::write' => 'write'] as $name => $role) {
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('recordDateFormat');
$wrapper->allows('usesSessionLeases')->returns(false);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$poolManager->expects('pool')->with($name)->returns($pool);
$pool->allows('getSharedInMemorySqlitePdo')->returns(null);
@@ -202,14 +202,14 @@ public function testTerminalReleaseOwnsEveryRequestedConnectionRole(): void
public function testBorrowedConnectionRetainsItsRequestedRole(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
$resolver = $this->makeResolver('sqlite', $poolManager);
$pool->allows('getSharedInMemorySqlitePdo')->returns(null);
$wrappers = [
- 'sqlite::write' => Double::for(PooledConnection::class),
- 'sqlite' => Double::for(PooledConnection::class),
+ 'sqlite::write' => Double::for(PooledConnection::class)->strict(),
+ 'sqlite' => Double::for(PooledConnection::class)->strict(),
];
$pool->expects('borrow')->times(2)->returns(...array_values($wrappers));
@@ -231,16 +231,16 @@ public function testBorrowedConnectionRetainsItsRequestedRole(): void
public function testSharedInMemorySqliteAliasesReuseOneConnectionOwner(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('recordDateFormat');
$wrapper->allows('usesSessionLeases')->returns(false);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$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('getSharedInMemorySqlitePdo')->times(2)->returns(Double::for(PDO::class)->strict());
$pool->expects('getName')->times(2)->returns('sqlite');
$pool->expects('borrow')->returns($wrapper);
$wrapper->expects('getConnection')->returns($connection);
@@ -259,16 +259,16 @@ public function testSharedInMemorySqliteAliasesReuseOneConnectionOwner(): void
public function testTerminalStateRemainsAvailableUntilItsOwnerIsReleased(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $firstWrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $firstWrapper = Double::for(PooledConnection::class)->strict();
$firstWrapper->allows('recordDateFormat');
$firstWrapper->allows('usesSessionLeases')->returns(false);
- $secondWrapper = Double::for(PooledConnection::class);
+ $secondWrapper = Double::for(PooledConnection::class)->strict();
$secondWrapper->allows('recordDateFormat');
$secondWrapper->allows('usesSessionLeases')->returns(false);
- $firstConnection = Double::for(Connection::class);
- $secondConnection = Double::for(Connection::class);
+ $firstConnection = Double::for(Connection::class)->strict();
+ $secondConnection = Double::for(Connection::class)->strict();
$poolManager->expects('pool')->times(2)->with('mysql')->returns($pool);
$pool->allows('getSharedInMemorySqlitePdo')->returns(null);
@@ -299,22 +299,22 @@ public function testTerminalReleaseExhaustsConnectionsAndPreservesTheFirstFailur
{
$firstException = new RuntimeException('First release failed.');
$secondException = new RuntimeException('Second release failed.');
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$resolver = $this->makeResolver('first', $poolManager);
foreach ([
['first', $firstException],
['second', $secondException],
] as [$name, $exception]) {
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$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('getConnection')->returns(Double::for(Connection::class)->strict());
$wrapper->expects('dispatchConnectionEstablishedEvent');
$wrapper->expects('release')->throws($exception);
@@ -341,7 +341,7 @@ public function testTerminalReleasePrioritizesTheFirstCancellationAndStillExhaus
$firstCancellation = new RuntimeException('Release cleanup failed.', previous: $firstCancellation);
}
$secondCancellation = new CanceledException('Third release was canceled.');
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$resolver = $this->makeResolver('first', $poolManager);
foreach ([
@@ -349,15 +349,15 @@ public function testTerminalReleasePrioritizesTheFirstCancellationAndStillExhaus
['second', $firstCancellation],
['third', $secondCancellation],
] as [$name, $failure]) {
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$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('getConnection')->returns(Double::for(Connection::class)->strict());
$wrapper->expects('dispatchConnectionEstablishedEvent');
$wrapper->expects('release')->throws($failure);
@@ -376,19 +376,19 @@ public function testTerminalReleasePrioritizesTheFirstCancellationAndStillExhaus
public function testTerminalDiscardExhaustsExactConnections(): void
{
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$resolver = $this->makeResolver('first', $poolManager);
foreach (['first', 'second'] as $name) {
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$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('getConnection')->returns(Double::for(Connection::class)->strict());
$wrapper->expects('dispatchConnectionEstablishedEvent');
$wrapper->expects('discard');
@@ -402,9 +402,9 @@ public function testTerminalDiscardExhaustsExactConnections(): void
public function testConnectionRetrievalFailureDiscardsTheExactWrapper(): void
{
$exception = new RuntimeException('Connection retrieval failed.');
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('usesSessionLeases')->returns(false);
$poolManager->expects('pool')->with('mysql')->returns($pool);
@@ -426,15 +426,15 @@ public function testConnectionRetrievalFailureDiscardsTheExactWrapper(): void
public function testListenerFailureDiscardsTheExactWrapperWithoutDeferringRelease(): void
{
$exception = new RuntimeException('Connection listener failed.');
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$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('getConnection')->returns(Double::for(Connection::class)->strict());
$wrapper->expects('dispatchConnectionEstablishedEvent')->throws($exception);
$wrapper->expects('discard');
$wrapper->expects('release')->never();
@@ -456,11 +456,11 @@ public function testListenerFailureDiscardsTheExactWrapperWithoutDeferringReleas
public function testWriteRoleConfigurationFailureDiscardsTheExactWrapper(): void
{
$exception = new RuntimeException('Write role configuration failed.');
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('usesSessionLeases')->returns(false);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$poolManager->expects('pool')->with('mysql::write')->returns($pool);
$pool->allows('getSharedInMemorySqlitePdo')->returns(null);
@@ -484,9 +484,9 @@ public function testDiscardFailureDoesNotReplaceTheSetupFailure(): void
{
$setupException = new RuntimeException('Connection retrieval failed.');
$discardException = new RuntimeException('Discard failed.');
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('usesSessionLeases')->returns(false);
$poolManager->expects('pool')->with('mysql')->returns($pool);
@@ -512,9 +512,9 @@ 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 = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('usesSessionLeases')->returns(false);
$poolManager->expects('pool')->with('mysql')->returns($pool);
@@ -537,9 +537,9 @@ public function testSetupCancellationRemainsPrimaryOverAnOrdinaryDiscardFailure(
{
$setupCancellation = new CanceledException('Connection setup was canceled.');
$discardException = new RuntimeException('Discard failed.');
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('usesSessionLeases')->returns(false);
$poolManager->expects('pool')->with('mysql')->returns($pool);
@@ -565,9 +565,9 @@ 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 = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('usesSessionLeases')->returns(false);
$poolManager->expects('pool')->with('mysql')->returns($pool);
@@ -588,12 +588,12 @@ public function testSetupCancellationRemainsPrimaryOverDiscardCancellation(bool
public function testCoroutineConnectionRemainsDeferOwned(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('recordDateFormat');
$wrapper->allows('usesSessionLeases')->returns(false);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$poolManager->expects('pool')->with('mysql')->returns($pool);
$pool->allows('getSharedInMemorySqlitePdo')->returns(null);
@@ -614,8 +614,8 @@ public function testCoroutineConnectionRemainsDeferOwned(): void
public function testConnectionDateFormatReadsThePoolsRecordWithoutBorrowing(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
$poolManager->expects('existing')->with('pgsql')->returns($pool);
$poolManager->expects('existing')->with('pgsql::write')->returns($pool);
$poolManager->expects('pool')->never();
@@ -633,9 +633,9 @@ public function testConnectionDateFormatReadsThePoolsRecordWithoutBorrowing(): v
public function testConnectionDateFormatPrefersTheGrammarOfAHeldConnection(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$wrapper->allows('usesSessionLeases')->returns(false);
$connection = new PdoConnection(new PDO('sqlite::memory:'), config: ['name' => 'sqlite']);
$poolManager->expects('pool')->with('sqlite')->returns($pool);
@@ -661,15 +661,15 @@ public function testConnectionDateFormatPrefersTheGrammarOfAHeldConnection(): vo
public function testSharedInMemorySqliteAliasesReadTheFormatOfTheirHeldOwner(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$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')->returns($pool);
$poolManager->expects('existing')->with('sqlite::read')->returns($pool);
- $pool->allows('getSharedInMemorySqlitePdo')->returns(Double::for(PDO::class));
+ $pool->allows('getSharedInMemorySqlitePdo')->returns(Double::for(PDO::class)->strict());
$pool->allows('getName')->returns('sqlite');
$wrapper->expects('recordDateFormat');
$pool->expects('recordedDateFormat')->never();
@@ -688,9 +688,9 @@ public function testSharedInMemorySqliteAliasesReadTheFormatOfTheirHeldOwner():
public function testConnectionDateFormatResolvesTheConnectionWhileNoOpenPoolHasRecordedOne(): void
{
- $poolManager = Double::for(PoolManager::class);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$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.
@@ -718,7 +718,7 @@ protected function makeResolver(
$app->instance('config', new Repository([
'database' => ['default' => $configuredDefault],
]));
- $app->instance(PoolManager::class, $poolManager ?? Double::for(PoolManager::class));
+ $app->instance(PoolManager::class, $poolManager ?? Double::for(PoolManager::class)->strict());
return new ConnectionResolver($app);
}
diff --git a/tests/Database/ConnectionTest.php b/tests/Database/ConnectionTest.php
index 07e214169e..7b65e4f69e 100644
--- a/tests/Database/ConnectionTest.php
+++ b/tests/Database/ConnectionTest.php
@@ -110,7 +110,7 @@ public function testDisconnectCancellationFromTransactionResetSupersedesAnOrdina
$resetCancellation = new CanceledException('Transaction reset was canceled.');
$connection = new DisconnectFailureConnection(new PDO('sqlite::memory:'));
$connection->disconnectFailure = $driverFailure;
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('rollback')->with('', 0)->throws($resetCancellation);
$connection->setTransactionManager($manager);
@@ -130,7 +130,7 @@ public function testDisconnectPreservesDriverCancellationOverAnOrdinaryTransacti
$resetFailure = new RuntimeException('Transaction reset failed.');
$connection = new DisconnectFailureConnection(new PDO('sqlite::memory:'));
$connection->disconnectFailure = $driverCancellation;
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('rollback')->with('', 0)->throws($resetFailure);
$connection->setTransactionManager($manager);
@@ -150,7 +150,7 @@ public function testDisconnectPreservesTheFirstCancellationWhenTransactionResetI
$resetCancellation = new CanceledException('Transaction reset was canceled.');
$connection = new DisconnectFailureConnection(new PDO('sqlite::memory:'));
$connection->disconnectFailure = $driverCancellation;
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('rollback')->with('', 0)->throws($resetCancellation);
$connection->setTransactionManager($manager);
@@ -170,7 +170,7 @@ public function testDisconnectPreservesTheFirstOrdinaryFailureAfterTransactionRe
$resetFailure = new RuntimeException('Transaction reset failed.');
$connection = new DisconnectFailureConnection(new PDO('sqlite::memory:'));
$connection->disconnectFailure = $driverFailure;
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('rollback')->with('', 0)->throws($resetFailure);
$connection->setTransactionManager($manager);
diff --git a/tests/Database/DatabaseAbstractSchemaGrammarTest.php b/tests/Database/DatabaseAbstractSchemaGrammarTest.php
index 4c35058ad3..1f6f25f029 100755
--- a/tests/Database/DatabaseAbstractSchemaGrammarTest.php
+++ b/tests/Database/DatabaseAbstractSchemaGrammarTest.php
@@ -41,7 +41,7 @@ public function testDropDatabaseIfExists(): void
#[TestWith(['compileCreateRangePartition', ['users', 'users_1', [1], [2]]])]
public function testPartitioningIsUnsupportedByDefault(string $method, array $arguments): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new class($connection) extends Grammar {
};
diff --git a/tests/Database/DatabaseApplicableTransactionTest.php b/tests/Database/DatabaseApplicableTransactionTest.php
index 11ba24c867..db30b0c6a4 100644
--- a/tests/Database/DatabaseApplicableTransactionTest.php
+++ b/tests/Database/DatabaseApplicableTransactionTest.php
@@ -102,7 +102,7 @@ public function testCurrentDefaultAndSharedSqliteRoleAliasesUseTheirHeldConnecti
public function testCustomManagerResolversProvideTransactionStateAndDateFormat(): void
{
$connection = DB::connection('first');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with('first')->times(3)->returns($connection);
$this->app->instance('db.resolver', $resolver);
@@ -135,7 +135,7 @@ public function testCustomModelResolversUseTheirActualConnection(): void
{
$connection = DB::connection('second');
$connection->beginTransaction();
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with(null)->returns($connection);
Model::setConnectionResolver($resolver);
diff --git a/tests/Database/DatabaseConnectionFactoryTest.php b/tests/Database/DatabaseConnectionFactoryTest.php
index 5e5c8202cb..14cb6ef200 100755
--- a/tests/Database/DatabaseConnectionFactoryTest.php
+++ b/tests/Database/DatabaseConnectionFactoryTest.php
@@ -322,8 +322,8 @@ public function testReadWriteConnectionSetsReadConnectionConfig(): void
public function testReadEndpointMetadataMatchesTheSelectedPdoConfiguration(): void
{
$container = new Container;
- $pdo = Double::for(PDO::class);
- $connector = Double::for(ConnectorInterface::class);
+ $pdo = Double::for(PDO::class)->strict();
+ $connector = Double::for(ConnectorInterface::class)->strict();
$connector->expects('connect')->with(Argument::satisfies(
static fn (array $config): bool => $config['host'] === 'first-reader'
&& $config['options'][PDO::ATTR_EMULATE_PREPARES] === true
@@ -361,7 +361,7 @@ public function testExceptionIsThrownOnUnsupportedDriver(): void
{
$this->expectExceptionObject(new InvalidArgumentException('Unsupported driver [foo]'));
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('bound')->returns(false);
$factory = new ConnectionFactory($container->instance());
$factory->createConnector(['driver' => 'foo']);
@@ -369,8 +369,8 @@ public function testExceptionIsThrownOnUnsupportedDriver(): void
public function testCustomConnectorsCanBeResolvedViaContainer(): void
{
- $connector = Double::for(ConnectorInterface::class);
- $container = Double::for(Container::class, override: true);
+ $connector = Double::for(ConnectorInterface::class)->strict();
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('bound')->with('db.connector.foo')->returns(true);
$container->expects('make')->with('db.connector.foo')->returns($connector);
$factory = new ConnectionFactory($container->instance());
@@ -520,7 +520,7 @@ public function testExtensionCallbackReceivesConfigAndName(): void
public function testConfigFirstExtensionCreatesNeutralConnectionWithoutResolvingAConnector(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$factory = new ConnectionFactory($container->instance());
$receivedConfig = null;
diff --git a/tests/Database/DatabaseConnectionLeaseTest.php b/tests/Database/DatabaseConnectionLeaseTest.php
index b3d44188ae..42e27c60c5 100644
--- a/tests/Database/DatabaseConnectionLeaseTest.php
+++ b/tests/Database/DatabaseConnectionLeaseTest.php
@@ -156,6 +156,27 @@ public function testRetainedBuildersAndCallerStateSurviveAnotherBorrower(): void
$this->assertCount($queries, $connection->getQueryLog());
}
+ #[TestWith([false])]
+ #[TestWith([true])]
+ public function testIdleReleaseContinuesAfterFailureAndGivesCancellationPriority(bool $cancel): void
+ {
+ $firstFailure = new RuntimeException('First release failed.');
+ $secondFailure = $cancel ? new CanceledException('Second release canceled.') : new RuntimeException('Second release failed.');
+
+ foreach (['first' => $firstFailure, 'second' => $secondFailure] as $name => $failure) {
+ $lease = Double::for(ConnectionLease::class)->strict();
+ $lease->expects('releaseIfIdle')->throws($failure);
+ CoroutineContext::set($name, $lease);
+ }
+
+ try {
+ DB::releaseIdleConnections();
+ $this->fail('Expected idle release to propagate a failure.');
+ } catch (Throwable $exception) {
+ $this->assertSame($cancel ? $secondFailure : $firstFailure, $exception);
+ }
+ }
+
public function testConcurrentExternalWaitsDoNotRetainTheOnlyPoolSlot(): void
{
$ready = new Channel(2);
@@ -1025,8 +1046,8 @@ public function testAcquisitionCleanupPropagatesWrappedCancellation(): void
'database' => ':memory:',
'prefix' => '',
]);
- $pool = Double::for(DatabasePool::class);
- $wrapper = Double::for(PooledConnection::class);
+ $pool = Double::for(DatabasePool::class)->strict();
+ $wrapper = Double::for(PooledConnection::class)->strict();
$pool->expects('borrow')->returns($wrapper);
$wrapper->expects('attachLease')->times(2);
$wrapper->expects('getDriverConnection')->returns($physical);
diff --git a/tests/Database/DatabaseConnectionLifecycleListenerTest.php b/tests/Database/DatabaseConnectionLifecycleListenerTest.php
index b3ecc74c3d..faf6793a7e 100644
--- a/tests/Database/DatabaseConnectionLifecycleListenerTest.php
+++ b/tests/Database/DatabaseConnectionLifecycleListenerTest.php
@@ -21,7 +21,7 @@ class DatabaseConnectionLifecycleListenerTest extends TestCase
public function testTaskCleanupDoesNotResolveAnUnusedResolver(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(false);
$container->expects('make')->never();
@@ -30,9 +30,9 @@ public function testTaskCleanupDoesNotResolveAnUnusedResolver(): void
public function testTaskCleanupReleasesTheConcretePooledResolver(): void
{
- $resolver = Double::for(ConnectionResolver::class);
+ $resolver = Double::for(ConnectionResolver::class)->strict();
$resolver->expects('releaseConnections');
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(true);
$container->expects('make')->with('db.resolver')->returns($resolver);
@@ -42,7 +42,7 @@ public function testTaskCleanupReleasesTheConcretePooledResolver(): void
public function testTaskCleanupLeavesCustomResolversAlone(): void
{
$resolver = Double::for(SimpleConnectionResolver::class)->strict();
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(true);
$container->expects('make')->with('db.resolver')->returns($resolver);
@@ -51,7 +51,7 @@ public function testTaskCleanupLeavesCustomResolversAlone(): void
public function testProcessCleanupDoesNotResolveUnusedOwners(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(false);
$container->expects('resolved')->with(PoolManager::class)->returns(false);
$container->expects('make')->never();
@@ -61,11 +61,11 @@ public function testProcessCleanupDoesNotResolveUnusedOwners(): void
public function testProcessCleanupDiscardsResolverAndPurgesPools(): void
{
- $resolver = Double::for(ConnectionResolver::class);
+ $resolver = Double::for(ConnectionResolver::class)->strict();
$resolver->expects('discardConnections');
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$poolManager->expects('purgeAll');
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(true);
$container->expects('make')->with('db.resolver')->returns($resolver);
$container->expects('resolved')->with(PoolManager::class)->returns(true);
@@ -78,11 +78,11 @@ public function testResolverFailureDoesNotSkipPoolPurgeAndRemainsPrimary(): void
{
$resolverException = new RuntimeException('Resolver discard failed.');
$purgeException = new RuntimeException('Pool purge failed.');
- $resolver = Double::for(ConnectionResolver::class);
+ $resolver = Double::for(ConnectionResolver::class)->strict();
$resolver->expects('discardConnections')->throws($resolverException);
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$poolManager->expects('purgeAll')->throws($purgeException);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(true);
$container->expects('make')->with('db.resolver')->returns($resolver);
$container->expects('resolved')->with(PoolManager::class)->returns(true);
@@ -99,11 +99,11 @@ public function testResolverFailureDoesNotSkipPoolPurgeAndRemainsPrimary(): void
public function testPoolPurgeFailurePropagatesAfterResolverCleanup(): void
{
$exception = new RuntimeException('Pool purge failed.');
- $resolver = Double::for(ConnectionResolver::class);
+ $resolver = Double::for(ConnectionResolver::class)->strict();
$resolver->expects('discardConnections');
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$poolManager->expects('purgeAll')->throws($exception);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(true);
$container->expects('make')->with('db.resolver')->returns($resolver);
$container->expects('resolved')->with(PoolManager::class)->returns(true);
@@ -121,11 +121,11 @@ public function testPoolPurgeCancellationSupersedesAnOrdinaryResolverFailure():
{
$resolverException = new RuntimeException('Resolver discard failed.');
$purgeCancellation = new CanceledException('Pool purge was canceled.');
- $resolver = Double::for(ConnectionResolver::class);
+ $resolver = Double::for(ConnectionResolver::class)->strict();
$resolver->expects('discardConnections')->throws($resolverException);
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$poolManager->expects('purgeAll')->throws($purgeCancellation);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(true);
$container->expects('make')->with('db.resolver')->returns($resolver);
$container->expects('resolved')->with(PoolManager::class)->returns(true);
@@ -143,11 +143,11 @@ public function testResolverCancellationRemainsPrimaryOverAnOrdinaryPoolPurgeFai
{
$resolverCancellation = new CanceledException('Resolver discard was canceled.');
$purgeException = new RuntimeException('Pool purge failed.');
- $resolver = Double::for(ConnectionResolver::class);
+ $resolver = Double::for(ConnectionResolver::class)->strict();
$resolver->expects('discardConnections')->throws($resolverCancellation);
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$poolManager->expects('purgeAll')->throws($purgeException);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('resolved')->with('db.resolver')->returns(true);
$container->expects('make')->with('db.resolver')->returns($resolver);
$container->expects('resolved')->with(PoolManager::class)->returns(true);
diff --git a/tests/Database/DatabaseConnectionTest.php b/tests/Database/DatabaseConnectionTest.php
index f190ab2d79..e1c1fc811d 100755
--- a/tests/Database/DatabaseConnectionTest.php
+++ b/tests/Database/DatabaseConnectionTest.php
@@ -110,7 +110,7 @@ public function testConfiglessQueryFailureRetainsTheOriginalDatabaseException():
public function testConfiglessDatabaseEventsRetainTheNullableConnectionName(): void
{
$queryConnection = new PdoConnection(new PDO('sqlite::memory:'));
- $queryConnection->setEventDispatcher($queryEvents = Double::for(Dispatcher::class));
+ $queryConnection->setEventDispatcher($queryEvents = Double::for(Dispatcher::class)->strict());
$queryEvents->expects('hasListeners')->with(QueryExecuted::class)->returns(true);
$queryEvents->expects('dispatch')->with(Argument::satisfies(
static fn (object $event): bool => $event instanceof QueryExecuted
@@ -120,7 +120,7 @@ public function testConfiglessDatabaseEventsRetainTheNullableConnectionName(): v
$queryConnection->logQuery('select 1', [], 0.0);
$transactionConnection = new PdoConnection(new PDO('sqlite::memory:'));
- $transactionConnection->setEventDispatcher($transactionEvents = Double::for(Dispatcher::class));
+ $transactionConnection->setEventDispatcher($transactionEvents = Double::for(Dispatcher::class)->strict());
$transactionEvents->expects('hasListeners')->with(TransactionBeginning::class)->returns(true);
$transactionEvents->expects('dispatch')->with(Argument::satisfies(
static fn (object $event): bool => $event instanceof TransactionBeginning
@@ -687,7 +687,7 @@ public function testBeganTransactionSkipsDispatchWhenNoListenersAreRegistered():
{
$pdo = $this->createStub(PDOStub::class);
$connection = $this->getMockConnection([], $pdo);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$connection->setEventDispatcher($events);
$events->expects('hasListeners')->with(TransactionBeginning::class)->returns(false);
$events->expects('dispatch')->never();
@@ -843,7 +843,7 @@ public function testRunMethodPreservesQueryCancellationWithoutRetryOrLogging(Thr
$pdo = $this->createStub(PDOStub::class);
$connection = $this->getMockConnection(['tryAgainIfCausedByLostConnection'], $pdo);
$connection->expects($this->never())->method('tryAgainIfCausedByLostConnection');
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$events->expects('hasListeners')->never()->with(QueryFailed::class);
$events->expects('dispatch')->never()->with(Argument::type(QueryFailed::class));
@@ -879,16 +879,10 @@ public function testRunDispatchesQueryFailedWithTheFinalLogicalFailure(): void
Connection::READ_WRITE_TYPE_CONFIG_KEY => 'read',
],
);
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$event = null;
$events->expects('hasListeners')->with(QueryFailed::class)->returns(true);
- $events->expects('dispatch')->with(Argument::satisfies(
- static function (QueryFailed $dispatched) use (&$event): bool {
- $event = $dispatched;
-
- return true;
- },
- ));
+ $events->expects('dispatch')->with(Argument::capture($event));
$exception = null;
try {
@@ -920,16 +914,10 @@ public function testRunDispatchesTheReconnectorThrowableAsTheFinalFailure(): voi
$connection->setReconnector(static function (Connection $connection) use ($reconnectorException): never {
throw $reconnectorException;
});
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$event = null;
$events->expects('hasListeners')->with(QueryFailed::class)->returns(true);
- $events->expects('dispatch')->with(Argument::satisfies(
- static function (QueryFailed $dispatched) use (&$event): bool {
- $event = $dispatched;
-
- return true;
- },
- ));
+ $events->expects('dispatch')->with(Argument::capture($event));
$exception = null;
try {
@@ -951,16 +939,10 @@ public function testRunDispatchesLostConnectionExceptionWhenNoReconnectorExists(
{
$method = (new ReflectionClass(Connection::class))->getMethod('run');
$connection = $this->getMockConnection();
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$event = null;
$events->expects('hasListeners')->with(QueryFailed::class)->returns(true);
- $events->expects('dispatch')->with(Argument::satisfies(
- static function (QueryFailed $dispatched) use (&$event): bool {
- $event = $dispatched;
-
- return true;
- },
- ));
+ $events->expects('dispatch')->with(Argument::capture($event));
$exception = null;
try {
@@ -987,16 +969,10 @@ public function testRunReportsAMissingConnectionDriverFailureAsTheQueryFailure()
$connection->setReconnector(static function () use ($driverFailure): never {
throw $driverFailure;
});
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$event = null;
$events->expects('hasListeners')->with(QueryFailed::class)->returns(true);
- $events->expects('dispatch')->with(Argument::satisfies(
- static function (QueryFailed $dispatched) use (&$event): bool {
- $event = $dispatched;
-
- return true;
- },
- ));
+ $events->expects('dispatch')->with(Argument::capture($event));
$exception = null;
try {
@@ -1026,16 +1002,10 @@ public function testRunReportsAFailedLostConnectionReconnectAsTheQueryFailure():
$connection->setReconnector(static function () use ($driverFailure): never {
throw $driverFailure;
});
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$event = null;
$events->expects('hasListeners')->with(QueryFailed::class)->returns(true);
- $events->expects('dispatch')->with(Argument::satisfies(
- static function (QueryFailed $dispatched) use (&$event): bool {
- $event = $dispatched;
-
- return true;
- },
- ));
+ $events->expects('dispatch')->with(Argument::capture($event));
$exception = null;
try {
@@ -1089,7 +1059,7 @@ public function testRunPreservesCancellationDuringAQueryReconnect(Throwable $can
$connection->setReconnector(static function () use ($cancellation): never {
throw $cancellation;
});
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$events->expects('hasListeners')->never()->with(QueryFailed::class);
$events->expects('dispatch')->never()->with(Argument::type(QueryFailed::class));
@@ -1145,7 +1115,7 @@ public function testRunEmitsOnlyQueryExecutedWhenLostConnectionRetrySucceeds():
$connection = $this->getMockConnection();
$connection->setReconnector(static function (Connection $connection): void {
});
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$events->expects('hasListeners')->with(QueryExecuted::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(QueryExecuted::class));
$events->expects('dispatch')->never()->with(Argument::type(QueryFailed::class));
@@ -1171,7 +1141,7 @@ public function testRunSkipsQueryFailedDispatchWhenNoListenersAreRegistered(): v
{
$method = (new ReflectionClass(Connection::class))->getMethod('run');
$connection = $this->getMockConnection();
- $connection->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $connection->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$events->expects('hasListeners')->with(QueryFailed::class)->returns(false);
$events->expects('dispatch')->never();
@@ -1194,7 +1164,7 @@ public function testStreamingRunsLazilyAndLogsOnlyAfterExhaustion(): void
$query = 'select ? as modified';
$bindings = [2];
});
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(QueryExecuted::class)->returns(true);
$events->expects('dispatch')->resolves(
static function (QueryExecuted $dispatched) use (&$event): void {
@@ -1279,7 +1249,7 @@ public function testStreamingReportsAMissingConnectionDriverFailureAsTheQueryFai
throw $driverFailure;
});
$event = null;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(QueryFailed::class)->returns(true);
$events->expects('dispatch')->resolves(
static function (QueryFailed $dispatched) use (&$event): void {
@@ -1336,7 +1306,7 @@ public function testStreamingRetriesALostConnectionBeforeTheFirstValue(): void
$connection->setReconnector(static function () use (&$reconnects): void {
++$reconnects;
});
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(QueryExecuted::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(QueryExecuted::class));
$connection->setEventDispatcher($events);
@@ -1369,7 +1339,7 @@ public function testStreamingReportsOneFinalFailureWhenTheRetryAlsoFails(): void
++$reconnects;
});
$event = null;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(QueryFailed::class)->returns(true);
$events->expects('dispatch')->resolves(
static function (QueryFailed $dispatched) use (&$event): void {
@@ -1406,7 +1376,7 @@ public function testStreamingLateFailureRetainsItsRoleAndNeverRetries(): void
$connection->setReconnector(static fn (): never => throw new LogicException('Unexpected retry.'));
$failure = new RuntimeException('server has gone away');
$event = null;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(QueryFailed::class)->returns(true);
$events->expects('dispatch')->resolves(
static function (QueryFailed $dispatched) use (&$event): void {
@@ -1448,7 +1418,7 @@ public function testAbandonedStreamingCleansUpWithoutSuccess(): void
{
$connection = new NeutralConnectionForTest;
$connection->enableQueryLog();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never();
$events->expects('dispatch')->never();
$connection->setEventDispatcher($events);
@@ -1476,7 +1446,7 @@ public function testStreamingConsumerExceptionsCleanUpWithoutQueryEvents(): void
{
$connection = new NeutralConnectionForTest;
$connection->enableQueryLog();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never();
$events->expects('dispatch')->never();
$connection->setEventDispatcher($events);
@@ -1509,7 +1479,7 @@ public function testStreamingCancellationCleansUpWithoutWrappingOrEvents(Throwab
{
$connection = new NeutralConnectionForTest;
$connection->enableQueryLog();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never();
$events->expects('dispatch')->never();
$connection->setEventDispatcher($events);
@@ -1542,7 +1512,7 @@ public function testClosedStreamingCleansUpWithoutWrappingOrEvents(bool $yieldFi
$connection = new NeutralConnectionForTest;
$connection->enableQueryLog();
$connection->setReconnector(static fn (): never => throw new LogicException('Unexpected retry.'));
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never();
$events->expects('dispatch')->never();
$connection->setEventDispatcher($events);
@@ -1713,7 +1683,7 @@ protected function newQueryException(string $query, array $bindings, Exception $
};
$connection->enableQueryLog();
$failure = new InvalidArgumentException('Invalid query parameters.');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->times(2)->with(QueryFailed::class)->returns(true);
$events->expects('dispatch')->times(2)->with(Argument::satisfies(
static fn (QueryFailed $event): bool => $event->exception === $failure,
@@ -1780,8 +1750,8 @@ public function testRunMethodNeverRetriesIfWithinTransaction(): void
public function testTableNormalizesIntegerBackedEnumName(): void
{
$connection = $this->getMockConnection();
- $connection->setQueryGrammar(Double::for(Grammar::class));
- $connection->setPostProcessor(Double::for(Processor::class));
+ $connection->setQueryGrammar(Double::for(Grammar::class)->strict());
+ $connection->setPostProcessor(Double::for(Processor::class)->strict());
$builder = $connection->table(DatabaseTableName::Zero);
@@ -1790,11 +1760,11 @@ public function testTableNormalizesIntegerBackedEnumName(): void
public function testPrepareBindings(): void
{
- $date = Double::for(DateTime::class);
+ $date = Double::for(DateTime::class)->strict();
$date->expects('format')->with('foo')->returns('bar');
$bindings = ['test' => $date];
$conn = $this->getMockConnection();
- $grammar = Double::for(Grammar::class);
+ $grammar = Double::for(Grammar::class)->strict();
$grammar->expects('getDateFormat')->returns('foo');
$conn->setQueryGrammar($grammar);
$result = $conn->prepareBindings($bindings);
@@ -1814,7 +1784,7 @@ public function testLogQueryFiresEventsIfSet(): void
public function testLogQuerySkipsDispatchWhenNoListenersAreRegistered(): void
{
$connection = $this->getMockConnection();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$connection->setEventDispatcher($events);
$events->expects('hasListeners')->with(QueryExecuted::class)->returns(false);
$events->expects('dispatch')->never();
@@ -1848,7 +1818,7 @@ public function testBeginPublicationFailureRollsBackAndPreservesTheOriginalFailu
$connection = $this->getSqliteTransactionConnection();
$publicationFailure = new RuntimeException('manager begin failure');
$cleanupFailure = new RuntimeException('manager rollback failure');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1)->throws($publicationFailure);
$manager->expects('rollback')->with('default', 0)->throws($cleanupFailure);
$connection->setTransactionManager($manager);
@@ -1869,7 +1839,7 @@ public function testBeginPublicationCleanupPreservesCancellation(Throwable $canc
{
$connection = $this->getSqliteTransactionConnection();
$publicationFailure = new RuntimeException('manager begin failure');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1)->throws($publicationFailure);
$manager->expects('rollback')->with('default', 0)->throws($cancellation);
$connection->setTransactionManager($manager);
@@ -1890,7 +1860,7 @@ public function testBeginPublicationCancellationRemainsPrimaryOverCleanupCancell
{
$connection = $this->getSqliteTransactionConnection();
$cleanupCancellation = new CanceledException('manager rollback canceled');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1)->throws($cancellation);
$manager->expects('rollback')->with('default', 0)->throws($cleanupCancellation);
$connection->setTransactionManager($manager);
@@ -1912,7 +1882,7 @@ public function testBeganEventFailureRollsBackPublishedTransactionState(): void
$manager = new DatabaseTransactionsManager;
$connection->setTransactionManager($manager);
$failure = new RuntimeException('began listener failure');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionBeginning::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(TransactionBeginning::class))->throws($failure);
$events->expects('hasListeners')->with(TransactionRolledBack::class)->returns(false);
@@ -1936,7 +1906,7 @@ public function testCommittingEventFailureRollsBackManagedTransaction(): void
$manager = new DatabaseTransactionsManager;
$connection->setTransactionManager($manager);
$failure = new RuntimeException('committing listener failure');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionBeginning::class)->returns(false);
$events->expects('hasListeners')->with(TransactionCommitting::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(TransactionCommitting::class))->throws($failure);
@@ -2035,7 +2005,7 @@ public function testManagedTransactionRollbackCleanupPreservesCancellation(Throw
{
$connection = $this->getSqliteTransactionConnection();
$failure = new RuntimeException('transaction callback failure');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('rollback')->with('default', 0)->throws($cancellation);
$connection->setTransactionManager($manager);
@@ -2056,7 +2026,7 @@ public function testManagedTransactionCancellationRemainsPrimaryOverRollbackCanc
{
$connection = $this->getSqliteTransactionConnection();
$cleanupCancellation = new CanceledException('rollback cleanup canceled');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('rollback')->with('default', 0)->throws($cleanupCancellation);
$connection->setTransactionManager($manager);
@@ -2152,7 +2122,7 @@ public function testNestedDeadlockRollbackCleanupPreservesCancellation(Throwable
'',
['name' => 'analytics', 'driver' => 'http']
);
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->times(2);
$manager->expects('rollback')->with('analytics', 1)->throws($cancellation);
$connection->setTransactionManager($manager);
@@ -2183,7 +2153,7 @@ public function testExplicitCommittingEventFailureLeavesTheTransactionCallerOwne
$connection = $this->getSqliteTransactionConnection();
$connection->beginTransaction();
$failure = new RuntimeException('committing listener failure');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionCommitting::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(TransactionCommitting::class))->throws($failure);
$connection->setEventDispatcher($events);
@@ -2206,14 +2176,14 @@ public function testManagerCommitFailureStillDispatchesCommittedEventAfterPhysic
{
$connection = $this->getSqliteTransactionConnection();
$failure = new RuntimeException('after commit callback failure');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('commit')->with('default', 1, 0)->throws($failure);
$connection->setTransactionManager($manager);
$connection->beginTransaction();
$eventDispatched = false;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionCommitting::class)->returns(false);
$events->expects('hasListeners')->with(TransactionCommitted::class)->returns(true);
$events->expects('dispatch')
@@ -2239,11 +2209,11 @@ public function testManagerCommitFailureStillDispatchesCommittedEventAfterPhysic
public function testManagedTransactionManagerCancellationSkipsCommittedEvent(Throwable $cancellation): void
{
$connection = $this->getSqliteTransactionConnection();
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('commit')->with('default', 1, 0)->throws($cancellation);
$connection->setTransactionManager($manager);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionBeginning::class)->returns(false);
$events->expects('hasListeners')->with(TransactionCommitting::class)->returns(false);
$events->expects('hasListeners')->never()->with(TransactionCommitted::class);
@@ -2265,11 +2235,11 @@ public function testManagedTransactionEventCancellationSupersedesManagerFailure(
{
$connection = $this->getSqliteTransactionConnection();
$managerFailure = new RuntimeException('manager commit failure');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('commit')->with('default', 1, 0)->throws($managerFailure);
$connection->setTransactionManager($manager);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionBeginning::class)->returns(false);
$events->expects('hasListeners')->with(TransactionCommitting::class)->returns(false);
$events->expects('hasListeners')->with(TransactionCommitted::class)->returns(true);
@@ -2291,12 +2261,12 @@ public function testManagedTransactionEventCancellationSupersedesManagerFailure(
public function testExplicitCommitManagerCancellationSkipsCommittedEvent(Throwable $cancellation): void
{
$connection = $this->getSqliteTransactionConnection();
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('commit')->with('default', 1, 0)->throws($cancellation);
$connection->setTransactionManager($manager);
$connection->beginTransaction();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionCommitting::class)->returns(false);
$events->expects('hasListeners')->never()->with(TransactionCommitted::class);
$connection->setEventDispatcher($events);
@@ -2317,12 +2287,12 @@ public function testExplicitCommitEventCancellationSupersedesManagerFailure(Thro
{
$connection = $this->getSqliteTransactionConnection();
$managerFailure = new RuntimeException('manager commit failure');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('commit')->with('default', 1, 0)->throws($managerFailure);
$connection->setTransactionManager($manager);
$connection->beginTransaction();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionCommitting::class)->returns(false);
$events->expects('hasListeners')->with(TransactionCommitted::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(TransactionCommitted::class))->throws($cancellation);
@@ -2386,7 +2356,7 @@ public function testLostConnectionCommitCleanupPreservesCancellation(Throwable $
new PDOException('server has gone away')
);
$connection = $this->getMockConnection([], $pdo);
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('test', 1);
$manager->expects('rollback')->with('test', 0)->throws($cancellation);
$connection->setTransactionManager($manager);
@@ -2415,7 +2385,7 @@ public function testCommitRollbackCleanupPreservesCancellationWithoutRetry(Throw
$pdo->expects($this->once())->method('inTransaction')->willReturn(true);
$pdo->expects($this->once())->method('rollBack');
$connection = $this->getMockConnection([], $pdo);
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('test', 1);
$manager->expects('rollback')->with('test', 0)->throws($cancellation);
$connection->setTransactionManager($manager);
@@ -2446,7 +2416,7 @@ public function testCommitCancellationRemainsPrimaryOverRollbackCancellation():
$pdo->expects($this->once())->method('inTransaction')->willReturn(true);
$pdo->expects($this->once())->method('rollBack');
$connection = $this->getMockConnection([], $pdo);
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('test', 1);
$manager->expects('rollback')->with('test', 0)->throws($cleanupCancellation);
$connection->setTransactionManager($manager);
@@ -2465,14 +2435,14 @@ public function testManagerRollbackFailureStillDispatchesRolledBackEvent(): void
{
$connection = $this->getSqliteTransactionConnection();
$failure = new RuntimeException('manager rollback failure');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('rollback')->with('default', 0)->throws($failure);
$connection->setTransactionManager($manager);
$connection->beginTransaction();
$eventDispatched = false;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionRolledBack::class)->returns(true);
$events->expects('dispatch')
->with(Argument::type(TransactionRolledBack::class))
@@ -2497,12 +2467,12 @@ public function testManagerRollbackFailureStillDispatchesRolledBackEvent(): void
public function testExplicitRollbackManagerCancellationSkipsRolledBackEvent(Throwable $cancellation): void
{
$connection = $this->getSqliteTransactionConnection();
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('rollback')->with('default', 0)->throws($cancellation);
$connection->setTransactionManager($manager);
$connection->beginTransaction();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->never()->with(TransactionRolledBack::class);
$connection->setEventDispatcher($events);
@@ -2522,12 +2492,12 @@ public function testExplicitRollbackEventCancellationSupersedesManagerFailure(Th
{
$connection = $this->getSqliteTransactionConnection();
$managerFailure = new RuntimeException('manager rollback failure');
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('default', 1);
$manager->expects('rollback')->with('default', 0)->throws($managerFailure);
$connection->setTransactionManager($manager);
$connection->beginTransaction();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionRolledBack::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(TransactionRolledBack::class))->throws($cancellation);
$connection->setEventDispatcher($events);
@@ -2550,7 +2520,7 @@ public function testRolledBackEventFailureOccursAfterManagerCleanup(): void
$connection->setTransactionManager($manager);
$connection->beginTransaction();
$failure = new RuntimeException('rolled back listener failure');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(TransactionRolledBack::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(TransactionRolledBack::class))->throws($failure);
$connection->setEventDispatcher($events);
@@ -2579,7 +2549,7 @@ public function testLostConnectionRollbackCleanupPreservesCancellation(Throwable
new PDOException('server has gone away')
);
$connection = $this->getMockConnection([], $pdo);
- $manager = Double::for(DatabaseTransactionsManager::class);
+ $manager = Double::for(DatabaseTransactionsManager::class)->strict();
$manager->expects('begin')->with('test', 1);
$manager->expects('rollback')->with('test', 0)->throws($cancellation);
$connection->setTransactionManager($manager);
@@ -2599,7 +2569,7 @@ public function testLostConnectionRollbackCleanupPreservesCancellation(Throwable
public function testPretendOnlyLogsQueries(): void
{
$connection = $this->getMockConnection();
- $grammar = Double::for(Grammar::class);
+ $grammar = Double::for(Grammar::class)->strict();
$grammar->allows('substituteBindingsIntoRawSql')->resolves(fn ($query) => $query);
$connection->setQueryGrammar($grammar);
$queries = $connection->pretend(function ($connection) {
@@ -2696,7 +2666,7 @@ public function testOlapSetsWorkloadOnReadAndWriteConnections(): void
public function testOlapLeavesOtherMySqlServersUnchanged(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.34');
$pdo->expects('exec')->never();
$connection = new MySqlConnection($pdo);
@@ -2706,7 +2676,7 @@ public function testOlapLeavesOtherMySqlServersUnchanged(): void
public function testNestedOlapScopesRestoreTheWorkloadOnlyAfterTheOuterCallback(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.34-vitess');
$connection = new MySqlConnection($pdo);
@@ -2727,13 +2697,13 @@ public function testNestedOlapScopesRestoreTheWorkloadOnlyAfterTheOuterCallback(
public function testOlapReappliesTheWorkloadBeforeRetryingALostConnection(): void
{
- $original = Double::for(PDO::class);
+ $original = Double::for(PDO::class)->strict();
$original->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.34-vitess');
$original->expects('exec')->with("set workload = 'olap'")->returns(0);
$original->expects('prepare')->with('select total')->throws(new PDOException('server has gone away'));
- $replacement = Double::for(PDO::class);
+ $replacement = Double::for(PDO::class)->strict();
$replacement->expects('exec')->with("set workload = 'olap'")->returns(0)->ordered();
- $statement = Double::for(PDOStatement::class);
+ $statement = Double::for(PDOStatement::class)->strict();
$statement->expects('setFetchMode')->with(PDO::FETCH_OBJ)->returns(true);
$statement->expects('execute')->returns(true);
$statement->expects('fetchAll')->returns([42]);
@@ -2755,18 +2725,18 @@ public function testOlapReappliesTheWorkloadBeforeRetryingALostConnection(): voi
public function testOlapRecoversItsWorkloadAndEndpointAfterAFailedReconnect(bool $read): void
{
$calls = [];
- $original = Double::for(PDO::class);
+ $original = Double::for(PDO::class)->strict();
$original->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.34-vitess');
$original->expects('exec')->with("set workload = 'olap'")->returns(0);
- $originalRead = Double::for(PDO::class);
+ $originalRead = Double::for(PDO::class)->strict();
$originalRead->expects('exec')->with("set workload = 'olap'")->returns(0);
- $replacement = Double::for(PDO::class);
+ $replacement = Double::for(PDO::class)->strict();
$replacement->expects('exec')->with("set workload = 'olap'")->resolves(function () use (&$calls): int {
$calls[] = 'write:olap';
return 0;
});
- $replacementRead = Double::for(PDO::class);
+ $replacementRead = Double::for(PDO::class)->strict();
$replacementRead->expects('exec')->with("set workload = 'olap'")->resolves(function () use (&$calls): int {
$calls[] = 'read:olap';
@@ -2774,7 +2744,7 @@ public function testOlapRecoversItsWorkloadAndEndpointAfterAFailedReconnect(bool
});
if ($read) {
- $statement = Double::for(PDOStatement::class);
+ $statement = Double::for(PDOStatement::class)->strict();
$statement->expects('setFetchMode')->with(PDO::FETCH_OBJ)->returns(true);
$statement->expects('execute')->returns(true);
$statement->expects('fetchAll')->returns([42]);
@@ -2836,10 +2806,10 @@ public function testOlapRecoversItsWorkloadAndEndpointAfterAFailedReconnect(bool
public function testPartialOlapSetupPreventsReusingEitherSession(): void
{
- $writePdo = Double::for(PDO::class);
+ $writePdo = Double::for(PDO::class)->strict();
$writePdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.34-vitess');
$writePdo->expects('exec')->with("set workload = 'olap'")->returns(0);
- $readPdo = Double::for(PDO::class);
+ $readPdo = Double::for(PDO::class)->strict();
$failure = new PDOException('Workload change refused.');
$readPdo->expects('exec')->with("set workload = 'olap'")->throws($failure);
$connection = (new MySqlConnection($writePdo))->setReadPdo($readPdo);
@@ -2857,7 +2827,7 @@ public function testPartialOlapSetupPreventsReusingEitherSession(): void
public function testOlapRestorationFailurePreservesCancellationAndDiscardsTheSession(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->expects('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.34-vitess');
$pdo->expects('exec')->with("set workload = 'olap'")->returns(0);
$connection = new MySqlConnection($pdo);
@@ -3397,7 +3367,7 @@ protected function getMockConnection($methods = [], $pdo = null)
if ($methods === []) {
$connection = new PdoConnection($pdo, 'test_db', '', ['name' => 'test', 'driver' => 'mysql']);
- $connection->setSchemaGrammar(Double::for(SchemaGrammar::class));
+ $connection->setSchemaGrammar(Double::for(SchemaGrammar::class)->strict());
$connection->enableQueryLog();
return $connection;
@@ -3405,7 +3375,7 @@ protected function getMockConnection($methods = [], $pdo = null)
$defaults = ['getDefaultQueryGrammar', 'getDefaultPostProcessor', 'getDefaultSchemaGrammar'];
$connection = $this->getMockBuilder(PdoConnection::class)->onlyMethods(array_values(array_unique(array_merge($defaults, $methods))))->setConstructorArgs([$pdo, 'test_db', '', ['name' => 'test', 'driver' => 'mysql']])->getMock();
- $connection->method('getDefaultSchemaGrammar')->willReturn(Double::for(SchemaGrammar::class));
+ $connection->method('getDefaultSchemaGrammar')->willReturn(Double::for(SchemaGrammar::class)->strict());
$connection->enableQueryLog();
return $connection;
diff --git a/tests/Database/DatabaseConnectorTest.php b/tests/Database/DatabaseConnectorTest.php
index 041c1d8a58..defcbf33a6 100755
--- a/tests/Database/DatabaseConnectorTest.php
+++ b/tests/Database/DatabaseConnectorTest.php
@@ -52,7 +52,7 @@ public function testConnectionsRejectNonExceptionErrorModes(int $mode): void
public function testMySqlConnectCallsCreateConnectionWithProperArguments(string $dsn, array $config): void
{
$connector = $this->getMockBuilder(MySqlConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$connection->expects('exec')->with('use `bar`;')->returns(0);
@@ -139,7 +139,7 @@ public function testMySqlEscapesBackticksInTheSelectedDatabaseName(): void
{
$config = ['host' => 'foo', 'database' => 'app`tenant', 'modes' => []];
$connector = $this->getMockBuilder(MySqlConnector::class)->onlyMethods(['createConnection'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('createConnection')->willReturn($connection);
$connection->expects('exec')->with('use `app``tenant`;')->returns(0);
$connection->expects('exec')->with("SET SESSION sql_mode='';")->returns(0);
@@ -153,7 +153,7 @@ public function testMySqlConnectCallsCreateConnectionWithIsolationLevel(): void
$config = ['host' => 'foo', 'database' => 'bar', 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8', 'isolation_level' => 'REPEATABLE READ', 'modes' => []];
$connector = $this->getMockBuilder(MySqlConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$connection->expects('exec')->with('use `bar`;')->returns(0);
@@ -175,7 +175,7 @@ public function testMySqlLockTimeoutIsCombinedWithConnectionSettings(): void
];
$connector = $this->getMockBuilder(MySqlConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->willReturn($connection);
$connection->expects('exec')->with('use `bar`;')->returns(0);
@@ -200,7 +200,7 @@ public function testMySqlAndMariaDbRequireAnExplicitSqlModeConfiguration(): void
{
foreach ([MySqlConnector::class => 'MySQL', MariaDbConnector::class => 'MariaDB'] as $connectorClass => $driver) {
$connector = $this->getMockBuilder($connectorClass)->onlyMethods(['createConnection'])->getMock();
- $connector->expects($this->once())->method('createConnection')->willReturn(Double::for(PDO::class));
+ $connector->expects($this->once())->method('createConnection')->willReturn(Double::for(PDO::class)->strict());
try {
$connector->connect(['host' => 'localhost', 'database' => '']);
@@ -216,7 +216,7 @@ public function testPostgresConnectCallsCreateConnectionWithProperArguments(): v
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111;client_encoding=\'utf8\'';
$config = ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'charset' => 'utf8'];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -229,7 +229,7 @@ public function testPostgresLockTimeoutIsBakedIntoDsn(): void
$dsn = "pgsql:host=foo;dbname='bar';options='-c lock_timeout=2s'";
$config = ['host' => 'foo', 'database' => 'bar', 'lock_timeout' => 2];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
@@ -261,7 +261,7 @@ public function testPostgresSearchPathIsSet(array|string $searchPath, string $ex
$dsn = "pgsql:host=foo;dbname='bar';client_encoding='utf8';options='-c search_path={$escaped}'";
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -352,7 +352,7 @@ public function testPostgresSearchPathFallbackToConfigKeySchema(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';client_encoding=\'utf8\';options=\'-c search_path="public",\\\ "user"\'';
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -365,7 +365,7 @@ public function testPostgresApplicationNameIsSet(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';client_encoding=\'utf8\';application_name=\'Hypervel App\'';
$config = ['host' => 'foo', 'database' => 'bar', 'charset' => 'utf8', 'application_name' => 'Hypervel App'];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -378,7 +378,7 @@ public function testPostgresKeepaliveOptionsAreSet(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111;keepalives=1;keepalives_idle=600;keepalives_interval=30;keepalives_count=5';
$config = ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'keepalives' => 1, 'keepalives_idle' => 600, 'keepalives_interval' => 30, 'keepalives_count' => 5];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -391,7 +391,7 @@ public function testPostgresKeepaliveOptionsAreOmittedWhenNotConfigured(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111;keepalives_idle=600';
$config = ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'keepalives_idle' => 600];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -404,7 +404,7 @@ public function testPostgresServerOptionsAreSet(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111;options=\'-c statement_timeout=5s -c search_path=public\'';
$config = ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'server_options' => ['statement_timeout' => '5s', 'search_path' => 'public']];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -417,7 +417,7 @@ public function testPostgresServerOptionsAreOmittedWhenNotConfigured(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111';
$config = ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'server_options' => []];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -430,7 +430,7 @@ public function testPostgresServerOptionValuesAreEscaped(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111;options=\'-c application_name=my\\\ app -c custom.tag=o\\\'clock\'';
$config = ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'server_options' => ['application_name' => 'my app', 'custom.tag' => "o'clock"]];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -451,7 +451,7 @@ public function testPostgresConnectionValuesAreQuoted(): void
$dsn = <<<'DSN'
pgsql:dbname='team\'s\\database';client_encoding='utf8';application_name='team\'s\\app';sslcert='/tmp/client cert.pem';sslkey='/tmp/client key.pem';sslrootcert='/tmp/root ca.pem'
DSN;
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection'])->getMock();
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, $connector->getOptions($config))->willReturn($connection);
@@ -463,7 +463,7 @@ public function testPostgresApplicationUseAlternativeDatabaseName(): void
$dsn = 'pgsql:dbname=\'baz\'';
$config = ['database' => 'bar', 'connect_via_database' => 'baz'];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -476,7 +476,7 @@ public function testPostgresApplicationUseAlternativeDatabaseNameAndPort(): void
$dsn = 'pgsql:dbname=\'baz\';port=2345';
$config = ['database' => 'bar', 'connect_via_database' => 'baz', 'port' => 5432, 'connect_via_port' => 2345];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -489,7 +489,7 @@ public function testPostgresConnectorReadsIsolationLevelFromConfig(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';port=111;options=\'-c default_transaction_isolation=SERIALIZABLE\'';
$config = ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'isolation_level' => 'SERIALIZABLE'];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -502,7 +502,7 @@ public function testPostgresIsolationLevelWithSpaceIsBackslashEscaped(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';options=\'-c default_transaction_isolation=read\\\ committed\'';
$config = ['host' => 'foo', 'database' => 'bar', 'isolation_level' => 'read committed'];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
$result = $connector->connect($config);
@@ -515,7 +515,7 @@ public function testPostgresTimezoneIsBakedIntoDsn(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';options=\'-c TimeZone=UTC\'';
$config = ['host' => 'foo', 'database' => 'bar', 'timezone' => 'UTC'];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
$result = $connector->connect($config);
@@ -528,7 +528,7 @@ public function testPostgresSynchronousCommitIsBakedIntoDsn(): void
$dsn = 'pgsql:host=foo;dbname=\'bar\';options=\'-c synchronous_commit=off\'';
$config = ['host' => 'foo', 'database' => 'bar', 'synchronous_commit' => 'off'];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
$result = $connector->connect($config);
@@ -550,7 +550,7 @@ public function testPostgresCombinesMultipleStartupParamsInDsn(): void
'synchronous_commit' => 'on',
];
$connector = $this->getMockBuilder(PostgresConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
$result = $connector->connect($config);
@@ -563,7 +563,7 @@ public function testSQLiteMemoryDatabasesMayBeConnectedTo(): void
$dsn = 'sqlite::memory:';
$config = ['database' => ':memory:'];
$connector = $this->getMockBuilder(SQLiteConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -661,7 +661,7 @@ public function testSQLiteRelativePathResolvesAgainstApplicationRoot(): void
$config = ['database' => basename(__FILE__)];
$dsn = 'sqlite:' . __FILE__;
$connector = $this->getMockBuilder(SQLiteConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
@@ -674,7 +674,7 @@ public function testSQLiteNamedMemoryDatabasesMayBeConnectedTo(): void
$dsn = 'sqlite:file:mydb?mode=memory&cache=shared';
$config = ['database' => 'file:mydb?mode=memory&cache=shared'];
$connector = $this->getMockBuilder(SQLiteConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
@@ -687,7 +687,7 @@ public function testSQLiteFileUriDatabasesMayBeConnectedTo(): void
$dsn = 'sqlite:file:/tmp/database.sqlite?mode=rw';
$config = ['database' => 'file:/tmp/database.sqlite?mode=rw'];
$connector = $this->getMockBuilder(SQLiteConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(['options']))->willReturn($connection);
@@ -701,7 +701,7 @@ public function testSQLiteFileDatabasesMayBeConnectedTo(): void
$dsn = 'sqlite:' . __DIR__;
$config = ['database' => __DIR__];
$connector = $this->getMockBuilder(SQLiteConnector::class)->onlyMethods(['createConnection', 'getOptions'])->getMock();
- $connection = Double::for(PDO::class);
+ $connection = Double::for(PDO::class)->strict();
$connector->expects($this->once())->method('getOptions')->with($config)->willReturn(['options']);
$connector->expects($this->once())->method('createConnection')->with($dsn, $config, ['options'])->willReturn($connection);
$result = $connector->connect($config);
diff --git a/tests/Database/DatabaseDbCommandLaunchTest.php b/tests/Database/DatabaseDbCommandLaunchTest.php
index c7e38a7d49..74f108705e 100644
--- a/tests/Database/DatabaseDbCommandLaunchTest.php
+++ b/tests/Database/DatabaseDbCommandLaunchTest.php
@@ -110,7 +110,7 @@ public function testHostlessExtensionResolvesOnceForTheLaunch(): void
*/
private function prepareCommand(DbCommand $command, DatabaseCliManager $manager, array $connection): BufferedOutput
{
- $this->application = Double::for(Application::class, override: true);
+ $this->application = Double::for(Application::class, override: true)->strict();
$this->application->expects('make')->with(DatabaseCliManager::class)->returns($manager);
$this->application->expects('make')->with('config')->returns(new Repository([
'database' => ['default' => 'testing', 'connections' => ['testing' => $connection]],
@@ -131,7 +131,8 @@ private function prepareCommand(DbCommand $command, DatabaseCliManager $manager,
*/
private function expectProcess(array $arguments, array $environment): void
{
- $process = Double::for(Process::class);
+ $process = Double::for(Process::class)->strict();
+ $process->allows('stop')->with(0.0)->returns(0); // Symfony stops the process in its destructor.
$process->expects('setTimeout')->with(null);
$process->expects('setTty')->with(true);
$process->expects('mustRun')->with(Argument::type(Closure::class))
diff --git a/tests/Database/DatabaseDbCommandTest.php b/tests/Database/DatabaseDbCommandTest.php
index 063b087143..e51eb0caed 100644
--- a/tests/Database/DatabaseDbCommandTest.php
+++ b/tests/Database/DatabaseDbCommandTest.php
@@ -435,7 +435,7 @@ private function getConnection(array $connections, array $input = []): array
*/
private function applicationWithConfig(array $connections): DoubleInterface
{
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$application->expects('make')
->with('config')
->returns(new Repository([
diff --git a/tests/Database/DatabaseDriverConnectionLeaseTest.php b/tests/Database/DatabaseDriverConnectionLeaseTest.php
index 3146845095..3c2ee93598 100644
--- a/tests/Database/DatabaseDriverConnectionLeaseTest.php
+++ b/tests/Database/DatabaseDriverConnectionLeaseTest.php
@@ -19,6 +19,7 @@
use Hypervel\Testbench\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use LogicException;
use PHPUnit\Framework\Attributes\TestWith;
use RuntimeException;
@@ -193,8 +194,8 @@ public function testDisconnectClosesOnlyAHeldPhysicalConnectionAndEachGeneration
public function testQueriesRunWhileReconnectingDoNotReconnectAgain(): void
{
$failure = new RuntimeException('The remote database connection was lost.');
- $detector = Double::for(LostConnectionDetector::class);
- $detector->allows('causedByLostConnection')->with($failure)->returns(true);
+ $detector = Double::for(LostConnectionDetector::class)->strict();
+ $detector->allows('causedByLostConnection')->with(Argument::same($failure))->returns(true);
$this->app->instance(LostConnectionDetector::class, $detector);
$connection = DB::connection('leased');
$reconnects = 0;
diff --git a/tests/Database/DatabaseEloquentAsVectorCastTest.php b/tests/Database/DatabaseEloquentAsVectorCastTest.php
index 084e5c1bac..771dcb1b9e 100644
--- a/tests/Database/DatabaseEloquentAsVectorCastTest.php
+++ b/tests/Database/DatabaseEloquentAsVectorCastTest.php
@@ -196,11 +196,11 @@ public static function storedVectorProvider(): array
*/
protected function useGrammar(string $grammar): Grammar
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new $grammar($connection);
$connection->allows('getQueryGrammar')->returns($grammar);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
Model::setConnectionResolver($resolver);
diff --git a/tests/Database/DatabaseEloquentBelongsToManyCreateOrFirstTest.php b/tests/Database/DatabaseEloquentBelongsToManyCreateOrFirstTest.php
index a8c6b187fa..af6129f385 100644
--- a/tests/Database/DatabaseEloquentBelongsToManyCreateOrFirstTest.php
+++ b/tests/Database/DatabaseEloquentBelongsToManyCreateOrFirstTest.php
@@ -582,7 +582,7 @@ protected function mockConnectionForModels(array $models, string $database): voi
$grammarClass = 'Hypervel\Database\Query\Grammars\\' . $database . 'Grammar';
$processorClass = 'Hypervel\Database\Query\Processors\\' . $database . 'Processor';
$processor = new $processorClass;
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getPostProcessor')->returns($processor);
$grammar = new $grammarClass($connection);
$connection->allows('getQueryGrammar')->returns($grammar);
@@ -594,7 +594,7 @@ protected function mockConnectionForModels(array $models, string $database): voi
fn ($table, $as = null) => $connection->query()->from($table, $as)
);
$connection->allows('getDatabaseName')->returns('database');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
foreach ($models as $model) {
diff --git a/tests/Database/DatabaseEloquentBelongsToTest.php b/tests/Database/DatabaseEloquentBelongsToTest.php
index e41dfc5d73..eece093df6 100755
--- a/tests/Database/DatabaseEloquentBelongsToTest.php
+++ b/tests/Database/DatabaseEloquentBelongsToTest.php
@@ -98,7 +98,7 @@ public function testIdsInEagerConstraintsCanBeBackedEnum(): void
public function testRelationIsProperlyInitialized(): void
{
$relation = $this->getRelation();
- $model = Double::for(Model::class);
+ $model = Double::for(Model::class)->strict();
$model->expects('setRelation')->with('foo', null);
$models = $relation->initRelation([$model], 'foo');
@@ -309,9 +309,9 @@ protected function getRelationWithRealQuery(string $keyType = 'int'): BelongsTo
*/
protected function getRelation(?Model $parent = null, string $keyType = 'int'): BelongsTo
{
- $this->builder = Double::for(Builder::class);
+ $this->builder = Double::for(Builder::class)->strict();
$this->builder->expects('where')->with('relation.id', '=', 'foreign.value');
- $this->related = Double::for(Model::class);
+ $this->related = Double::for(Model::class)->strict();
$this->related->allows('getKeyType')->returns($keyType);
$this->related->allows('getKeyName')->returns('id');
$this->related->allows('getTable')->returns('relation');
@@ -331,7 +331,7 @@ protected function getRelation(?Model $parent = null, string $keyType = 'int'):
*/
protected function getRelationWithPartialMock(?Model $parent = null): BelongsTo
{
- $this->builder = Double::for(Builder::class);
+ $this->builder = Double::for(Builder::class)->strict();
$this->builder->expects('where')->with('relation.id', '=', 'foreign.value');
$this->related = Double::for(new ModelStub)->passthru();
$this->related->allows('getKeyType')->returns('int');
diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php
index 67938a8b70..91e8c54e66 100755
--- a/tests/Database/DatabaseEloquentBuilderTest.php
+++ b/tests/Database/DatabaseEloquentBuilderTest.php
@@ -56,7 +56,7 @@ public function testFindMethod(): void
$builder->setModel($model);
$model->expects('getKeyType')->returns('int');
$builder->getQuery()->expects('where')->with('foo_table.foo', '=', 'bar', 'and');
- $expectedModel = Double::for(Model::class);
+ $expectedModel = Double::for(Model::class)->strict();
$builder->expects('first')->with(['column'])->returns($expectedModel);
$result = $builder->find('bar', ['column']);
@@ -102,7 +102,7 @@ public function testFindSoleMethod(): void
$builder->setModel($model);
$model->expects('getKeyType')->returns('int');
$builder->getQuery()->expects('where')->with('foo_table.foo', '=', 'bar', 'and');
- $expectedModel = Double::for(Model::class);
+ $expectedModel = Double::for(Model::class)->strict();
$builder->expects('sole')->with(['column'])->returns($expectedModel);
$result = $builder->findSole('bar', ['column']);
@@ -222,7 +222,7 @@ public function testFindOrFailWithEnumIds(BackedEnum $id, int|string $value, boo
$models = new Collection([$model]);
$ids = [$id, $id, $value];
$ids = $useCollection ? new BaseCollection($ids) : $ids;
- $builder->expects('find')->with($ids, ['column'])->returns($models);
+ $builder->expects('find')->with(Argument::same($ids), ['column'])->returns($models);
$this->assertSame($models, $builder->findOrFail($ids, ['column']));
}
@@ -239,7 +239,7 @@ public function testFindOrFailWithMissingEnumIds(BackedEnum $id, int|string $val
$builder->setModel($model);
$ids = ['existing', $id];
$ids = $useCollection ? new BaseCollection($ids) : $ids;
- $builder->expects('find')->with($ids, ['*'])->returns(new Collection([$model]));
+ $builder->expects('find')->with(Argument::same($ids), ['*'])->returns(new Collection([$model]));
try {
$builder->findOrFail($ids);
@@ -313,7 +313,7 @@ public function testFirstMethod(): void
public function testQualifyColumn(): void
{
- $builder = new Builder(Double::for(BaseBuilder::class));
+ $builder = new Builder(Double::for(BaseBuilder::class)->strict());
$builder->expects('from')->with('foo_table');
$builder->getQuery()->allows('getFromAlias')->returns(null);
@@ -324,7 +324,7 @@ public function testQualifyColumn(): void
public function testQualifyColumns(): void
{
- $builder = new Builder(Double::for(BaseBuilder::class));
+ $builder = new Builder(Double::for(BaseBuilder::class)->strict());
$builder->expects('from')->with('foo_table');
$builder->getQuery()->allows('getFromAlias')->returns(null);
@@ -335,7 +335,7 @@ public function testQualifyColumns(): void
public function testQualifyColumnWithTableAlias(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = new Builder($query);
@@ -869,7 +869,7 @@ public function testLocalMacrosAreCalledOnBuilder(): void
unset($_SERVER['__test.builder']);
$builder = new Builder(new BaseBuilder(
new PdoConnection(new PDO('sqlite::memory:')),
- Double::for(Grammar::class),
+ Double::for(Grammar::class)->strict(),
new Processor
));
$builder->macro('fooBar', function ($builder) {
@@ -942,12 +942,12 @@ public function testRelationshipEagerLoadProcess(): void
},
'orders.lines' => fn () => $this->fail('Nested relationships must load on their own query.'),
]);
- $relation = Double::for(Relation::class);
+ $relation = Double::for(Relation::class)->strict();
$relation->expects('addEagerConstraints')->with(['models']);
$relation->expects('initRelation')->with(['models'], 'orders')->returns(['models']);
$eagerResults = new Collection(['results']);
$relation->expects('getEager')->returns($eagerResults);
- $relation->expects('match')->with(['models'], $eagerResults, 'orders')->returns(['models.matched']);
+ $relation->expects('match')->with(['models'], Argument::same($eagerResults), 'orders')->returns(['models.matched']);
$builder->expects('getRelation')->with('orders')->returns($relation);
$results = $builder->eagerLoadRelations(['models']);
@@ -1107,10 +1107,16 @@ public function testEagerLoadParsingSetsProperRelationships(): void
public function testQueryPassThru(): void
{
- BaseBuilder::macro('foobar', fn () => 'foo');
- $builder = $this->getBuilder();
+ $called = false;
+ BaseBuilder::macro('foobar', function () use (&$called) {
+ $called = true;
+
+ return 'foo';
+ });
+ $builder = $this->newBuilder($this->useInMemoryConnection());
- $this->assertInstanceOf(Builder::class, $builder->foobar());
+ $this->assertSame($builder, $builder->foobar());
+ $this->assertTrue($called);
$builder = $this->getBuilder();
$builder->getQuery()->expects('insert')->with(['bar'])->returns(true);
@@ -2163,7 +2169,7 @@ public function testHasNestedWithMorphToAfterFirstRelation(): void
public function testHasWithCustomCountExpression(): void
{
- $count = Double::for(ExpressionContract::class);
+ $count = Double::for(ExpressionContract::class)->strict();
$count->allows('getValue')->returns('model_parent_stubs.required_count');
$query = (new ModelParentStub)->whereHas('foo', static function (Builder $query): void {
@@ -2862,7 +2868,7 @@ public function testWhereKeyMethodWithBinaryParameter(): void
$builder = $this->getBuilder()->setModel($model);
$binary = new BinaryParameter("\0binary-key");
- $builder->getQuery()->expects('where')->with($model->getQualifiedKeyName(), '=', $binary, 'and');
+ $builder->getQuery()->expects('where')->with($model->getQualifiedKeyName(), '=', Argument::same($binary), 'and');
$builder->whereKey($binary);
}
@@ -2965,7 +2971,7 @@ public function testWhereKeyNotMethodWithBinaryParameter(): void
$builder = $this->getBuilder()->setModel($model);
$binary = new BinaryParameter("\0binary-key");
- $builder->getQuery()->expects('where')->with($model->getQualifiedKeyName(), '!=', $binary, 'and');
+ $builder->getQuery()->expects('where')->with($model->getQualifiedKeyName(), '!=', Argument::same($binary), 'and');
$builder->whereKeyNot($binary);
}
@@ -3225,7 +3231,7 @@ public function testUpdate(): void
{
CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = new Builder($query);
@@ -3241,7 +3247,7 @@ public function testUpdate(): void
public function testUpdateWithTimestampValue(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getTablePrefix')->times(2)->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = new Builder($query);
@@ -3257,7 +3263,7 @@ public function testUpdateWithTimestampValue(): void
public function testUpdateWithQualifiedTimestampValue(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = new Builder($query);
@@ -3273,7 +3279,7 @@ public function testUpdateWithQualifiedTimestampValue(): void
public function testUpdateWithoutTimestamp(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getTablePrefix')->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = new Builder($query);
@@ -3291,7 +3297,7 @@ public function testUpdateWithAlias(): void
{
CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = new Builder($query);
@@ -3309,7 +3315,7 @@ public function testUpdateWithAliasWithQualifiedTimestampValue(): void
{
CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = new Builder($query);
@@ -3327,9 +3333,9 @@ public function testUpdateWithAnExplicitRawSourceAliasAndPrefix(): void
{
CarbonImmutable::setTestNow('2017-10-10 10:10:10');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('prefix_');
- $query = new BaseBuilder($connection, new MySqlGrammar($connection), Double::for(Processor::class));
+ $query = new BaseBuilder($connection, new MySqlGrammar($connection), Double::for(Processor::class)->strict());
$builder = (new Builder($query))->setModel((new Stub)->setDateFormat('Y-m-d H:i:s'));
$connection->expects('update')->with(
'update `prefix_table` as `prefix_target` inner join `prefix_profiles` on `prefix_profiles`.`user_id` = `prefix_target`.`id` set `prefix_target`.`name` = ?, `prefix_target`.`updated_at` = ?',
@@ -3455,7 +3461,7 @@ public function testUpsert(): void
{
CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10');
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('foo_table')->returns($query);
$query->from = 'foo_table';
@@ -3479,7 +3485,7 @@ public function testUpsertAddsUpdatedAtUnlessTheUpdateAlreadySetsIt(array $updat
{
CarbonImmutable::setTestNow($now = '2017-10-10 10:10:10');
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('foo_table')->returns($query);
$query->from = 'foo_table';
@@ -3510,7 +3516,7 @@ public function testTouch(): void
{
CarbonImmutable::setTestNow('2017-10-10 10:10:10');
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('foo_table')->returns($query);
$query->from = 'foo_table';
@@ -3529,7 +3535,7 @@ public function testTouchWithCustomColumn(): void
{
CarbonImmutable::setTestNow('2017-10-10 10:10:10');
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('foo_table')->returns($query);
$query->from = 'foo_table';
@@ -3548,7 +3554,7 @@ public function testTouchWithMultipleColumns(): void
{
CarbonImmutable::setTestNow('2017-10-10 10:10:10');
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('foo_table')->returns($query);
$query->from = 'foo_table';
@@ -3567,7 +3573,7 @@ public function testTouchWithMultipleColumns(): void
public function testTouchWithoutUpdatedAtColumn(): void
{
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('table')->returns($query);
$query->from = 'table';
@@ -3584,7 +3590,7 @@ public function testTouchWithoutUpdatedAtColumn(): void
public function testClone(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getTablePrefix')->times(2)->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = new Builder($query);
@@ -3655,7 +3661,7 @@ public function testNewQueryRestoresTheModelDefaults(): void
public function testCloneModelMakesAFreshCopyOfTheModel(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getTablePrefix')->times(2)->returns('');
$query = new BaseBuilder($connection, new Grammar($connection), new Processor);
$builder = (new Builder($query))->setModel(new Stub);
@@ -3683,7 +3689,7 @@ public function testCloneModelMakesAFreshCopyOfTheModel(): void
public function testToRawSql(): void
{
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('toRawSql')
->returns('select * from "users" where "email" = \'foo\'');
@@ -3694,7 +3700,7 @@ public function testToRawSql(): void
public function testPassthruMethodsCallsAreNotCaseSensitive(): void
{
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$mockResponse = 'select 1';
$query
@@ -3711,7 +3717,7 @@ public function testPassthruMethodsCallsAreNotCaseSensitive(): void
public function testPassthruArrayElementsMustAllBeLowercase(): void
{
- $builder = new class(Double::for(BaseBuilder::class)) extends Builder {
+ $builder = new class(Double::for(BaseBuilder::class)->strict()) extends Builder {
// expose protected member for test
public function getPassthru(): array
{
@@ -3759,7 +3765,7 @@ public function testPipeCallback(): void
public function testIncrementEachCallsToBaseWithUpdatedAt(): void
{
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('foo_table');
$query->expects('getFromAlias')->returns('foo_table');
$query->expects('incrementEach')->with(Argument::all(function (array $columns, array $extra): bool {
@@ -3784,7 +3790,7 @@ public function testIncrementEachCallsToBaseWithUpdatedAt(): void
public function testDecrementEachCallsToBaseWithUpdatedAt(): void
{
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('foo_table');
$query->expects('getFromAlias')->returns('foo_table');
$query->expects('decrementEach')->with(Argument::all(function (array $columns, array $extra): bool {
@@ -3809,7 +3815,7 @@ public function testDecrementEachCallsToBaseWithUpdatedAt(): void
public function testIncrementEachWithoutTimestamps(): void
{
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->expects('from')->with('foo_table');
$query->expects('incrementEach')->with(['votes' => 1], [])->returns(1);
@@ -3854,7 +3860,7 @@ protected function mockConnectionForModel(Model $model, string $database): Conne
$grammarClass = 'Hypervel\Database\Query\Grammars\\' . $database . 'Grammar';
$processorClass = 'Hypervel\Database\Query\Processors\\' . $database . 'Processor';
$processor = new $processorClass;
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getPostProcessor')->returns($processor);
$grammar = new $grammarClass($connection);
$connection->allows('getQueryGrammar')->returns($grammar);
@@ -3863,7 +3869,7 @@ protected function mockConnectionForModel(Model $model, string $database): Conne
return new BaseBuilder($connection, $grammar, $processor);
});
$connection->allows('getDatabaseName')->returns('database');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
$class = get_class($model);
$class::setConnectionResolver($resolver);
@@ -3884,7 +3890,7 @@ protected function getBuilder(): Builder
*/
protected function getMockModel(): Model
{
- $model = Double::for(Model::class);
+ $model = Double::for(Model::class)->strict();
$model->allows('getKeyName')->returns('foo');
$model->allows('getTable')->returns('foo_table');
$model->allows('getQualifiedKeyName')->returns('foo_table.foo');
@@ -3976,7 +3982,7 @@ protected function newBuilder(SQLiteConnection $connection): Builder
*/
protected function getMockQueryBuilder(): BaseBuilder
{
- $query = Double::for(BaseBuilder::class);
+ $query = Double::for(BaseBuilder::class)->strict();
$query->allows('from')->with('foo_table');
return $query;
diff --git a/tests/Database/DatabaseEloquentCollectionQueueableTest.php b/tests/Database/DatabaseEloquentCollectionQueueableTest.php
index 5d951a0d3c..331bc7c645 100644
--- a/tests/Database/DatabaseEloquentCollectionQueueableTest.php
+++ b/tests/Database/DatabaseEloquentCollectionQueueableTest.php
@@ -19,7 +19,7 @@ class DatabaseEloquentCollectionQueueableTest extends TestCase
public function testSerializesPivotsEntitiesId(): void
{
- $spy = Double::for(Pivot::class);
+ $spy = Double::for(Pivot::class)->strict();
$spy->expects('getQueueableId')->with(Argument::none())->returns('project_id:1:user_id:2');
$c = new Collection([$spy]);
@@ -29,7 +29,7 @@ public function testSerializesPivotsEntitiesId(): void
public function testSerializesModelEntitiesById(): void
{
- $spy = Double::for(Model::class);
+ $spy = Double::for(Model::class)->strict();
$spy->expects('getQueueableId')->with(Argument::none())->returns(1);
$c = new Collection([$spy]);
@@ -68,7 +68,7 @@ public function testJsonSerializationOfCollectionQueueableIdsWorks(): void
// When the ID of a Model is binary instead of int or string, the Collection
// serialization + JSON encoding breaks because of UTF-8 issues. Encoding
// of a QueueableCollection must favor QueueableEntity::queueableId().
- $mock = Double::for(Model::class);
+ $mock = Double::for(Model::class)->strict();
$mock->expects('getKey')->never();
$mock->expects('getQueueableId')->returns('mocked');
diff --git a/tests/Database/DatabaseEloquentCollectionTest.php b/tests/Database/DatabaseEloquentCollectionTest.php
index 537ad3d944..34bf3111a8 100755
--- a/tests/Database/DatabaseEloquentCollectionTest.php
+++ b/tests/Database/DatabaseEloquentCollectionTest.php
@@ -359,8 +359,8 @@ public function testFindOrFailThrowsExceptionWithoutMessageWhenOtherModelsAreNot
public function testLoadMethodEagerLoadsGivenRelationships(): void
{
- $model = Double::for(Model::class);
- $builder = Double::for(Builder::class);
+ $model = Double::for(Model::class)->strict();
+ $builder = Double::for(Builder::class)->strict();
$model->expects('newQueryWithoutRelationships')->returns($builder);
$builder->expects('with')->with(['bar', 'baz'])->returns($builder);
$builder->expects('eagerLoadRelations')->with([$model])->returns(['results']);
@@ -372,7 +372,7 @@ public function testLoadMethodEagerLoadsGivenRelationships(): void
public function testLoadMissingWithoutRelationsDoesNotBuildAQuery(): void
{
- $model = Double::for(Model::class);
+ $model = Double::for(Model::class)->strict();
$model->expects('newQueryWithoutRelationships')->never();
$collection = new Collection([$model]);
@@ -1005,15 +1005,15 @@ public function testEmptyCollectionStayEmptyOnFresh(): void
public function testCanConvertCollectionOfModelsToEloquentQueryBuilder(): void
{
- $one = Double::for(Model::class);
+ $one = Double::for(Model::class)->strict();
$one->allows('getKey')->returns(1);
- $two = Double::for(Model::class);
+ $two = Double::for(Model::class)->strict();
$two->allows('getKey')->returns(2);
$c = new Collection([$one, $two]);
- $mocBuilder = Double::for(Builder::class);
+ $mocBuilder = Double::for(Builder::class)->strict();
$one->expects('newModelQuery')->returns($mocBuilder);
$mocBuilder->expects('whereKey')->with($c->modelKeys())->returns($mocBuilder);
$this->assertInstanceOf(Builder::class, $c->toQuery());
diff --git a/tests/Database/DatabaseEloquentCreateOrFirstValidationTest.php b/tests/Database/DatabaseEloquentCreateOrFirstValidationTest.php
index 864ead2972..c3d995cf5c 100644
--- a/tests/Database/DatabaseEloquentCreateOrFirstValidationTest.php
+++ b/tests/Database/DatabaseEloquentCreateOrFirstValidationTest.php
@@ -24,13 +24,13 @@ class DatabaseEloquentCreateOrFirstValidationTest extends TestCase
#[DataProvider('creationHelpers')]
public function testRelatedBuilderValidationRunsBeforeQueriesAndValueCallbacks(string $relation, string $method): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$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 = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
Model::setConnectionResolver($resolver);
$parent = new CreationValidationParent(['id' => 1]);
diff --git a/tests/Database/DatabaseEloquentFactoryTest.php b/tests/Database/DatabaseEloquentFactoryTest.php
index 6c8d2e33a8..5d5b5e79cf 100644
--- a/tests/Database/DatabaseEloquentFactoryTest.php
+++ b/tests/Database/DatabaseEloquentFactoryTest.php
@@ -54,7 +54,7 @@ protected function setUp(): void
$container->singleton(Generator::class, function (Container $app, array $parameters): Generator {
return FakerFactory::create('en_US');
});
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->allows('getNamespace')->returns('App\\');
$container->instance(Application::class, $app->instance());
@@ -846,7 +846,7 @@ public function testResolveNestedModelFactories(): void
public function testResolveNestedModelNameFromFactory(): void
{
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->expects('getNamespace')->returns('Hypervel\Tests\Database\Fixtures\\');
Container::getInstance()->instance(Application::class, $app->instance());
@@ -859,7 +859,7 @@ public function testResolveNestedModelNameFromFactory(): void
public function testResolveNonAppNestedModelFactories(): void
{
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->allows('getNamespace')->returns('Foo\\');
Container::getInstance()->instance(Application::class, $app->instance());
@@ -930,19 +930,13 @@ public function testCanBeMacroable(): void
public function testFactoryCanConditionallyExecuteCode(): void
{
- UserFactory::new()
- ->when(true, function () {
- $this->assertTrue(true);
- })
- ->when(false, function () {
- $this->fail('Unreachable code that has somehow been reached.');
- })
- ->unless(false, function () {
- $this->assertTrue(true);
- })
- ->unless(true, function () {
- $this->fail('Unreachable code that has somehow been reached.');
- });
+ $factory = UserFactory::new();
+ $callback = static fn () => 'called';
+
+ $this->assertSame('called', $factory->when(true, $callback));
+ $this->assertSame($factory, $factory->when(false, $callback));
+ $this->assertSame('called', $factory->unless(false, $callback));
+ $this->assertSame($factory, $factory->unless(true, $callback));
}
public function testDynamicTrashedStateForSoftdeletesModels(): void
diff --git a/tests/Database/DatabaseEloquentInverseRelationTest.php b/tests/Database/DatabaseEloquentInverseRelationTest.php
index c8f892cd86..27db7fa081 100755
--- a/tests/Database/DatabaseEloquentInverseRelationTest.php
+++ b/tests/Database/DatabaseEloquentInverseRelationTest.php
@@ -28,7 +28,7 @@ class DatabaseEloquentInverseRelationTest extends TestCase
public function testBuilderCallbackIsNotAppliedWhenInverseRelationIsNotSet(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->returns(new HasInverseRelationRelatedStub);
$builder->expects('afterQuery')->never();
@@ -37,7 +37,7 @@ public function testBuilderCallbackIsNotAppliedWhenInverseRelationIsNotSet(): vo
public function testBuilderCallbackIsNotSetIfInverseRelationIsEmptyString(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub);
$builder->expects('afterQuery')->never();
@@ -48,7 +48,7 @@ public function testBuilderCallbackIsNotSetIfInverseRelationIsEmptyString(): voi
public function testBuilderCallbackIsNotSetIfInverseRelationshipDoesNotExist(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(3)->returns(new HasInverseRelationRelatedStub);
$builder->expects('afterQuery')->never();
@@ -59,7 +59,7 @@ public function testBuilderCallbackIsNotSetIfInverseRelationshipDoesNotExist():
public function testWithoutInverseMethodRemovesInverseRelation(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub);
$builder->expects('afterQuery')->returns($builder);
@@ -77,7 +77,7 @@ public function testBuilderCallbackIsAppliedWhenInverseRelationIsSet(): void
{
$parent = new HasInverseRelationParentStub;
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub);
$builder->expects('afterQuery')->with(Argument::satisfies(function (Closure $callback) use ($parent): bool {
$relation = (new ReflectionFunction($callback))->getClosureThis();
@@ -90,14 +90,12 @@ public function testBuilderCallbackIsAppliedWhenInverseRelationIsSet(): void
public function testBuilderCallbackAppliesInverseRelationToAllModelsInResult(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub);
// Capture the callback so that we can manually call it.
$afterQuery = null;
- $builder->expects('afterQuery')->with(Argument::satisfies(function (Closure $callback) use (&$afterQuery): bool {
- return (bool) $afterQuery = $callback;
- }))->returns($builder);
+ $builder->expects('afterQuery')->with(Argument::capture($afterQuery))->returns($builder);
$parent = new HasInverseRelationParentStub;
(new HasInverseRelationStub($builder, $parent))->inverse('test');
@@ -120,14 +118,12 @@ public function testBuilderCallbackAppliesInverseRelationToAllModelsInResult():
public function testInverseRelationIsNotSetIfInverseRelationIsUnset(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(2)->returns(new HasInverseRelationRelatedStub);
// Capture the callback so that we can manually call it.
$afterQuery = null;
- $builder->expects('afterQuery')->with(Argument::satisfies(function (Closure $callback) use (&$afterQuery): bool {
- return (bool) $afterQuery = $callback;
- }))->returns($builder);
+ $builder->expects('afterQuery')->with(Argument::capture($afterQuery))->returns($builder);
$parent = new HasInverseRelationParentStub;
$relation = (new HasInverseRelationStub($builder, $parent));
@@ -158,7 +154,7 @@ public function testInverseRelationIsNotSetIfInverseRelationIsUnset(): void
public function testProvidesPossibleInverseRelationBasedOnParent(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->allows('getModel')->returns(new HasInverseRelationRelatedStub);
$relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub));
@@ -169,7 +165,7 @@ public function testProvidesPossibleInverseRelationBasedOnParent(): void
public function testProvidesPossibleInverseRelationBasedOnForeignKey(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(2)->returns(new HasInverseRelationParentStub);
$relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub, 'test_id'));
@@ -179,7 +175,7 @@ public function testProvidesPossibleInverseRelationBasedOnForeignKey(): void
public function testProvidesPossibleRecursiveRelationsIfRelatedIsTheSameClassAsParent(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(2)->returns(new HasInverseRelationParentStub);
$relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub));
@@ -190,10 +186,10 @@ public function testProvidesPossibleRecursiveRelationsIfRelatedIsTheSameClassAsP
#[DataProvider('guessedParentRelationsDataProvider')]
public function testGuessesInverseRelationBasedOnParent($guessedRelation): void
{
- $related = Double::for(Model::class);
+ $related = Double::for(Model::class)->strict();
$related->allows('isRelation')->resolves(fn ($relation) => $relation === $guessedRelation);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->allows('getModel')->returns($related);
$relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub));
@@ -203,10 +199,10 @@ public function testGuessesInverseRelationBasedOnParent($guessedRelation): void
public function testGuessesPossibleInverseRelationBasedOnForeignKey(): void
{
- $related = Double::for(Model::class);
+ $related = Double::for(Model::class)->strict();
$related->expects('isRelation')->resolves(fn (string $relation): bool => $relation === 'test');
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(3)->returns($related);
$relation = (new HasInverseRelationStub($builder, new HasInverseRelationParentStub, 'test_id'));
@@ -216,14 +212,14 @@ public function testGuessesPossibleInverseRelationBasedOnForeignKey(): void
public function testGuessesRecursiveInverseRelationsIfRelatedIsSameClassAsParent(): void
{
- $related = Double::for(Model::class);
+ $related = Double::for(Model::class)->strict();
$related->expects('isRelation')->times(4)->resolves(fn (string $relation): bool => $relation === 'parent');
- $parent = Double::for(Model::class);
+ $parent = Double::for(Model::class)->strict();
$parent->expects('getForeignKey')->returns('recursive_parent_id');
$parent->expects('getKeyName')->times(2)->returns('id');
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(6)->returns($related);
$relation = (new HasInverseRelationStub($builder, $parent));
@@ -234,10 +230,10 @@ public function testGuessesRecursiveInverseRelationsIfRelatedIsSameClassAsParent
#[DataProvider('guessedParentRelationsDataProvider')]
public function testSetsGuessedInverseRelationBasedOnParent($guessedRelation): void
{
- $related = Double::for(Model::class);
+ $related = Double::for(Model::class)->strict();
$related->allows('isRelation')->resolves(fn ($relation) => $relation === $guessedRelation);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->allows('getModel')->returns($related);
$builder->expects('afterQuery')->returns($builder);
@@ -255,14 +251,14 @@ public static function guessedParentRelationsDataProvider()
public function testSetsRecursiveInverseRelationsIfRelatedIsSameClassAsParent(): void
{
- $related = Double::for(Model::class);
+ $related = Double::for(Model::class)->strict();
$related->expects('isRelation')->times(5)->resolves(fn (string $relation): bool => $relation === 'parent');
- $parent = Double::for(Model::class);
+ $parent = Double::for(Model::class)->strict();
$parent->expects('getForeignKey')->returns('recursive_parent_id');
$parent->expects('getKeyName')->times(2)->returns('id');
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(7)->returns($related);
$builder->expects('afterQuery')->returns($builder);
@@ -273,10 +269,10 @@ public function testSetsRecursiveInverseRelationsIfRelatedIsSameClassAsParent():
public function testSetsGuessedInverseRelationBasedOnForeignKey(): void
{
- $related = Double::for(Model::class);
+ $related = Double::for(Model::class)->strict();
$related->expects('isRelation')->times(2)->resolves(fn (string $relation): bool => $relation === 'test');
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getModel')->times(4)->returns($related);
$builder->expects('afterQuery')->returns($builder);
diff --git a/tests/Database/DatabaseEloquentJsonCastTest.php b/tests/Database/DatabaseEloquentJsonCastTest.php
index 902000e781..0f50bc701f 100644
--- a/tests/Database/DatabaseEloquentJsonCastTest.php
+++ b/tests/Database/DatabaseEloquentJsonCastTest.php
@@ -140,7 +140,7 @@ public function testJsonPathAssignmentRejectsEncoderFalseBeforeStorageOrEncrypti
{
$model = new JsonCastModel;
$model->mergeCasts(['encrypted_payload' => 'encrypted:array']);
- $encrypter = Double::for(Encrypter::class);
+ $encrypter = Double::for(Encrypter::class)->strict();
$encrypter->expects('encrypt')->never();
Model::encryptUsing($encrypter);
diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php
index e1500293a6..47b35d5b2d 100755
--- a/tests/Database/DatabaseEloquentModelTest.php
+++ b/tests/Database/DatabaseEloquentModelTest.php
@@ -84,6 +84,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use LogicException;
use PDO;
use PHPUnit\Framework\Attributes\DataProvider;
@@ -864,7 +865,7 @@ public function testInsertProcess(): void
#[TestWith([['name' => 'taylor'], 'insert into "stub" ("name") values (?)', ['taylor']])]
public function testNonIncrementingModelInsertsOneRow(array $attributes, string $sql, array $bindings): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$connection->allows('getWritableName')->returns('testing');
$grammar = new Grammar($connection);
@@ -874,7 +875,7 @@ public function testNonIncrementingModelInsertsOneRow(array $attributes, string
);
$connection->expects('insert')->with($sql, $bindings)->returns(true);
- Model::setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class));
+ Model::setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class)->strict());
$resolver->allows('connection')->returns($connection);
$model = new class extends ModelStub {
@@ -897,7 +898,7 @@ public function testNonIncrementingModelWithoutAttributesDoesNotInsert(): void
$model->setConnection('testing');
$model->setIncrementing(false);
$model->timestamps = false;
- $baseQuery = Double::for(BaseBuilder::class);
+ $baseQuery = Double::for(BaseBuilder::class)->strict();
$baseQuery->expects('insert')->never();
$query = new Builder($baseQuery);
$model->expects($this->once())->method('newModelQuery')->willReturn($query);
@@ -993,7 +994,7 @@ public function testInsertOrIgnoreProcessWithNamedUnique(): void
#[TestWith([true, ['name' => 'taylor'], ['name'], 'insert into "stub" ("name") values (?) on conflict ("name") do nothing returning *', ['taylor']])]
public function testInsertOrIgnorePreservesOneModelRow(bool $incrementing, array $attributes, array $uniqueBy, string $sql, array $bindings): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$connection->allows('getWritableName')->returns('testing');
$grammar = new PostgresGrammar($connection);
@@ -1005,7 +1006,7 @@ public function testInsertOrIgnorePreservesOneModelRow(bool $incrementing, array
->with($sql, $bindings)->returns([(object) ['id' => 1, ...$attributes]]);
$connection->expects('recordsHaveBeenModified')->with(true);
- Model::setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class));
+ Model::setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class)->strict());
$resolver->allows('connection')->returns($connection);
$model = new class($attributes) extends ModelStub {
@@ -1033,13 +1034,13 @@ public function testInsertOrIgnoreThrowsWithoutAttributes(): void
$model = $this->getMockBuilder(ModelStub::class)
->onlyMethods(['newModelQuery', 'updateTimestamps'])
->getMock();
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$model->expects($this->once())->method('newModelQuery')->willReturn($query);
$model->expects($this->once())->method('updateTimestamps');
- $model::setEventDispatcher($events = Double::for(Dispatcher::class));
- $events->expects('until')->with('eloquent.saving: ' . get_class($model), $model)->returns(true);
- $events->expects('until')->with('eloquent.creating: ' . get_class($model), $model)->returns(true);
+ $model::setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
+ $events->expects('until')->with('eloquent.saving: ' . get_class($model), Argument::same($model))->returns(true);
+ $events->expects('until')->with('eloquent.creating: ' . get_class($model), Argument::same($model))->returns(true);
$this->expectExceptionObject(new LogicException('Cannot use saveOrIgnore on a model without attributes.'));
@@ -1188,7 +1189,7 @@ public function testConnectionManagement(): void
#[TestWith([ConnectionNameBacked::Foo])]
public function testConnectionEnums(string|UnitEnum $connectionName): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
ModelStub::setConnectionResolver($resolver);
$model = new ModelStub;
@@ -1196,7 +1197,7 @@ public function testConnectionEnums(string|UnitEnum $connectionName): void
$this->assertEquals($retval, $model);
$this->assertSame('Foo', $model->getConnectionName());
- $mockConnection = Double::for(Connection::class);
+ $mockConnection = Double::for(Connection::class)->strict();
$resolver->expects('connection')->with('Foo')->returns($mockConnection);
$this->assertSame($mockConnection, $model->getConnection());
@@ -2114,11 +2115,11 @@ public function testGuarded(): void
{
$model = new ModelStub;
- $resolver = Double::for(Resolver::class);
+ $resolver = Double::for(Resolver::class)->strict();
ModelStub::setConnectionResolver($resolver);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$resolver->allows('connection')->returns($connection);
- $schema = Double::for(SchemaBuilder::class);
+ $schema = Double::for(SchemaBuilder::class)->strict();
$schema->expects('getColumnListing')->returns(['name', 'age', 'foo']);
$connection->expects('getSchemaBuilder')->returns($schema);
@@ -2160,11 +2161,11 @@ public function testGuardedWithFillableConfig(): void
public function testUsesOverriddenHandlerWhenDiscardingAttributes(): void
{
- $resolver = Double::for(Resolver::class);
+ $resolver = Double::for(Resolver::class)->strict();
ModelStub::setConnectionResolver($resolver);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$resolver->allows('connection')->returns($connection);
- $schema = Double::for(SchemaBuilder::class);
+ $schema = Double::for(SchemaBuilder::class)->strict();
$schema->expects('getColumnListing')->returns(['name', 'age', 'foo']);
$connection->expects('getSchemaBuilder')->returns($schema);
@@ -2617,7 +2618,7 @@ public function testCloneModelMakesAFreshCopyOfTheModelWhenModelHasUlid(): void
public function testModelObserversCanBeAttachedToModels(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('dispatch');
$events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestObserverStub::class . '@creating');
$events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestObserverStub::class . '@saved');
@@ -2629,7 +2630,7 @@ public function testModelObserversCanBeAttachedToModels(): void
public function testModelObserversCanBeAttachedToModelsWithString(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('dispatch');
$events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestObserverStub::class . '@creating');
$events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestObserverStub::class . '@saved');
@@ -2641,7 +2642,7 @@ public function testModelObserversCanBeAttachedToModelsWithString(): void
public function testModelObserversCanBeAttachedToModelsThroughAnArray(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('dispatch');
$events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestObserverStub::class . '@creating');
$events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestObserverStub::class . '@saved');
@@ -2653,7 +2654,7 @@ public function testModelObserversCanBeAttachedToModelsThroughAnArray(): void
public function testModelObserversCanBeAttachedToModelsWithStringUsingAttribute(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('dispatch')->times(2);
$events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeStub', TestObserverStub::class . '@creating');
$events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeStub', TestObserverStub::class . '@saved');
@@ -2664,7 +2665,7 @@ public function testModelObserversCanBeAttachedToModelsWithStringUsingAttribute(
public function testModelObserversCanBeAttachedToModelsThroughAnArrayUsingAttribute(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('dispatch')->times(2);
$events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeUsingArrayStub', TestObserverStub::class . '@creating');
$events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeUsingArrayStub', TestObserverStub::class . '@saved');
@@ -2675,7 +2676,7 @@ public function testModelObserversCanBeAttachedToModelsThroughAnArrayUsingAttrib
public function testModelObserversCanBeAttachedToModelsThroughAttributesOnParentClasses(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('dispatch')->times(2);
$events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeGrandchildStub', TestObserverStub::class . '@creating');
$events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelWithObserveAttributeGrandchildStub', TestObserverStub::class . '@saved');
@@ -2702,7 +2703,7 @@ public function testThrowExceptionOnAttachingNotExistsModelObserversThroughAnArr
public function testModelObserversCanBeAttachedToModelsThroughCallingObserveMethodOnlyOnce(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('dispatch');
$events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestObserverStub::class . '@creating');
$events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\ModelStub', TestObserverStub::class . '@saved');
@@ -2726,7 +2727,7 @@ public function testWithoutEventDispatcher(): void
// Boot the model before the dispatcher is set so booting events aren't dispatched.
new SaveStub;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('listen')->with('eloquent.creating: Hypervel\Tests\Database\DatabaseEloquentModelTest\SaveStub', TestObserverStub::class . '@creating');
$events->expects('listen')->with('eloquent.saved: Hypervel\Tests\Database\DatabaseEloquentModelTest\SaveStub', TestObserverStub::class . '@saved');
SaveStub::setEventDispatcher($events);
@@ -3027,9 +3028,9 @@ public function testIncrementReturnsFalseWhenUpdatingEventIsCancelled(): void
$model->foo = 1;
$model->expects('newQueryWithoutScopes')->never();
- $model->setEventDispatcher($events = Double::for(Dispatcher::class));
+ $model->setEventDispatcher($events = Double::for(Dispatcher::class)->strict());
$events->expects('until')
- ->with('eloquent.updating: ' . get_class($model), $model)
+ ->with('eloquent.updating: ' . get_class($model), Argument::same($model))
->returns(false);
$this->assertFalse($model->publicIncrement('foo'));
@@ -3045,7 +3046,7 @@ public function testIncrementEachQuietlyOnExistingModelCallsQueryAndSetsAttribut
$model->foo = 2;
$model->bar = 5;
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$model->expects('newQueryWithoutScopes')->times(2)->returns($query);
$query->expects('where')->times(2)->returns($query);
$query->expects('incrementEach')->times(2)->returns(1);
@@ -3075,7 +3076,7 @@ public function testDecrementEachQuietlyOnExistingModelCallsQueryAndSetsAttribut
$model->foo = 10;
$model->bar = 5;
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$model->expects('newQueryWithoutScopes')->times(2)->returns($query);
$query->expects('where')->times(2)->returns($query);
$query->expects('decrementEach')->times(2)->returns(1);
@@ -3904,7 +3905,7 @@ public function testSaveQueryRejectsAMissingPrimaryKey(): void
{
$model = new ModelStub;
$model->exists = true;
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->never();
$this->expectException(MissingAttributeException::class);
@@ -3916,7 +3917,7 @@ public function testSelectQueryRejectsAMissingPrimaryKey(): void
{
$model = new ModelStub;
$model->exists = true;
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->never();
$this->expectException(MissingAttributeException::class);
@@ -3953,7 +3954,7 @@ public function testWithoutTouchingOnCallback(): void
public function testFlushGuardableColumnsRestoresOnlyGuardableColumnMetadata(): void
{
$reflection = new ReflectionClass(Model::class);
- $resolver = Double::for(Resolver::class);
+ $resolver = Double::for(Resolver::class)->strict();
Model::setConnectionResolver($resolver);
$reflection->setStaticPropertyValue('guardableColumns', [ModelStub::class => ['id']]);
@@ -3968,8 +3969,8 @@ public function testFlushStateRestoresStaticState(): void
{
$reflection = new ReflectionClass(Model::class);
- Model::setConnectionResolver(Double::for(Resolver::class));
- Model::setEventDispatcher(Double::for(Dispatcher::class));
+ Model::setConnectionResolver(Double::for(Resolver::class)->strict());
+ Model::setEventDispatcher(Double::for(Dispatcher::class)->strict());
Model::preventLazyLoading();
Model::automaticallyEagerLoadRelationships();
Model::handleLazyLoadingViolationUsing(static function () {
@@ -3981,7 +3982,7 @@ public function testFlushStateRestoresStaticState(): void
Model::handleMissingAttributeViolationUsing(static function () {
});
Model::$snakeAttributes = false;
- Model::encryptUsing(Double::for(Encrypter::class));
+ Model::encryptUsing(Double::for(Encrypter::class)->strict());
$reflection->setStaticPropertyValue('booting', [ModelStub::class => 1]);
$reflection->setStaticPropertyValue('booted', [ModelStub::class => true]);
@@ -4301,12 +4302,8 @@ public function testThrowingExistenceAccessorRestoresMissingAttributeChecks(): v
$this->assertSame($failure, $exception);
}
- try {
- $model->missing;
- $this->fail('Missing attribute checks were not restored.');
- } catch (MissingAttributeException) {
- $this->addToAssertionCount(1);
- }
+ $this->expectException(MissingAttributeException::class);
+ $model->missing;
} finally {
Model::preventAccessingMissingAttributes($originalMode);
}
@@ -4340,9 +4337,9 @@ public function testExistenceCheckSuppressesCustomMissingAttributeCallbackOnlyLo
*/
protected function addMockConnection(Model $model): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$model->setConnectionResolver($resolver);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$resolver->allows('connection')->returns($connection);
$grammar = new Grammar($connection);
$connection->allows('getQueryGrammar')->returns($grammar);
@@ -5216,7 +5213,7 @@ public function setIncrementing(bool $value): static
*/
public function getConnection(): Connection
{
- $mock = Double::for(Connection::class);
+ $mock = Double::for(Connection::class)->strict();
$grammar = new Grammar($mock);
$mock->allows('getQueryGrammar')->returns($grammar);
$processor = new Processor;
diff --git a/tests/Database/DatabaseEloquentMorphToTest.php b/tests/Database/DatabaseEloquentMorphToTest.php
index 054790f329..138066a4a5 100644
--- a/tests/Database/DatabaseEloquentMorphToTest.php
+++ b/tests/Database/DatabaseEloquentMorphToTest.php
@@ -226,7 +226,7 @@ public function testAssociateMethodIgnoresNullValue(): void
public function testAssociateMethodUsesConfiguredOwnerKeyWithZeroValue(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->allows('getModel')->returns(new MorphToAssociateRelatedStub);
$parent = new MorphToAssociateParentStub;
@@ -252,7 +252,7 @@ public function testAssociateMethodUsesConfiguredOwnerKeyWithZeroValue(): void
public function testAssociateMethodUsesConfiguredOwnerKeyWithNullValue(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->allows('getModel')->returns(new MorphToAssociateRelatedStub);
$parent = new MorphToAssociateParentStub;
@@ -278,7 +278,7 @@ public function testAssociateMethodUsesConfiguredOwnerKeyWithNullValue(): void
public function testAssociateMethodRejectsScalarValuesBeforeChangingTheParent(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->allows('getModel')->returns(new MorphToAssociateRelatedStub);
$parent = (new MorphToAssociateParentStub)->forceFill([
@@ -309,7 +309,7 @@ public function testAssociateMethodRejectsScalarValuesBeforeChangingTheParent():
public function testAssociateMethodRejectsUnmappedModelsBeforeChangingTheParent(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->allows('getModel')->returns(new MorphToAssociateRelatedStub);
$parent = (new MorphToAssociateParentStub)->forceFill([
@@ -371,7 +371,7 @@ public function __toString(): string
}
};
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$related = new RelatedStub;
$builder->expects('getModel')->returns($related);
@@ -385,7 +385,7 @@ public function __toString(): string
$relation->addEagerConstraints([$parent]);
- $result = Double::for(Model::class);
+ $result = Double::for(Model::class)->strict();
$result->expects('getKey')->returns($uuidObject);
$relation->callMatchToMorphParents('type_1', new EloquentCollection([$result]));
@@ -415,9 +415,9 @@ protected function getRelationWithRealQuery(): MorphTo
public function getRelation($parent = null, $builder = null)
{
- $this->builder = $builder ?: Double::for(Builder::class);
+ $this->builder = $builder ?: Double::for(Builder::class)->strict();
$this->builder->allows('where')->with('relation.id', '=', 'foreign.value')->returns($this->builder);
- $this->related = Double::for(Model::class);
+ $this->related = Double::for(Model::class)->strict();
$this->related->allows('getKeyName')->returns('id');
$this->related->allows('getTable')->returns('relation');
$this->related->allows('qualifyColumn')->resolves(fn (string $column) => "relation.{$column}");
diff --git a/tests/Database/DatabaseEloquentPivotTest.php b/tests/Database/DatabaseEloquentPivotTest.php
index 87ce9f208d..4605ff01bf 100755
--- a/tests/Database/DatabaseEloquentPivotTest.php
+++ b/tests/Database/DatabaseEloquentPivotTest.php
@@ -25,9 +25,9 @@ public function testPropertiesAreSetCorrectly(): void
{
$parent = Double::for(Model::class)->passthru();
$parent->expects('getConnectionName')->times(1)->returns('connection');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$parent->setConnectionResolver($resolver);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$resolver->expects('connection')->times(1)->returns($connection);
$grammar = new Grammar($connection);
$connection->expects('getQueryGrammar')->times(1)->returns($grammar);
@@ -124,7 +124,7 @@ public function testDeleteMethodDeletesModelByKeys(): void
$pivot->setPivotKeys('foreign', 'other');
$pivot->foreign = 'foreign.value';
$pivot->other = 'other.value';
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->with(['foreign' => 'foreign.value', 'other' => 'other.value'])->returns($query);
$query->expects('delete')->returns(1);
$pivot->expects($this->once())->method('newQueryWithoutRelationships')->willReturn($query);
@@ -138,8 +138,8 @@ public function testModelDeleteWrappersReturnAffectedRowCountForPivots(): void
$pivot = new DeleteReturnPivotStub;
$pivot->exists = true;
- $pivot->setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class));
- $resolver->expects('connection')->returns($connection = Double::for(Connection::class));
+ $pivot->setConnectionResolver($resolver = Double::for(ConnectionResolverInterface::class)->strict());
+ $resolver->expects('connection')->returns($connection = Double::for(Connection::class)->strict());
$connection->expects('transaction')->resolves(fn ($callback) => $callback());
$this->assertSame(1, $pivot->deleteQuietly());
@@ -173,7 +173,7 @@ public function testPivotModelTableNameIsSingular(): void
public function testRestorationQueriesUsePrimaryKeys(string $pivotClass, array|int|string $ids): void
{
$pivot = $this->getMockBuilder($pivotClass)->onlyMethods(['newQueryWithoutScopes'])->getMock();
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('whereKey')->with($ids)->returns($query);
$pivot->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
@@ -205,7 +205,7 @@ public function testWithoutRelations(): void
{
$original = new Pivot;
- $parentModel = Double::for(Model::class);
+ $parentModel = Double::for(Model::class)->strict();
$original->pivotParent = $parentModel;
$original->setRelation('bar', 'baz');
diff --git a/tests/Database/DatabaseEloquentRelationshipsTest.php b/tests/Database/DatabaseEloquentRelationshipsTest.php
index 9d99508186..bc24b6516c 100644
--- a/tests/Database/DatabaseEloquentRelationshipsTest.php
+++ b/tests/Database/DatabaseEloquentRelationshipsTest.php
@@ -277,7 +277,7 @@ class MockedConnectionModel extends Model
*/
public function getConnection(): Connection
{
- $mock = Double::for(Connection::class);
+ $mock = Double::for(Connection::class)->strict();
$grammar = new Grammar($mock);
$mock->allows('getQueryGrammar')->returns($grammar);
$processor = new Processor;
diff --git a/tests/Database/DatabaseEloquentRouteBindingTest.php b/tests/Database/DatabaseEloquentRouteBindingTest.php
index 9a14016512..f7be92ac5e 100644
--- a/tests/Database/DatabaseEloquentRouteBindingTest.php
+++ b/tests/Database/DatabaseEloquentRouteBindingTest.php
@@ -23,7 +23,7 @@ class DatabaseEloquentRouteBindingTest extends TestCase
#[DataProvider('invalidIntegerKeyProvider')]
public function testItRejectsValuesThatCannotAddressAnIntegerKeyWithoutQuerying(mixed $value): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->never();
$this->expectException(ModelNotFoundException::class);
@@ -55,7 +55,7 @@ public static function invalidIntegerKeyProvider(): array
#[DataProvider('validIntegerKeyProvider')]
public function testItPassesThroughValuesTheDatabaseCanStillMatch(int|string $value): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->with('id', $value);
$this->assertSame($query, (new RouteBindingIntKeyModel)->resolveRouteBindingQuery($query, $value));
@@ -83,7 +83,7 @@ public static function validIntegerKeyProvider(): array
#[TestWith(['integer'])]
public function testItValidatesQualifiedKeyColumnsFromChildBindings(string $keyType): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->never();
$this->expectException(ModelNotFoundException::class);
@@ -93,7 +93,7 @@ public function testItValidatesQualifiedKeyColumnsFromChildBindings(string $keyT
public function testItDoesNotValidateNonKeyBindingFields(): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->with('slug', 'abc');
(new RouteBindingIntKeyModel)->resolveRouteBindingQuery($query, 'abc', 'slug');
@@ -101,7 +101,7 @@ public function testItDoesNotValidateNonKeyBindingFields(): void
public function testItDoesNotValidateModelsWithStringKeys(): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->with('id', 'abc');
(new RouteBindingStringKeyModel)->resolveRouteBindingQuery($query, 'abc');
@@ -112,7 +112,7 @@ public function testItDoesNotValidateModelsWithStringKeys(): void
public function testItValidatesNonIncrementingModelsWithTheDefaultKeyType(): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->never();
$this->expectException(ModelNotFoundException::class);
@@ -122,7 +122,7 @@ public function testItValidatesNonIncrementingModelsWithTheDefaultKeyType(): voi
public function testItDoesNotValidateNullValuesForModelsWithStringKeys(): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->with('id', null);
(new RouteBindingStringKeyModel)->resolveRouteBindingQuery($query, null);
@@ -130,7 +130,7 @@ public function testItDoesNotValidateNullValuesForModelsWithStringKeys(): void
public function testTheInvalidKeyHandlerMayBeOverridden(): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->never();
$this->expectException(RuntimeException::class);
@@ -141,7 +141,7 @@ public function testTheInvalidKeyHandlerMayBeOverridden(): void
public function testTheExceptionCarriesTheModelAndValue(): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
try {
(new RouteBindingIntKeyModel)->resolveRouteBindingQuery($query, 'abc');
@@ -161,7 +161,7 @@ public function testTheExceptionCarriesTheModelAndValue(): void
#[DataProvider('nullRouteKeyModelProvider')]
public function testNullValuesCarryNoIdentifiers(string $model): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->never();
try {
@@ -190,7 +190,7 @@ public static function nullRouteKeyModelProvider(): array
public function testItValidatesQualifiedUniqueIdColumnsFromChildBindings(): void
{
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$query->expects('where')->never();
$this->expectException(ModelNotFoundException::class);
@@ -202,7 +202,7 @@ public function testItPassesQualifiedUniqueIdColumnsThroughForValidIds(): void
{
$uuid = '0190ecbd-0aa7-7cc8-9d51-4b4f6fb3a3c7';
- $query = Double::for(Builder::class);
+ $query = Double::for(Builder::class)->strict();
$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/DatabaseManagerSetDefaultConnectionTest.php b/tests/Database/DatabaseManagerSetDefaultConnectionTest.php
index ddeb258659..737bf00d1b 100644
--- a/tests/Database/DatabaseManagerSetDefaultConnectionTest.php
+++ b/tests/Database/DatabaseManagerSetDefaultConnectionTest.php
@@ -127,9 +127,9 @@ protected function makeManager(array $databaseConfig, ?Repository $config = null
$app = Container::getInstance();
$app->instance('config', $config);
- $app->instance(PoolManager::class, Double::for(PoolManager::class));
+ $app->instance(PoolManager::class, Double::for(PoolManager::class)->strict());
- $factory = Double::for(ConnectionFactory::class);
+ $factory = Double::for(ConnectionFactory::class)->strict();
return new DatabaseManager($app, $factory);
}
diff --git a/tests/Database/DatabaseManagerTest.php b/tests/Database/DatabaseManagerTest.php
index 27bbb41506..c4d4ef0da4 100644
--- a/tests/Database/DatabaseManagerTest.php
+++ b/tests/Database/DatabaseManagerTest.php
@@ -54,7 +54,7 @@ public function testSetDefaultConnectionAcceptsEnums(): void
$config = new Repository(['database' => ['default' => 'sqlite']]);
$container->instance('config', $config);
- $manager = new DatabaseManager($container, Double::for(ConnectionFactory::class));
+ $manager = new DatabaseManager($container, Double::for(ConnectionFactory::class)->strict());
$manager->setDefaultConnection(DatabaseManagerTestBackedConnection::Reporting);
@@ -76,7 +76,7 @@ public function testUsingConnectionAcceptsEnumsAndRestoresTheDefaultConnection()
$container = new Container;
$container->instance('config', new Repository(['database' => ['default' => 'sqlite']]));
- $manager = new DatabaseManager($container, Double::for(ConnectionFactory::class));
+ $manager = new DatabaseManager($container, Double::for(ConnectionFactory::class)->strict());
$default = $manager->usingConnection(DatabaseManagerTestBackedConnection::Reporting, fn (): ?string => $manager->getDefaultConnection());
@@ -239,10 +239,9 @@ public function testDisconnectWithNoExistingConnectionDoesNotError(): void
{
$manager = $this->db->getDatabaseManager();
- // Should not throw — no connection has been resolved yet
$manager->disconnect();
- $this->assertTrue(true);
+ $this->assertSame([], $manager->getConnections());
}
public function testReconnectAfterDisconnectOnNonPooledConnection(): void
diff --git a/tests/Database/DatabaseMariaDbBuilderTest.php b/tests/Database/DatabaseMariaDbBuilderTest.php
index bc73734392..f08ef7a864 100644
--- a/tests/Database/DatabaseMariaDbBuilderTest.php
+++ b/tests/Database/DatabaseMariaDbBuilderTest.php
@@ -17,7 +17,7 @@ class DatabaseMariaDbBuilderTest extends TestCase
public function testCreateDatabase(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new MariaDbGrammar($connection);
$connection->expects('getConfig')->with('charset')->returns('utf8mb4');
@@ -33,7 +33,7 @@ public function testCreateDatabase(): void
public function testDropDatabaseIfExists(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new MariaDbGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
diff --git a/tests/Database/DatabaseMariaDbQueryGrammarTest.php b/tests/Database/DatabaseMariaDbQueryGrammarTest.php
index c1ff1702ca..1830206c03 100755
--- a/tests/Database/DatabaseMariaDbQueryGrammarTest.php
+++ b/tests/Database/DatabaseMariaDbQueryGrammarTest.php
@@ -21,13 +21,13 @@ public function testUpdateBindingsRejectUnencodableArrays(): void
{
$this->expectException(JsonException::class);
- (new MariaDbGrammar(Double::for(Connection::class)))
+ (new MariaDbGrammar(Double::for(Connection::class)->strict()))
->prepareBindingsForUpdate([], ['payload' => [NAN]]);
}
public function testToRawSql(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('escape')->with('foo', false)->returns("'foo'");
$grammar = new MariaDbGrammar($connection);
@@ -106,14 +106,14 @@ public function testTimeoutCanBeCleared(): void
protected function getBuilder(): Builder
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getDatabaseName')->returns('database');
$connection->allows('getTablePrefix')->returns('');
return new Builder(
$connection,
new MariaDbGrammar($connection),
- Double::for(Processor::class)
+ Double::for(Processor::class)->strict()
);
}
}
diff --git a/tests/Database/DatabaseMariaDbSchemaBuilderTest.php b/tests/Database/DatabaseMariaDbSchemaBuilderTest.php
index 7ee171de9f..683ae2ffda 100755
--- a/tests/Database/DatabaseMariaDbSchemaBuilderTest.php
+++ b/tests/Database/DatabaseMariaDbSchemaBuilderTest.php
@@ -18,7 +18,7 @@ class DatabaseMariaDbSchemaBuilderTest extends TestCase
public function testHasTable(): void
{
- $connection = Double::for(MariaDbConnection::class);
+ $connection = Double::for(MariaDbConnection::class)->strict();
$connection->allows('usesBackslashEscapes')->returns(true);
$grammar = new MariaDbGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -31,7 +31,7 @@ public function testHasTable(): void
public function testGetColumnListing(): void
{
- $connection = Double::for(MariaDbConnection::class);
+ $connection = Double::for(MariaDbConnection::class)->strict();
$connection->allows('usesBackslashEscapes')->returns(true);
$grammar = new MariaDbGrammar($connection);
$processor = new MariaDbProcessor;
diff --git a/tests/Database/DatabaseMariaDbSchemaGrammarTest.php b/tests/Database/DatabaseMariaDbSchemaGrammarTest.php
index a5a7e8b1ca..47e4a097dd 100755
--- a/tests/Database/DatabaseMariaDbSchemaGrammarTest.php
+++ b/tests/Database/DatabaseMariaDbSchemaGrammarTest.php
@@ -1607,7 +1607,7 @@ protected function getConnection(
?MariaDbBuilder $builder = null,
string $prefix = ''
): Connection&DoubleInterface {
- $connection = Double::for(MariaDbConnection::class);
+ $connection = Double::for(MariaDbConnection::class)->strict();
$connection->allows('usesBackslashEscapes')->returns(true);
$connection->allows('getTablePrefix')->returns($prefix);
$connection->allows('getConfig')->with('prefix_indexes')->returns(null);
@@ -1647,6 +1647,6 @@ public function getGrammar(?Connection $connection = null): MariaDbGrammar
*/
public function getBuilder(): MariaDbBuilder&DoubleInterface
{
- return Double::for(MariaDbBuilder::class);
+ return Double::for(MariaDbBuilder::class)->strict();
}
}
diff --git a/tests/Database/DatabaseMigrationCreatorTest.php b/tests/Database/DatabaseMigrationCreatorTest.php
index 394010d859..5620737dd0 100755
--- a/tests/Database/DatabaseMigrationCreatorTest.php
+++ b/tests/Database/DatabaseMigrationCreatorTest.php
@@ -152,7 +152,7 @@ protected function getDatePrefix(): string
public function testOverriddenCreateMethodRetainsExistingDatePrefixBehavior(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('glob')->never();
$creator = new class($files, 'stubs') extends MigrationCreator {
@@ -259,7 +259,7 @@ public function testGlobFailureIsReported(): void
public function testDatePrefixUsesTheFrameworkClockWithoutAnActivePath(): void
{
- $creator = new class(Double::for(Filesystem::class)) extends MigrationCreator {
+ $creator = new class(Double::for(Filesystem::class)->strict()) extends MigrationCreator {
public function datePrefix(): string
{
return $this->getDatePrefix();
@@ -321,7 +321,7 @@ public function testCollisionFreePrefixesAreIsolatedAcrossConcurrentPaths(): voi
*/
protected function getCreator(array $methods = ['getDatePrefix']): MigrationCreator
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$customStubs = 'stubs';
if ($methods === []) {
diff --git a/tests/Database/DatabaseMigrationFreshCommandTest.php b/tests/Database/DatabaseMigrationFreshCommandTest.php
index 115284813d..c5bf64a15f 100644
--- a/tests/Database/DatabaseMigrationFreshCommandTest.php
+++ b/tests/Database/DatabaseMigrationFreshCommandTest.php
@@ -29,10 +29,10 @@ class DatabaseMigrationFreshCommandTest extends TestCase
public function testFreshWipesEveryPreExistingTargetThenMigratesDispatchesAndSeeds(): void
{
$app = $this->makeApplication();
- $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class));
+ $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)->strict());
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectPreExistingMigrationTargets($migrator, ['sqlite', 'analytics'], registeredPaths: ['/registered']);
@@ -103,7 +103,7 @@ public function testReachableDatabaseWithoutMigrationRepositoryIsStillWiped(): v
$app = $this->makeApplication();
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectPreExistingMigrationTargets($migrator, ['sqlite'], repositoryExists: false);
@@ -126,7 +126,7 @@ public function testMissingTargetIsCreatedAndVerifiedButNeverWiped(): void
$app = $this->makeApplication();
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations'];
@@ -196,7 +196,7 @@ public function testDecliningProductionConfirmationCreatesAndWipesNothing(): voi
$app = $this->makeApplication('production');
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations'];
@@ -232,7 +232,7 @@ public function testCreationFailurePreventsEveryWipeAndMigration(): void
$app = $this->makeApplication();
$command = $this->getMockBuilder(TestableFreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->creationFailure = $failure = new RuntimeException('create failed');
$command->setHypervel($app);
@@ -270,7 +270,7 @@ public function testWipeFailureAbortsBeforeMigration(): void
$app = $this->makeApplication();
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectPreExistingMigrationTargets($migrator, ['analytics']);
@@ -290,10 +290,11 @@ public function testWipeFailureAbortsBeforeMigration(): void
public function testMigrationFailureAbortsBeforeEventAndSeeding(): void
{
$app = $this->makeApplication();
- $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class));
+ $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)->strict());
+ $dispatcher->allows('hasListeners')->resolves(static fn (string $event): bool => $event === DatabaseRefreshed::class);
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectPreExistingMigrationTargets($migrator, ['sqlite']);
@@ -317,10 +318,10 @@ public function testMigrationFailureAbortsBeforeEventAndSeeding(): void
public function testSeedFailureOccursAfterDatabaseRefreshedEventAndFailsTheCommand(): void
{
$app = $this->makeApplication();
- $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class));
+ $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)->strict());
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectPreExistingMigrationTargets($migrator, ['sqlite']);
@@ -355,7 +356,7 @@ public function testUnclassifiedInspectionFailurePropagatesBeforeMutation(): voi
$app = $this->makeApplication();
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations'];
@@ -388,7 +389,7 @@ public function testFreshUsesTheSamePathOptionsForDiscoveryAndNestedMigrate(
$app = $this->makeApplication();
$command = $this->getMockBuilder(FreshCommand::class)
->onlyMethods(['call', 'callSilent'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict()])
->getMock();
$command->setHypervel($app);
$migrator->expects('paths')->never();
@@ -431,7 +432,7 @@ public static function migrationPathProvider(): array
public function testProhibitedFreshReturnsBeforeDiscovery(): void
{
$app = $this->makeApplication();
- $command = new FreshCommand($migrator = Double::for(Migrator::class));
+ $command = new FreshCommand($migrator = Double::for(Migrator::class)->strict());
$command->setHypervel($app);
$migrator->expects('getMigrationConnections')->never();
FreshCommand::prohibit();
diff --git a/tests/Database/DatabaseMigrationInstallCommandTest.php b/tests/Database/DatabaseMigrationInstallCommandTest.php
index 1dcee40ca6..26fbc2c722 100755
--- a/tests/Database/DatabaseMigrationInstallCommandTest.php
+++ b/tests/Database/DatabaseMigrationInstallCommandTest.php
@@ -23,7 +23,7 @@ class DatabaseMigrationInstallCommandTest extends TestCase
public function testFireCallsRepositoryToInstall(): void
{
$app = new ApplicationDatabaseInstallStub;
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$command = new InstallCommand($repository);
$command->setHypervel($app);
$repository->expects('setSource')->with('foo');
@@ -36,7 +36,7 @@ public function testFireCallsRepositoryToInstall(): void
public function testFireCallsRepositoryToInstallExists(): void
{
$app = new ApplicationDatabaseInstallStub;
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$command = new InstallCommand($repository);
$command->setHypervel($app);
$repository->expects('setSource')->with('foo');
@@ -58,7 +58,7 @@ public function testSetSourceReceivesSwappedNameWhenMigrationsConnectionConfigur
],
]));
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$command = new InstallCommand($repository);
$command->setHypervel($app);
$repository->expects('setSource')->with('pgsql');
@@ -85,7 +85,7 @@ public function testSetSourceRoutesThroughDefaultWhenNoDatabaseOptionGiven(): vo
],
]));
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$command = new InstallCommand($repository);
$command->setHypervel($app);
$repository->expects('setSource')->with('pgsql');
@@ -120,7 +120,7 @@ public function testSetSourceHonorsContextOverrideWhenNoDatabaseOptionGiven(): v
CoroutineContext::set(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY, 'tenant-pooled');
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$command = new InstallCommand($repository);
$command->setHypervel($app);
$repository->expects('setSource')->with('tenant-direct');
diff --git a/tests/Database/DatabaseMigrationMakeCommandTest.php b/tests/Database/DatabaseMigrationMakeCommandTest.php
index 05b02d65fe..8f85ef1427 100755
--- a/tests/Database/DatabaseMigrationMakeCommandTest.php
+++ b/tests/Database/DatabaseMigrationMakeCommandTest.php
@@ -24,7 +24,7 @@ public function testBasicCreateGivesCreatorProperArguments(): void
{
$app = new ApplicationDatabaseMigrationMakeStub;
$app->useDatabasePath(__DIR__);
- $creator = Double::for(MigrationCreator::class);
+ $creator = Double::for(MigrationCreator::class)->strict();
$command = new MigrateMakeCommand($creator);
$command->setHypervel($app);
$creator->expects('create')
@@ -38,7 +38,7 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenNameIsStudlyCase()
{
$app = new ApplicationDatabaseMigrationMakeStub;
$app->useDatabasePath(__DIR__);
- $creator = Double::for(MigrationCreator::class);
+ $creator = Double::for(MigrationCreator::class)->strict();
$command = new MigrateMakeCommand($creator);
$command->setHypervel($app);
$creator->expects('create')
@@ -52,7 +52,7 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenTableIsSet(): void
{
$app = new ApplicationDatabaseMigrationMakeStub;
$app->useDatabasePath(__DIR__);
- $creator = Double::for(MigrationCreator::class);
+ $creator = Double::for(MigrationCreator::class)->strict();
$command = new MigrateMakeCommand($creator);
$command->setHypervel($app);
$creator->expects('create')
@@ -66,7 +66,7 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenCreateTablePattern
{
$app = new ApplicationDatabaseMigrationMakeStub;
$app->useDatabasePath(__DIR__);
- $creator = Double::for(MigrationCreator::class);
+ $creator = Double::for(MigrationCreator::class)->strict();
$command = new MigrateMakeCommand($creator);
$command->setHypervel($app);
$creator->expects('create')
@@ -79,7 +79,7 @@ public function testBasicCreateGivesCreatorProperArgumentsWhenCreateTablePattern
public function testCanSpecifyPathToCreateMigrationsIn(): void
{
$app = new ApplicationDatabaseMigrationMakeStub;
- $creator = Double::for(MigrationCreator::class);
+ $creator = Double::for(MigrationCreator::class)->strict();
$command = new MigrateMakeCommand($creator);
$command->setHypervel($app);
$app->setBasePath('/home/hypervel');
diff --git a/tests/Database/DatabaseMigrationMigrateCommandTest.php b/tests/Database/DatabaseMigrationMigrateCommandTest.php
index 2321ed706a..24bc230ea3 100755
--- a/tests/Database/DatabaseMigrationMigrateCommandTest.php
+++ b/tests/Database/DatabaseMigrationMigrateCommandTest.php
@@ -55,7 +55,7 @@ public function testBasicMigrationsCallMigratorWithProperArguments(): void
{
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$dispatcher = new EventsDispatcher;
$command = new MigrateCommand($migrator, $dispatcher);
$command->setHypervel($app);
@@ -71,17 +71,17 @@ public function testMigrationsCanBeRunWithStoredSchema(): void
{
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$dispatcher = new EventFake(new EventsDispatcher);
$command = new MigrateCommand($migrator, $dispatcher);
$command->setHypervel($app);
$this->expectMigrationPreflight($migrator);
$migrator->expects('hasRunAnyMigrations')->returns(false);
- $connection = Double::for(MySqlConnection::class);
+ $connection = Double::for(MySqlConnection::class)->strict();
$migrator->expects('resolveConnection')->returns($connection);
$connection->expects('getName')->returns('mysql');
$migrator->expects('deleteRepository');
- $schemaState = Double::for(MySqlSchemaState::class);
+ $schemaState = Double::for(MySqlSchemaState::class)->strict();
$connection->expects('getSchemaState')->returns($schemaState);
$schemaState->expects('handleOutputUsing')->returns($schemaState);
$schemaState->expects('load')->with(__DIR__ . '/Fixtures/schema.sql');
@@ -97,16 +97,16 @@ public function testStoredSchemaDoesNotDispatchWithoutListeners(): void
{
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $migrator = Double::for(Migrator::class);
- $dispatcher = Double::for(Dispatcher::class);
+ $migrator = Double::for(Migrator::class)->strict();
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$command = new MigrateCommand($migrator, $dispatcher);
$command->setHypervel($app);
$this->expectMigrationPreflight($migrator);
$migrator->expects('hasRunAnyMigrations')->returns(false);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$migrator->expects('resolveConnection')->returns($connection);
$migrator->expects('deleteRepository');
- $schemaState = Double::for(SchemaState::class);
+ $schemaState = Double::for(SchemaState::class)->strict();
$connection->expects('getSchemaState')->returns($schemaState);
$schemaState->expects('handleOutputUsing')->returns($schemaState);
$schemaState->expects('load')->with(__DIR__ . '/Fixtures/schema.sql');
@@ -122,7 +122,7 @@ public function testMigrationRepositoryCreatedWhenNecessary(): void
{
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$dispatcher = new EventsDispatcher;
$params = [$migrator, $dispatcher];
$command = $this->getMockBuilder(MigrateCommand::class)->onlyMethods(['callSilent'])->setConstructorArgs($params)->getMock();
@@ -140,7 +140,7 @@ public function testTheCommandMayBePretended(): void
{
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$dispatcher = new EventsDispatcher;
$command = new MigrateCommand($migrator, $dispatcher);
$command->setHypervel($app);
@@ -156,7 +156,7 @@ public function testTheDatabaseMayBeSet(): void
{
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$dispatcher = new EventsDispatcher;
$command = new MigrateCommand($migrator, $dispatcher);
$command->setHypervel($app);
@@ -172,7 +172,7 @@ public function testStepMayBeSet(): void
{
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$dispatcher = new EventsDispatcher;
$command = new MigrateCommand($migrator, $dispatcher);
$command->setHypervel($app);
@@ -189,7 +189,7 @@ public function testGracefulReturnsSuccessWhenRunMigrationsThrows(): void
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$command = $this->getMockBuilder(MigrateCommand::class)
->onlyMethods(['runMigrations'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict(), $dispatcher = Double::for(Dispatcher::class)->strict()])
->getMock();
$command->setHypervel($app);
$command->expects($this->once())->method('runMigrations')->willThrowException(new RuntimeException('boom'));
@@ -205,7 +205,7 @@ public function testSeedOptionRunsSeederAfterMigrations(): void
$app->useDatabasePath(__DIR__);
$command = $this->getMockBuilder(MigrateCommand::class)
->onlyMethods(['call'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict(), $dispatcher = Double::for(Dispatcher::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectMigrationPreflight($migrator);
@@ -228,7 +228,7 @@ public function testSeedFailureHonorsGracefulOption(bool $graceful): void
$app->useDatabasePath(__DIR__);
$command = $this->getMockBuilder(MigrateCommand::class)
->onlyMethods(['call'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class), Double::for(Dispatcher::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict(), Double::for(Dispatcher::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectMigrationPreflight($migrator);
@@ -263,7 +263,7 @@ public function testSeedOptionForwardsDatabaseToSeedCommand(): void
$app->useDatabasePath(__DIR__);
$command = $this->getMockBuilder(MigrateCommand::class)
->onlyMethods(['call'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict(), $dispatcher = Double::for(Dispatcher::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectMigrationPreflight($migrator, 'pgsql-pooled');
@@ -296,7 +296,7 @@ public function testMigrateWithSeedDoesNotLeakConnectionStateOrMutateConfig(): v
$command = $this->getMockBuilder(MigrateCommand::class)
->onlyMethods(['call'])
- ->setConstructorArgs([$migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class)])
+ ->setConstructorArgs([$migrator = Double::for(Migrator::class)->strict(), $dispatcher = Double::for(Dispatcher::class)->strict()])
->getMock();
$command->setHypervel($app);
$this->expectMigrationPreflight($migrator, 'pgsql-pooled');
@@ -333,7 +333,7 @@ public function testAllTargetsAreInspectedAndMissingSqliteDatabaseIsCreatedBefor
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $command = new MigrateCommand($migrator = Double::for(Migrator::class), $dispatcher = Double::for(Dispatcher::class));
+ $command = new MigrateCommand($migrator = Double::for(Migrator::class)->strict(), $dispatcher = Double::for(Dispatcher::class)->strict());
$command->setHypervel($app);
$paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations'];
$currentConnection = null;
@@ -446,16 +446,16 @@ public function testDecliningMissingDatabaseCreationCreatesNothing(): void
public function testMissingDatabaseClassifierRecognizesOnlySupportedSignals(): void
{
- $migrator = Double::for(Migrator::class);
- $mysqlConnection = Double::for(Connection::class);
+ $migrator = Double::for(Migrator::class)->strict();
+ $mysqlConnection = Double::for(Connection::class)->strict();
$mysqlConnection->allows('getDriverName')->returns('mysql');
- $postgresConnection = Double::for(Connection::class);
+ $postgresConnection = Double::for(Connection::class)->strict();
$postgresConnection->allows('getDriverName')->returns('pgsql');
$postgresConnection->allows('getDatabaseName')->returns('analytics');
$migrator->allows('resolveConnection')->resolves(
fn (string $name): Connection => $name === 'mysql' ? $mysqlConnection : $postgresConnection
);
- $command = new TestableMigrateCommand($migrator, Double::for(Dispatcher::class));
+ $command = new TestableMigrateCommand($migrator, Double::for(Dispatcher::class)->strict());
$sqliteCause = new SQLiteDatabaseDoesNotExistException('/missing.sqlite');
$mysqlCause = new PDOException('Unknown database', 1049);
@@ -496,7 +496,7 @@ public function testMySqlAdminCreationUsesResolvedWriteConfigurationAndQuotesThe
'write' => ['host' => 'write-host', 'database' => 'tenant.with`quote', 'prefix' => 'write_'],
Connection::READ_WRITE_TYPE_CONFIG_KEY => 'write',
], 'mysql');
- $command = new TestableMigrateCommand(Double::for(Migrator::class), Double::for(Dispatcher::class));
+ $command = new TestableMigrateCommand(Double::for(Migrator::class)->strict(), Double::for(Dispatcher::class)->strict());
$command->setHypervel($app);
$command->probeCreateMissingServerDatabase($connection);
@@ -535,7 +535,7 @@ public function testPostgresAdminCreationRemovesConnectViaDatabaseAndDisconnects
], 'pgsql');
$failure = new RuntimeException('create failed');
RecordingMigrationPostgresConnection::$unpreparedException = $failure;
- $command = new TestableMigrateCommand(Double::for(Migrator::class), Double::for(Dispatcher::class));
+ $command = new TestableMigrateCommand(Double::for(Migrator::class)->strict(), Double::for(Dispatcher::class)->strict());
$command->setHypervel($app);
$caught = null;
@@ -580,7 +580,7 @@ private function makeCommandWithMissingSqliteTarget(string $path): TestableMigra
{
$app = new ApplicationDatabaseMigrationStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $command = new TestableMigrateCommand($migrator = Double::for(Migrator::class), Double::for(Dispatcher::class));
+ $command = new TestableMigrateCommand($migrator = Double::for(Migrator::class)->strict(), Double::for(Dispatcher::class)->strict());
$command->setHypervel($app);
$paths = [__DIR__ . DIRECTORY_SEPARATOR . 'migrations'];
$migrator->expects('paths')->returns([]);
@@ -611,7 +611,7 @@ class ApplicationDatabaseMigrationStub extends Application
{
public function __construct(array $data = [])
{
- $mutex = Double::for(CommandMutex::class);
+ $mutex = Double::for(CommandMutex::class)->strict();
$mutex->allows('create')->returns(true);
$this->instance(CommandMutex::class, $mutex);
$this->instance('env', 'development');
diff --git a/tests/Database/DatabaseMigrationRefreshCommandTest.php b/tests/Database/DatabaseMigrationRefreshCommandTest.php
index e51b195efb..431ddcae22 100755
--- a/tests/Database/DatabaseMigrationRefreshCommandTest.php
+++ b/tests/Database/DatabaseMigrationRefreshCommandTest.php
@@ -31,14 +31,14 @@ public function testRefreshCommandCallsCommandsWithProperArguments(): void
$command = new RefreshCommand;
$app = new ApplicationDatabaseRefreshStub(['path.database' => __DIR__]);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$dispatcher = $app->instance(Dispatcher::class, $events);
$console = Double::for(new ConsoleApplication)->passthru();
$command->setHypervel($app);
$command->setApplication($console);
- $resetCommand = Double::for(ResetCommand::class);
- $migrateCommand = Double::for(MigrateCommand::class);
+ $resetCommand = Double::for(ResetCommand::class)->strict();
+ $migrateCommand = Double::for(MigrateCommand::class)->strict();
$console->expects('find')->with('migrate:reset')->returns($resetCommand);
$console->expects('find')->with('migrate')->returns($migrateCommand);
@@ -62,14 +62,14 @@ public function testRefreshCommandCallsCommandsWithStep(): void
$command = new RefreshCommand;
$app = new ApplicationDatabaseRefreshStub(['path.database' => __DIR__]);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$dispatcher = $app->instance(Dispatcher::class, $events);
$console = Double::for(new ConsoleApplication)->passthru();
$command->setHypervel($app);
$command->setApplication($console);
- $rollbackCommand = Double::for(RollbackCommand::class);
- $migrateCommand = Double::for(MigrateCommand::class);
+ $rollbackCommand = Double::for(RollbackCommand::class)->strict();
+ $migrateCommand = Double::for(MigrateCommand::class)->strict();
$console->expects('find')->with('migrate:rollback')->returns($rollbackCommand);
$console->expects('find')->with('migrate')->returns($migrateCommand);
@@ -92,7 +92,7 @@ public function testRefreshCommandCallsCommandsWithStep(): void
public function testChildFailureStopsRefresh(string $failedCommand, array $options, array $expectedOperations, string $message): void
{
$app = new ApplicationDatabaseRefreshStub(['path.database' => __DIR__]);
- $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class));
+ $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)->strict());
$dispatcher->allows('hasListeners')->returns(false);
$command = $this->getMockBuilder(RefreshCommand::class)->onlyMethods(['call'])->getMock();
$command->setHypervel($app);
@@ -148,8 +148,9 @@ public function testRefreshCommandExitsWhenProhibited(): void
$command = new RefreshCommand;
$app = new ApplicationDatabaseRefreshStub(['path.database' => __DIR__]);
- $events = Double::for(Dispatcher::class);
- $dispatcher = $app->instance(Dispatcher::class, $events);
+ $dispatcher = $app->instance(Dispatcher::class, Double::for(Dispatcher::class)->strict());
+ $dispatcher->allows('hasListeners')->resolves(static fn (string $event): bool => $event === DatabaseRefreshed::class);
+ $dispatcher->expects('dispatch')->never();
$console = Double::for(new ConsoleApplication)->passthru();
$command->setHypervel($app);
$command->setApplication($console);
@@ -161,7 +162,6 @@ public function testRefreshCommandExitsWhenProhibited(): void
$this->assertSame(1, $code);
$console->received('find')->never();
- $dispatcher->received('dispatch')->never();
}
/**
diff --git a/tests/Database/DatabaseMigrationRepositoryTest.php b/tests/Database/DatabaseMigrationRepositoryTest.php
index 12d2077b3a..b8925741b2 100755
--- a/tests/Database/DatabaseMigrationRepositoryTest.php
+++ b/tests/Database/DatabaseMigrationRepositoryTest.php
@@ -22,8 +22,8 @@ class DatabaseMigrationRepositoryTest extends TestCase
public function testGetRanMigrationsListMigrationsByPackage(): void
{
$repository = $this->getRepository();
- $query = Double::for(QueryBuilder::class);
- $connectionMock = Double::for(Connection::class);
+ $query = Double::for(QueryBuilder::class)->strict();
+ $connectionMock = Double::for(Connection::class)->strict();
$repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->returns($connectionMock);
$repository->getConnection()->expects('table')->with('migrations')->returns($query);
$query->expects('orderBy')->with('batch', 'asc')->returns($query);
@@ -36,13 +36,13 @@ public function testGetRanMigrationsListMigrationsByPackage(): void
public function testGetLastMigrationsGetsAllMigrationsWithTheLatestBatchNumber(): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$repository = $this->getMockBuilder(DatabaseMigrationRepository::class)->onlyMethods(['getLastBatchNumber'])->setConstructorArgs([
$resolver, 'migrations',
])->getMock();
$repository->expects($this->once())->method('getLastBatchNumber')->willReturn(1);
- $query = Double::for(QueryBuilder::class);
- $connectionMock = Double::for(Connection::class);
+ $query = Double::for(QueryBuilder::class)->strict();
+ $connectionMock = Double::for(Connection::class)->strict();
$repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->returns($connectionMock);
$repository->getConnection()->expects('table')->with('migrations')->returns($query);
$query->expects('where')->with('batch', 1)->returns($query);
@@ -56,8 +56,8 @@ public function testGetLastMigrationsGetsAllMigrationsWithTheLatestBatchNumber()
public function testLogMethodInsertsRecordIntoMigrationTable(): void
{
$repository = $this->getRepository();
- $query = Double::for(QueryBuilder::class);
- $connectionMock = Double::for(Connection::class);
+ $query = Double::for(QueryBuilder::class)->strict();
+ $connectionMock = Double::for(Connection::class)->strict();
$repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->returns($connectionMock);
$repository->getConnection()->expects('table')->with('migrations')->returns($query);
$query->expects('insert')->with(['migration' => 'bar', 'batch' => 1]);
@@ -69,8 +69,8 @@ public function testLogMethodInsertsRecordIntoMigrationTable(): void
public function testDeleteMethodRemovesAMigrationFromTheTable(): void
{
$repository = $this->getRepository();
- $query = Double::for(QueryBuilder::class);
- $connectionMock = Double::for(Connection::class);
+ $query = Double::for(QueryBuilder::class)->strict();
+ $connectionMock = Double::for(Connection::class)->strict();
$repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->returns($connectionMock);
$repository->getConnection()->expects('table')->with('migrations')->returns($query);
$query->expects('where')->with('migration', 'foo')->returns($query);
@@ -84,7 +84,7 @@ public function testDeleteMethodRemovesAMigrationFromTheTable(): void
public function testGetNextBatchNumberReturnsLastBatchNumberPlusOne(): void
{
$repository = $this->getMockBuilder(DatabaseMigrationRepository::class)->onlyMethods(['getLastBatchNumber'])->setConstructorArgs([
- Double::for(ConnectionResolverInterface::class), 'migrations',
+ Double::for(ConnectionResolverInterface::class)->strict(), 'migrations',
])->getMock();
$repository->expects($this->once())->method('getLastBatchNumber')->willReturn(1);
@@ -95,8 +95,8 @@ public function testGetNextBatchNumberReturnsLastBatchNumberPlusOne(): void
public function testGetLastBatchNumberReturnsMaxBatch(int|string|null $value, int $expected): void
{
$repository = $this->getRepository();
- $query = Double::for(QueryBuilder::class);
- $connectionMock = Double::for(Connection::class);
+ $query = Double::for(QueryBuilder::class)->strict();
+ $connectionMock = Double::for(Connection::class)->strict();
$repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->returns($connectionMock);
$repository->getConnection()->expects('table')->with('migrations')->returns($query);
$query->expects('max')->with('batch')->returns($value);
@@ -120,8 +120,8 @@ public static function batchNumberProvider(): array
public function testCreateRepositoryCreatesProperDatabaseTable(): void
{
$repository = $this->getRepository();
- $schema = Double::for(SchemaBuilder::class);
- $connectionMock = Double::for(Connection::class);
+ $schema = Double::for(SchemaBuilder::class)->strict();
+ $connectionMock = Double::for(Connection::class)->strict();
$repository->getConnectionResolver()->expects('connection')->times(2)->with(null)->returns($connectionMock);
$repository->getConnection()->expects('getSchemaBuilder')->returns($schema);
$schema->expects('createMigrationRepositoryTable')->with('migrations');
@@ -134,6 +134,6 @@ public function testCreateRepositoryCreatesProperDatabaseTable(): void
*/
protected function getRepository(): DatabaseMigrationRepository
{
- return new DatabaseMigrationRepository(Double::for(ConnectionResolverInterface::class), 'migrations');
+ return new DatabaseMigrationRepository(Double::for(ConnectionResolverInterface::class)->strict(), 'migrations');
}
}
diff --git a/tests/Database/DatabaseMigrationResetCommandTest.php b/tests/Database/DatabaseMigrationResetCommandTest.php
index 5420bfdbf8..4187b96c53 100755
--- a/tests/Database/DatabaseMigrationResetCommandTest.php
+++ b/tests/Database/DatabaseMigrationResetCommandTest.php
@@ -22,7 +22,7 @@ class DatabaseMigrationResetCommandTest extends TestCase
public function testResetCommandCallsMigratorWithProperArguments(): void
{
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$command = new ResetCommand($migrator);
$app = new ApplicationDatabaseResetStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
@@ -40,7 +40,7 @@ public function testResetCommandCallsMigratorWithProperArguments(): void
public function testResetCommandCanBePretended(): void
{
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$command = new ResetCommand($migrator);
$app = new ApplicationDatabaseResetStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
@@ -58,7 +58,7 @@ public function testResetCommandCanBePretended(): void
public function testResetCommandExitsWhenProhibited(): void
{
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$command = new ResetCommand($migrator);
$app = new ApplicationDatabaseResetStub(['path.database' => __DIR__]);
diff --git a/tests/Database/DatabaseMigrationRollbackCommandTest.php b/tests/Database/DatabaseMigrationRollbackCommandTest.php
index b3ed9f0a3f..d1103288f1 100755
--- a/tests/Database/DatabaseMigrationRollbackCommandTest.php
+++ b/tests/Database/DatabaseMigrationRollbackCommandTest.php
@@ -20,7 +20,7 @@ class DatabaseMigrationRollbackCommandTest extends TestCase
public function testRollbackCommandCallsMigratorWithProperArguments(): void
{
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$command = new RollbackCommand($migrator);
$app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
@@ -37,7 +37,7 @@ public function testRollbackCommandCallsMigratorWithProperArguments(): void
public function testRollbackCommandCallsMigratorWithStepOption(): void
{
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$command = new RollbackCommand($migrator);
$app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
@@ -54,7 +54,7 @@ public function testRollbackCommandCallsMigratorWithStepOption(): void
public function testRollbackCommandCanBePretended(): void
{
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$command = new RollbackCommand($migrator);
$app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
@@ -71,7 +71,7 @@ public function testRollbackCommandCanBePretended(): void
public function testRollbackCommandCanBePretendedWithStepOption(): void
{
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$command = new RollbackCommand($migrator);
$app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
@@ -88,7 +88,7 @@ public function testRollbackCommandCanBePretendedWithStepOption(): void
public function testRollbackCommandCallsMigratorWithBatchOption(): void
{
- $migrator = Double::for(Migrator::class);
+ $migrator = Double::for(Migrator::class)->strict();
$command = new RollbackCommand($migrator);
$app = new ApplicationDatabaseRollbackStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
diff --git a/tests/Database/DatabaseMigrationStatusCommandTest.php b/tests/Database/DatabaseMigrationStatusCommandTest.php
index 87d877a66a..0a370f4bd2 100644
--- a/tests/Database/DatabaseMigrationStatusCommandTest.php
+++ b/tests/Database/DatabaseMigrationStatusCommandTest.php
@@ -22,9 +22,9 @@ public function testPendingOptionReturnsConfiguredExitCodeAsInteger(): void
{
$app = new ApplicationDatabaseStatusStub(['path.database' => __DIR__]);
$app->useDatabasePath(__DIR__);
- $command = new StatusCommand($migrator = Double::for(Migrator::class));
+ $command = new StatusCommand($migrator = Double::for(Migrator::class)->strict());
$command->setHypervel($app);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$migrator->expects('usingConnection')->resolves(function ($name, $callback) {
return $callback();
});
diff --git a/tests/Database/DatabaseMigratorIntegrationTest.php b/tests/Database/DatabaseMigratorIntegrationTest.php
index e6444726f5..1174d8dece 100644
--- a/tests/Database/DatabaseMigratorIntegrationTest.php
+++ b/tests/Database/DatabaseMigratorIntegrationTest.php
@@ -59,7 +59,7 @@ protected function setUpInCoroutine(): void
new Filesystem
);
- $output = Double::for(OutputStyle::class);
+ $output = Double::for(OutputStyle::class)->strict();
$output->allows('write');
$output->allows('writeln');
$output->allows('newLinesWritten');
diff --git a/tests/Database/DatabaseMigratorTest.php b/tests/Database/DatabaseMigratorTest.php
index 874db5202d..3d2ff7526f 100644
--- a/tests/Database/DatabaseMigratorTest.php
+++ b/tests/Database/DatabaseMigratorTest.php
@@ -85,9 +85,9 @@ public function testSetConnectionNullPreservesDefaultConnectionBehaviorWithoutDi
public function testRunMethodPreservesWriteConnectionName(): void
{
CoroutineContext::set(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY, 'pgsql');
- $resolver = Double::for(Resolver::class);
+ $resolver = Double::for(Resolver::class)->strict();
$migrator = $this->migrator($resolver);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getNameWithReadWriteType')->returns('pgsql::write');
$migration = new class($this) {
@@ -350,8 +350,8 @@ public function testSetConnectionWritesContextRepositorySourceAndStoredName(): v
'pgsql' => ['driver' => 'pgsql'],
]);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->with('pgsql');
@@ -370,8 +370,8 @@ public function testSetConnectionRejectsNullWithoutAnEffectiveDefault(): void
{
$this->bindConfig([]);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->never();
$migrator = new Migrator($repository, $resolver, new Filesystem);
@@ -388,8 +388,8 @@ public function testSetConnectionDoesNotSwapWhenNoMigrationsConnectionKey(): voi
'pgsql' => ['driver' => 'pgsql'],
]);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->with('pgsql');
@@ -410,9 +410,9 @@ public function testResolveConnectionUsesStoredConnectionWhenArgumentIsNullOrEmp
'pgsql' => ['driver' => 'pgsql'],
]);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
- $resolvedConnection = Double::for(Connection::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
+ $resolvedConnection = Double::for(Connection::class)->strict();
$repository->expects('setSource')->with('pgsql');
$resolver->expects('connection')->times(2)->with('pgsql')->returns($resolvedConnection);
@@ -434,9 +434,9 @@ public function testResolveConnectionPreservesExplicitZeroConnection(): void
default: 'pgsql',
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
- $resolvedConnection = Double::for(Connection::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
+ $resolvedConnection = Double::for(Connection::class)->strict();
$resolver->expects('connection')->with('0')->returns($resolvedConnection);
@@ -455,9 +455,9 @@ public function testResolveConnectionSwapsPerMigrationConnectionOverride(): void
'pgsql' => ['driver' => 'pgsql'],
]);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
- $resolvedConnection = Double::for(Connection::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
+ $resolvedConnection = Double::for(Connection::class)->strict();
$resolver->expects('connection')->with('pgsql')->returns($resolvedConnection);
@@ -473,9 +473,9 @@ public function testResolveConnectionPassesSwappedNameToCustomCallback(): void
'pgsql' => ['driver' => 'pgsql'],
]);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
- $resolvedConnection = Double::for(Connection::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
+ $resolvedConnection = Double::for(Connection::class)->strict();
$capturedName = null;
Migrator::resolveConnectionsUsing(function (Resolver $r, ?string $name) use (&$capturedName, $resolvedConnection) {
@@ -503,8 +503,8 @@ public function testSetConnectionWithNullAndPooledDefaultRoutesToDirect(): void
default: 'pgsql-pooled',
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->with('pgsql');
$migrator = new Migrator($repository, $resolver, new Filesystem);
@@ -531,9 +531,9 @@ public function testResolveConnectionWithNullAndPooledDefaultRoutesToDirect(): v
default: 'pgsql-pooled',
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
- $resolvedConnection = Double::for(Connection::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
+ $resolvedConnection = Double::for(Connection::class)->strict();
$resolver->expects('connection')->with('pgsql')->returns($resolvedConnection);
@@ -555,8 +555,8 @@ public function testUsingConnectionRestoresDistinctStoredAndContextState(): void
default: 'stored',
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->times(2)->with('stored');
$repository->expects('setSource')->with('inner-direct');
@@ -593,8 +593,8 @@ public function testUsingConnectionRestoresDistinctStoredAndContextStateAfterAnE
default: 'stored',
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->times(2)->with('stored');
$repository->expects('setSource')->with('inner-direct');
@@ -630,8 +630,8 @@ public function testUsingConnectionWithNullAndPooledDefaultRoutesAndRestores():
default: 'pgsql-pooled',
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->with('pgsql');
$repository->expects('setSource')->with(null);
@@ -669,8 +669,8 @@ public function testGetMigrationConnectionsDiscoversNamedAnonymousAndContextDecl
default: 'default-pooled',
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->with('default-direct');
$repository->expects('setSource')->with(null);
$migrator = new Migrator($repository, $resolver, new Filesystem);
@@ -698,8 +698,8 @@ public function testGetMigrationConnectionsIncludesTheDefaultWithoutMigrationFil
default: 'default-pooled',
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
$repository->expects('setSource')->with('default-direct');
$repository->expects('setSource')->with(null);
$migrator = new Migrator($repository, $resolver, new Filesystem);
@@ -727,8 +727,8 @@ public function testNestedUsingConnectionPreservesEachLevelsState(): void
default: null,
);
- $resolver = Double::for(Resolver::class);
- $repository = Double::for(MigrationRepositoryInterface::class);
+ $resolver = Double::for(Resolver::class)->strict();
+ $repository = Double::for(MigrationRepositoryInterface::class)->strict();
// Outer enter: setSource('pgsql'). Inner enter: setSource('mysql').
// Inner exit: setSource back to 'pgsql' (outer's stored). Outer exit:
diff --git a/tests/Database/DatabaseMonitorCommandTest.php b/tests/Database/DatabaseMonitorCommandTest.php
index 77fac89a7c..6e471d6f17 100644
--- a/tests/Database/DatabaseMonitorCommandTest.php
+++ b/tests/Database/DatabaseMonitorCommandTest.php
@@ -26,9 +26,9 @@ public function testMonitorCommandFailsWhenDatabaseDefaultIsMissing(): void
{
$this->app->instance('config', new Repository(['database' => []]));
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
- $command = new MonitorCommand($resolver, Double::for(Dispatcher::class));
+ $command = new MonitorCommand($resolver, Double::for(Dispatcher::class)->strict());
$command->setHypervel($this->app);
$this->expectException(InvalidArgumentException::class);
@@ -39,13 +39,13 @@ public function testMonitorCommandFailsWhenDatabaseDefaultIsMissing(): void
public function testMonitorCommandPreservesConnectionNameZero(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('threadCount')->returns(1);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with('0')->returns($connection);
- $command = new MonitorCommand($resolver, Double::for(Dispatcher::class));
+ $command = new MonitorCommand($resolver, Double::for(Dispatcher::class)->strict());
$command->setHypervel($this->app);
$this->assertSame(0, $command->run(new ArrayInput(['--databases' => '0']), new NullOutput));
@@ -53,11 +53,11 @@ public function testMonitorCommandPreservesConnectionNameZero(): void
public function testBusyEventIsNotDispatchedWithoutListeners(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('threadCount')->returns(2);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with('primary')->returns($connection);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(DatabaseBusy::class)->returns(false);
$events->expects('dispatch')->never();
$command = new MonitorCommand($resolver, $events);
@@ -71,11 +71,11 @@ public function testBusyEventIsNotDispatchedWithoutListeners(): void
public function testBusyEventIsDispatchedWithAListener(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('threadCount')->returns(2);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with('primary')->returns($connection);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(DatabaseBusy::class)->returns(true);
$events->expects('dispatch')->with(Argument::satisfies(
static fn (DatabaseBusy $event): bool => $event->connectionName === 'primary'
diff --git a/tests/Database/DatabaseMySQLSchemaBuilderTest.php b/tests/Database/DatabaseMySQLSchemaBuilderTest.php
index 1f9076b8d7..b9f5f10e2b 100755
--- a/tests/Database/DatabaseMySQLSchemaBuilderTest.php
+++ b/tests/Database/DatabaseMySQLSchemaBuilderTest.php
@@ -18,7 +18,7 @@ class DatabaseMySQLSchemaBuilderTest extends TestCase
public function testHasTable(): void
{
- $connection = Double::for(MySqlConnection::class);
+ $connection = Double::for(MySqlConnection::class)->strict();
$connection->allows('usesBackslashEscapes')->returns(true);
$grammar = new MySqlGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -31,7 +31,7 @@ public function testHasTable(): void
public function testGetColumnListing(): void
{
- $connection = Double::for(MySqlConnection::class);
+ $connection = Double::for(MySqlConnection::class)->strict();
$connection->allows('usesBackslashEscapes')->returns(true);
$grammar = new MySqlGrammar($connection);
$processor = new MySqlProcessor;
diff --git a/tests/Database/DatabaseMySqlBuilderTest.php b/tests/Database/DatabaseMySqlBuilderTest.php
index 55a418df87..f92cb59a7f 100644
--- a/tests/Database/DatabaseMySqlBuilderTest.php
+++ b/tests/Database/DatabaseMySqlBuilderTest.php
@@ -21,7 +21,7 @@ class DatabaseMySqlBuilderTest extends TestCase
public function testCreateDatabase(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new MySqlGrammarSchema($connection);
$connection->expects('getConfig')->with('charset')->returns('utf8mb4');
@@ -37,7 +37,7 @@ public function testCreateDatabase(): void
public function testDropDatabaseIfExists(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new MySqlGrammarSchema($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -52,7 +52,7 @@ public function testDropDatabaseIfExists(): void
public function testDeleteWithJoinCompilesOrderByAndLimit(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$processor = new Processor;
$grammar = new MySqlGrammar($connection);
@@ -75,7 +75,7 @@ public function testDeleteWithJoinCompilesOrderByAndLimit(): void
public function testDropAllTablesPreservesEnabledForeignKeyConstraints(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new MySqlGrammarSchema($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -98,7 +98,7 @@ public function testDropAllTablesPreservesEnabledForeignKeyConstraints(): void
public function testDropAllTablesPreservesDisabledForeignKeyConstraints(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new MySqlGrammarSchema($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -119,7 +119,7 @@ public function testDropAllTablesPreservesDisabledForeignKeyConstraints(): void
public function testDropAllTablesPropagatesAFalseStatementResultAfterRestoringConstraints(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new MySqlGrammarSchema($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -143,7 +143,7 @@ public function testDropAllTablesPropagatesAFalseStatementResultAfterRestoringCo
public function testDropAllViewsPropagatesAFalseStatementResult(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new MySqlGrammarSchema($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
diff --git a/tests/Database/DatabaseMySqlQueryGrammarTest.php b/tests/Database/DatabaseMySqlQueryGrammarTest.php
index 8f7598a13d..3c023fa66b 100755
--- a/tests/Database/DatabaseMySqlQueryGrammarTest.php
+++ b/tests/Database/DatabaseMySqlQueryGrammarTest.php
@@ -26,7 +26,7 @@ class DatabaseMySqlQueryGrammarTest extends TestCase
#[DataProvider('jsonPathEscapingProvider')]
public function testJsonPathsEscapeKeysUsingTheConfiguredSqlMode(array $modes, string $path): void
{
- $connection = new MySqlConnection(Double::for(PDO::class), config: ['modes' => $modes]);
+ $connection = new MySqlConnection(Double::for(PDO::class)->strict(), config: ['modes' => $modes]);
$builder = $connection->table('users')->select('options->App\Models\User->a"b[0]');
$this->assertSame("select json_unquote(json_extract(`options`, {$path})) from `users`", $builder->toSql());
@@ -57,13 +57,13 @@ public function testUpdateBindingsRejectUnencodableArrays(): void
{
$this->expectException(JsonException::class);
- (new MySqlGrammar(Double::for(Connection::class)))
+ (new MySqlGrammar(Double::for(Connection::class)->strict()))
->prepareBindingsForUpdate([], ['payload' => [NAN]]);
}
public function testToRawSql(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('escape')->with('foo', false)->returns("'foo'");
$grammar = new MySqlGrammar($connection);
@@ -158,7 +158,7 @@ public function testTimeoutDecoratesExistsAndLockingStatementsAtTheRoot(): void
#[DataProvider('nestedUnionVersions')]
public function testNestedUnionMembersUseTheSupportedServerSyntax(string $connectionClass, string $version, bool $wrapped): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->allows('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns($version);
$connection = new $connectionClass($pdo, 'database');
$member = $connection->table('posts')->select('id')->where('id', '<=', 3)
@@ -193,7 +193,7 @@ public static function nestedUnionVersions(): iterable
public function testOrdinaryUnionMembersDoNotInspectTheServerVersion(): void
{
- $connection = Double::for(MySqlConnection::class);
+ $connection = Double::for(MySqlConnection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$connection->expects('getServerVersion')->never();
$connection->expects('isMaria')->never();
diff --git a/tests/Database/DatabaseMySqlSchemaGrammarTest.php b/tests/Database/DatabaseMySqlSchemaGrammarTest.php
index a90134f4cc..7c16661316 100755
--- a/tests/Database/DatabaseMySqlSchemaGrammarTest.php
+++ b/tests/Database/DatabaseMySqlSchemaGrammarTest.php
@@ -885,7 +885,7 @@ public function testAddingEnum(): void
#[DataProvider('escapedSchemaLiteralsProvider')]
public function testSchemaLiteralsUseTheConfiguredSqlMode(array $modes, string $literal, string $path): void
{
- $connection = new MySqlConnection(Double::for(PDO::class), config: ['modes' => $modes]);
+ $connection = new MySqlConnection(Double::for(PDO::class)->strict(), config: ['modes' => $modes]);
$connection->useDefaultSchemaGrammar();
$blueprint = new Blueprint($connection, 'users');
$value = "O'Brien\\User";
@@ -954,7 +954,6 @@ public function testAddingJsonb(): void
public function testAddingDate(): void
{
$conn = $this->getConnection();
- $conn->expects('isMaria')->returns(false);
$conn->expects('getServerVersion')->returns('8.0.13');
$blueprint = new Blueprint($conn, 'users');
@@ -968,7 +967,6 @@ public function testAddingDate(): void
public function testAddingDateWithDefaultCurrent(): void
{
$conn = $this->getConnection();
- $conn->expects('isMaria')->returns(false);
$conn->expects('getServerVersion')->returns('8.0.13');
$blueprint = new Blueprint($conn, 'users');
@@ -982,7 +980,6 @@ public function testAddingDateWithDefaultCurrent(): void
public function testAddingDateWithDefaultCurrentOn57(): void
{
$conn = $this->getConnection();
- $conn->expects('isMaria')->returns(false);
$conn->expects('getServerVersion')->returns('5.7');
$blueprint = new Blueprint($conn, 'users');
@@ -996,7 +993,6 @@ public function testAddingDateWithDefaultCurrentOn57(): void
public function testAddingYear(): void
{
$conn = $this->getConnection();
- $conn->expects('isMaria')->returns(false);
$conn->expects('getServerVersion')->returns('8.0.13');
$blueprint = new Blueprint($conn, 'users');
@@ -1009,7 +1005,6 @@ public function testAddingYear(): void
public function testAddingYearWithDefaultCurrent(): void
{
$conn = $this->getConnection();
- $conn->expects('isMaria')->returns(false);
$conn->expects('getServerVersion')->returns('8.0.13');
$blueprint = new Blueprint($conn, 'users');
@@ -1023,7 +1018,6 @@ public function testAddingYearWithDefaultCurrent(): void
public function testAddingYearWithDefaultCurrentOn57(): void
{
$conn = $this->getConnection();
- $conn->expects('isMaria')->returns(false);
$conn->expects('getServerVersion')->returns('5.7');
$blueprint = new Blueprint($conn, 'users');
@@ -1683,7 +1677,8 @@ protected function getConnection(
?MySqlBuilder $builder = null,
string $prefix = ''
): Connection&DoubleInterface {
- $connection = Double::for(MySqlConnection::class);
+ $connection = Double::for(MySqlConnection::class)->strict();
+ $connection->allows('isMaria')->returns(false);
$connection->allows('usesBackslashEscapes')->returns(true);
$connection->allows('getTablePrefix')->returns($prefix);
$connection->allows('getConfig')->with('prefix_indexes')->returns(null);
@@ -1996,6 +1991,6 @@ public function getGrammar(?Connection $connection = null): MySqlGrammar
*/
public function getBuilder(): MySqlBuilder
{
- return Double::for(MySqlBuilder::class);
+ return Double::for(MySqlBuilder::class)->strict();
}
}
diff --git a/tests/Database/DatabasePdoConnectionTest.php b/tests/Database/DatabasePdoConnectionTest.php
index 90ab26ebe5..15eabc2d07 100755
--- a/tests/Database/DatabasePdoConnectionTest.php
+++ b/tests/Database/DatabasePdoConnectionTest.php
@@ -364,7 +364,7 @@ public function testStatementPreparedIsDispatchedFromThePdoPreparationPath(): vo
$statement->expects($this->once())->method('execute')->willReturn(true);
$statement->expects($this->once())->method('fetchAll')->willReturn([]);
$connection = $this->getMockConnection([], $pdo);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(StatementPrepared::class)->returns(true);
$events->expects('hasListeners')->with(QueryExecuted::class)->returns(false);
$events->expects('dispatch')
@@ -396,7 +396,7 @@ protected function event(object $event): void
parent::event($event);
}
};
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(StatementPrepared::class)->returns(false);
$events->expects('hasListeners')->with(QueryExecuted::class)->returns(false);
$events->expects('dispatch')->never();
@@ -412,7 +412,7 @@ public function testStatementListenerWarningsDoNotReconnectTheDatabase(): void
$connection = new SQLiteConnection($pdo);
$failure = new ErrorException('fopen(missing): Failed to open stream: No such file or directory', 0, E_WARNING);
$connection->setReconnector(static fn (): never => throw new LogicException('Unexpected reconnect.'));
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->with(StatementPrepared::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(StatementPrepared::class))->throws($failure);
$events->allows('hasListeners')->returns(false);
@@ -814,9 +814,9 @@ public function testOnLostConnectionPDOIsNotSwappedWithinATransaction(): void
$this->expectException(QueryException::class);
$this->expectExceptionMessageIs('server has gone away (Connection: test, Host: , Port: , Database: , SQL: foo)');
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->expects('beginTransaction')->returns(true);
- $statement = Double::for(PDOStatement::class);
+ $statement = Double::for(PDOStatement::class)->strict();
$pdo->expects('prepare')->returns($statement);
$statement->expects('execute')->throws(new PDOException('server has gone away'));
@@ -864,13 +864,13 @@ public function testQueryExceptionMasksBindingsWhenEnabledOnTheConnection(): voi
*/
protected function getFailingPdo(): PDO
{
- $statement = Double::for(PDOStatement::class);
+ $statement = Double::for(PDOStatement::class)->strict();
$statement->expects('bindValue')->returns(true);
$statement->expects('execute')->throws(
new PDOException('SQLSTATE[42S02]: Base table or view not found')
);
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->expects('prepare')->returns($statement);
return $pdo;
@@ -878,9 +878,9 @@ protected function getFailingPdo(): PDO
public function testOnLostConnectionPDOIsSwappedOutsideTransaction(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
- $statement = Double::for(PDOStatement::class);
+ $statement = Double::for(PDOStatement::class)->strict();
$executions = 0;
$statement->expects('execute')->times(2)->resolves(function () use (&$executions): bool {
if ($executions++ === 0) {
@@ -907,12 +907,12 @@ public function testOnLostConnectionPDOIsSwappedOutsideTransaction(): void
public function testQueriesRunWhileReconnectingDoNotReconnectAgain(): void
{
- $statement = Double::for(PDOStatement::class);
+ $statement = Double::for(PDOStatement::class)->strict();
$statement->expects('execute')->times(2)->throws(
new PDOException('SQLSTATE[08006] [7] connection to server at "127.0.0.1", port 5432 failed: Connection refused')
);
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->expects('prepare')->times(2)->returns($statement);
$connection = new PdoConnection($pdo);
@@ -1068,7 +1068,7 @@ public function testLostConnectionDuringCommitDiscardsPdoSoTheNextTransactionRec
public function testLostTransactionCleanupPreservesAConnectionOpenedByARollbackCallback(string $operation): void
{
$failure = new PDOException('server has gone away');
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->expects('beginTransaction')->returns(true);
$pdo->expects('prepare')->never();
@@ -1507,7 +1507,7 @@ public function testDisconnectReleasesEveryPdoWhenReleasingThemRaisesWarnings():
public function testLostConnectionIsRetriedWhenReleasingADeadReadPdoRaisesAWarning(): void
{
- $statement = Double::for(PDOStatement::class);
+ $statement = Double::for(PDOStatement::class)->strict();
$executions = 0;
$statement->expects('execute')->times(2)->resolves(function () use (&$executions): bool {
if ($executions++ === 0) {
@@ -1517,7 +1517,7 @@ public function testLostConnectionIsRetriedWhenReleasingADeadReadPdoRaisesAWarni
return true;
});
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->expects('prepare')->times(2)->returns($statement);
$pdo->expects('inTransaction')->returns(false);
@@ -1849,7 +1849,7 @@ protected function getMockConnection($methods = [], $pdo = null)
if ($methods === []) {
$connection = new PdoConnection($pdo, 'test_db', '', ['name' => 'test', 'driver' => 'mysql']);
- $connection->setSchemaGrammar(Double::for(SchemaGrammar::class));
+ $connection->setSchemaGrammar(Double::for(SchemaGrammar::class)->strict());
$connection->enableQueryLog();
return $connection;
@@ -1857,7 +1857,7 @@ protected function getMockConnection($methods = [], $pdo = null)
$defaults = ['getDefaultQueryGrammar', 'getDefaultPostProcessor', 'getDefaultSchemaGrammar'];
$connection = $this->getMockBuilder(PdoConnection::class)->onlyMethods(array_values(array_unique(array_merge($defaults, $methods))))->setConstructorArgs([$pdo, 'test_db', '', ['name' => 'test', 'driver' => 'mysql']])->getMock();
- $connection->method('getDefaultSchemaGrammar')->willReturn(Double::for(SchemaGrammar::class));
+ $connection->method('getDefaultSchemaGrammar')->willReturn(Double::for(SchemaGrammar::class)->strict());
$connection->enableQueryLog();
return $connection;
diff --git a/tests/Database/DatabasePostgresBuilderTest.php b/tests/Database/DatabasePostgresBuilderTest.php
index d1c1d2414d..7a224567eb 100644
--- a/tests/Database/DatabasePostgresBuilderTest.php
+++ b/tests/Database/DatabasePostgresBuilderTest.php
@@ -25,7 +25,7 @@ class DatabasePostgresBuilderTest extends TestCase
public function testCreateDatabase(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$connection->expects('getConfig')->with('charset')->returns('utf8');
@@ -40,7 +40,7 @@ public function testCreateDatabase(): void
public function testDropDatabaseIfExists(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -55,7 +55,7 @@ public function testDropDatabaseIfExists(): void
public function testExecuteBlueprintWrapsKnownMultiStatementCommandsInATransaction(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$blueprint = $this->executionBlueprint(
['first statement', 'second statement'],
@@ -74,7 +74,7 @@ public function testExecuteBlueprintWrapsKnownMultiStatementCommandsInATransacti
public function testExecuteBlueprintDoesNotNestAnExistingTransaction(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$blueprint = $this->executionBlueprint(
['first statement', 'second statement'],
@@ -92,7 +92,7 @@ public function testExecuteBlueprintDoesNotNestAnExistingTransaction(): void
public function testExecuteBlueprintDoesNotWrapASingleStatement(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$blueprint = $this->executionBlueprint(
['statement'],
@@ -109,7 +109,7 @@ public function testExecuteBlueprintDoesNotWrapASingleStatement(): void
public function testExecuteBlueprintDoesNotWrapOnlineCommands(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$blueprint = $this->executionBlueprint(
['create index concurrently', 'attach constraint'],
@@ -127,7 +127,7 @@ public function testExecuteBlueprintDoesNotWrapOnlineCommands(): void
public function testExecuteBlueprintDoesNotWrapCommandsAddedByAnExtensionGrammar(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$blueprint = $this->executionBlueprint(
['extension statement one', 'extension statement two'],
@@ -145,7 +145,7 @@ public function testExecuteBlueprintDoesNotWrapCommandsAddedByAnExtensionGrammar
public function testExecuteBlueprintWrapsFrameworkCommandsOverriddenByAnExtensionGrammar(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresBuilderExtensionGrammar($connection);
$blueprint = $this->executionBlueprint(
['overridden create', 'second statement'],
@@ -164,7 +164,7 @@ public function testExecuteBlueprintWrapsFrameworkCommandsOverriddenByAnExtensio
public function testExecuteBlueprintHonorsTheRuntimeGrammarTransactionFlag(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = Double::for(new PostgresGrammar($connection))->passthru();
$blueprint = $this->executionBlueprint(
['first statement', 'second statement'],
@@ -184,7 +184,7 @@ public function testExecuteBlueprintHonorsTheRuntimeGrammarTransactionFlag(): vo
public function testHasTableWhenSchemaUnqualifiedAndSearchPathMissing(): void
{
$connection = $this->getConnection();
- $grammar = Double::for(PostgresGrammar::class);
+ $grammar = Double::for(PostgresGrammar::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$grammar->expects('compileTableExists')->times(2)->returns('sql');
$connection->expects('selectFromWriteConnection')->times(2)->with('sql')->returns([['exists' => 1]]);
@@ -198,7 +198,7 @@ public function testHasTableWhenSchemaUnqualifiedAndSearchPathMissing(): void
public function testHasTableWhenSchemaUnqualifiedAndSearchPathFilled(): void
{
$connection = $this->getConnection();
- $grammar = Double::for(PostgresGrammar::class);
+ $grammar = Double::for(PostgresGrammar::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$grammar->expects('compileTableExists')->times(2)->returns('sql');
$connection->expects('selectFromWriteConnection')->times(2)->with('sql')->returns([['exists' => 1]]);
@@ -212,7 +212,7 @@ public function testHasTableWhenSchemaUnqualifiedAndSearchPathFilled(): void
public function testHasTableWhenSchemaUnqualifiedAndSearchPathFallbackFilled(): void
{
$connection = $this->getConnection();
- $grammar = Double::for(PostgresGrammar::class);
+ $grammar = Double::for(PostgresGrammar::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$grammar->expects('compileTableExists')->times(2)->returns('sql');
$connection->expects('selectFromWriteConnection')->times(2)->with('sql')->returns([['exists' => 1]]);
@@ -226,7 +226,7 @@ public function testHasTableWhenSchemaUnqualifiedAndSearchPathFallbackFilled():
public function testHasTableWhenSchemaUnqualifiedAndSearchPathIsUserVariable(): void
{
$connection = $this->getConnection();
- $grammar = Double::for(PostgresGrammar::class);
+ $grammar = Double::for(PostgresGrammar::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$grammar->expects('compileTableExists')->times(2)->returns('sql');
$connection->expects('selectFromWriteConnection')->times(2)->with('sql')->returns([['exists' => 1]]);
@@ -269,7 +269,7 @@ public function testGetColumnListingWhenSchemaUnqualifiedAndSearchPathMissing():
$connection->expects('getSchemaGrammar')->returns($grammar);
$connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->returns([['name' => 'some_column']]);
$connection->expects('getTablePrefix');
- $processor = Double::for(PostgresProcessor::class);
+ $processor = Double::for(PostgresProcessor::class)->strict();
$connection->expects('getPostProcessor')->returns($processor);
$processor->expects('processColumns')->returns([['name' => 'some_column']]);
$builder = $this->getBuilder($connection);
@@ -285,7 +285,7 @@ public function testGetColumnListingWhenSchemaUnqualifiedAndSearchPathFilled():
$connection->expects('getSchemaGrammar')->returns($grammar);
$connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->returns([['name' => 'some_column']]);
$connection->expects('getTablePrefix');
- $processor = Double::for(PostgresProcessor::class);
+ $processor = Double::for(PostgresProcessor::class)->strict();
$connection->expects('getPostProcessor')->returns($processor);
$processor->expects('processColumns')->returns([['name' => 'some_column']]);
$builder = $this->getBuilder($connection);
@@ -301,7 +301,7 @@ public function testGetColumnListingWhenSchemaUnqualifiedAndSearchPathIsUserVari
$connection->expects('getSchemaGrammar')->returns($grammar);
$connection->expects('selectFromWriteConnection')->with($grammar->compileColumns(null, 'foo'))->returns([['name' => 'some_column']]);
$connection->expects('getTablePrefix');
- $processor = Double::for(PostgresProcessor::class);
+ $processor = Double::for(PostgresProcessor::class)->strict();
$connection->expects('getPostProcessor')->returns($processor);
$processor->expects('processColumns')->returns([['name' => 'some_column']]);
$builder = $this->getBuilder($connection);
@@ -317,7 +317,7 @@ public function testGetColumnListingWhenSchemaQualifiedAndSearchPathMismatches()
$connection->expects('getSchemaGrammar')->returns($grammar);
$connection->expects('selectFromWriteConnection')->with($grammar->compileColumns('myapp', 'foo'))->returns([['name' => 'some_column']]);
$connection->expects('getTablePrefix');
- $processor = Double::for(PostgresProcessor::class);
+ $processor = Double::for(PostgresProcessor::class)->strict();
$connection->expects('getPostProcessor')->returns($processor);
$processor->expects('processColumns')->returns([['name' => 'some_column']]);
$builder = $this->getBuilder($connection);
@@ -342,7 +342,7 @@ public function testCurrentSchemaNameQueriesTheConnectionRatherThanConfiguredSea
$connection = $this->getConnection();
$connection->expects('getConfig')->with('username')->returns('foouser');
$connection->expects('getConfig')->with('search_path')->returns('"$user", public');
- $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class));
+ $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)->strict());
$connection->expects('scalar')
->with('select current_schema()', [], false)
->returns('public');
@@ -357,7 +357,7 @@ public function testCurrentSchemaNameQueriesTheConnectionRatherThanConfiguredSea
public function testCurrentSchemaListingFollowsTheConnectorSettingPrecedence(?string $searchPath, ?string $schema, array $expected): void
{
$connection = $this->getConnection();
- $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class));
+ $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)->strict());
$connection->allows('getConfig')->with('search_path')->returns($searchPath);
$connection->allows('getConfig')->with('schema')->returns($schema);
@@ -380,7 +380,7 @@ public static function currentSchemaListingConfigurationProvider(): array
public function testHasViewIsFalseWithoutACurrentSchema(): void
{
$connection = $this->getConnection();
- $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class));
+ $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)->strict());
$connection->expects('scalar')
->with('select current_schema()', [], false)
->returns(null);
@@ -392,8 +392,8 @@ public function testHasViewIsFalseWithoutACurrentSchema(): void
public function testHasViewUsesTheActualCurrentSchema(): void
{
$connection = $this->getConnection();
- $grammar = Double::for(PostgresGrammar::class);
- $processor = Double::for(PostgresProcessor::class);
+ $grammar = Double::for(PostgresGrammar::class)->strict();
+ $processor = Double::for(PostgresProcessor::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$connection->expects('getTablePrefix')->returns('');
@@ -481,7 +481,7 @@ public function testDropAllTablesWhenSearchPathIsArrayOfMany(): void
public function testDropAllObjectsWithAnEmptySearchPathLeavesEverySchemaUntouched(): void
{
$connection = $this->getConnection();
- $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class));
+ $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)->strict());
$connection->expects('getConfig')->times(3)->with('search_path')->returns('');
$connection->expects('selectFromWriteConnection')->never();
$connection->expects('statement')->never();
@@ -578,7 +578,7 @@ public function testDropAllDomainsPropagatesAFalseStatementResult(): void
*/
protected function getConnection(): Connection
{
- return Double::for(Connection::class);
+ return Double::for(Connection::class)->strict();
}
/**
@@ -589,7 +589,7 @@ protected function getConnection(): Connection
*/
protected function executionBlueprint(array $statements, array $commands): Blueprint
{
- $blueprint = Double::for(Blueprint::class);
+ $blueprint = Double::for(Blueprint::class)->strict();
$blueprint->expects('toSql')->returns($statements);
$blueprint->allows('getCommands')->returns($commands);
diff --git a/tests/Database/DatabasePostgresConnectionTest.php b/tests/Database/DatabasePostgresConnectionTest.php
index 26948b8b56..c7090e1ddd 100644
--- a/tests/Database/DatabasePostgresConnectionTest.php
+++ b/tests/Database/DatabasePostgresConnectionTest.php
@@ -142,7 +142,7 @@ public function testWaitingForACommitIdRequiresPostgres19OnTheReadConnection():
*/
protected function commitIdReadPdo(string $version): PDO
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$pdo->allows('getAttribute')->with(PDO::ATTR_SERVER_VERSION)->returns($version);
$pdo->allows('quote')->resolves(fn (string $value): string => "'{$value}'");
@@ -154,7 +154,7 @@ protected function commitIdReadPdo(string $version): PDO
*/
protected function commitIdStatement(bool|string $value): PDOStatement
{
- $statement = Double::for(PDOStatement::class);
+ $statement = Double::for(PDOStatement::class)->strict();
$statement->allows('setFetchMode')->returns(true);
$statement->allows('bindValue')->returns(true);
$statement->expects('execute')->returns(true);
diff --git a/tests/Database/DatabasePostgresQueryGrammarTest.php b/tests/Database/DatabasePostgresQueryGrammarTest.php
index c627a05ce2..fafecf26ac 100755
--- a/tests/Database/DatabasePostgresQueryGrammarTest.php
+++ b/tests/Database/DatabasePostgresQueryGrammarTest.php
@@ -23,7 +23,7 @@ public function testUpdateBindingsRejectUnencodableArrays(): void
{
$this->expectException(JsonException::class);
- (new PostgresGrammar(Double::for(Connection::class)))
+ (new PostgresGrammar(Double::for(Connection::class)->strict()))
->prepareBindingsForUpdate([], ['payload' => [NAN]]);
}
@@ -37,13 +37,13 @@ public function testUpdateFromBindingsRejectArraysOverTheNativeDepthLimit(): voi
$this->expectException(JsonException::class);
- (new PostgresGrammar(Double::for(Connection::class)))
+ (new PostgresGrammar(Double::for(Connection::class)->strict()))
->prepareBindingsForUpdateFrom([], ['payload' => $value]);
}
public function testToRawSql(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('escape')->with('foo', false)->returns("'foo'");
$grammar = new PostgresGrammar($connection);
@@ -75,7 +75,7 @@ public function testCustomOperators(): void
public function testCompileTruncate(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getTablePrefix')->times(3)->returns('');
$postgres = new PostgresGrammar($connection);
@@ -101,11 +101,11 @@ public function testCompileTruncate(): void
public function testFlushStateRestoresDefaults(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$postgres = new PostgresGrammar($connection);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->from = 'users';
PostgresGrammar::customOperators(['@@@']);
diff --git a/tests/Database/DatabasePostgresSchemaBuilderTest.php b/tests/Database/DatabasePostgresSchemaBuilderTest.php
index b8040585d9..db363961cb 100755
--- a/tests/Database/DatabasePostgresSchemaBuilderTest.php
+++ b/tests/Database/DatabasePostgresSchemaBuilderTest.php
@@ -18,7 +18,7 @@ class DatabasePostgresSchemaBuilderTest extends TestCase
public function testHasTable(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
$builder = new PostgresBuilder($connection);
@@ -32,7 +32,7 @@ public function testHasTable(): void
public function testGetColumnListing(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new PostgresGrammar($connection);
$connection->allows('getServerVersion')->returns('12.0.0');
$processor = new PostgresProcessor;
diff --git a/tests/Database/DatabasePostgresSchemaGrammarTest.php b/tests/Database/DatabasePostgresSchemaGrammarTest.php
index 38c2145c8e..6045288259 100755
--- a/tests/Database/DatabasePostgresSchemaGrammarTest.php
+++ b/tests/Database/DatabasePostgresSchemaGrammarTest.php
@@ -1714,7 +1714,7 @@ protected function getConnection(
?PostgresBuilder $builder = null,
string $prefix = ''
): Connection&DoubleInterface {
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns($prefix);
$connection->allows('getConfig')->with('prefix_indexes')->returns(null);
diff --git a/tests/Database/DatabasePostgresSchemaStateTest.php b/tests/Database/DatabasePostgresSchemaStateTest.php
index f033f58be9..72b014088c 100644
--- a/tests/Database/DatabasePostgresSchemaStateTest.php
+++ b/tests/Database/DatabasePostgresSchemaStateTest.php
@@ -49,7 +49,7 @@ public function testDumpOutputFailureStopsTheProcess(): void
public function testBaseVariablesUseConfiguredConnectionByDefault(): void
{
- $schemaState = new PostgresSchemaState(Double::for(PostgresConnection::class));
+ $schemaState = new PostgresSchemaState(Double::for(PostgresConnection::class)->strict());
$variables = (new ReflectionMethod(PostgresSchemaState::class, 'baseVariables'))->invoke($schemaState, [
'host' => 'pooler-host',
@@ -74,7 +74,7 @@ public function testBaseVariablesUseConfiguredConnectionByDefault(): void
public function testBaseVariablesDoNotExportEmptySslMode(): void
{
- $connection = Double::for(PostgresConnection::class);
+ $connection = Double::for(PostgresConnection::class)->strict();
$schemaState = new PostgresSchemaState($connection);
$method = new ReflectionMethod($schemaState, 'baseVariables');
@@ -105,14 +105,15 @@ public function testDumpPassesSchemaPathToProcessEnvironment(): void
'database' => 'hypervel',
];
- $schema = Double::for(PostgresBuilder::class);
+ $schema = Double::for(PostgresBuilder::class)->strict();
$schema->expects('hasTable')->with('migrations')->returns(false);
- $connection = Double::for(PostgresConnection::class);
+ $connection = Double::for(PostgresConnection::class)->strict();
$connection->allows('getConfig')->returns($config);
$connection->expects('getSchemaBuilder')->returns($schema);
- $process = Double::for(Process::class);
+ $process = Double::for(Process::class)->strict();
+ $process->allows('stop')->with(0.0)->returns(0); // Symfony stops the process in its destructor.
$process->expects('mustRun')->with(Argument::type('callable'), [
'HYPERVEL_LOAD_HOST' => '127.0.0.1',
'HYPERVEL_LOAD_PORT' => '5432',
@@ -142,10 +143,10 @@ public function testDumpPassesSchemaPathToProcessEnvironment(): void
public function testMigrationDataUsesLiteralPathAndTableArguments(): void
{
- $schema = Double::for(PostgresBuilder::class);
+ $schema = Double::for(PostgresBuilder::class)->strict();
$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 = Double::for(PostgresConnection::class)->strict();
$connection->expects('getSchemaBuilder')->times(2)->returns($schema);
$connection->expects('getTablePrefix')->returns('pre.');
$connection->allows('getConfig')->returns([
@@ -179,8 +180,8 @@ static function (?callable $output, array $variables) use (&$calls, $command, $p
public function testMigrationTableUsesTheActualSchemaUnlessExplicitlyQualified(): void
{
- $connection = Double::for(PostgresConnection::class);
- $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class));
+ $connection = Double::for(PostgresConnection::class)->strict();
+ $connection->expects('getSchemaGrammar')->returns(Double::for(PostgresGrammar::class)->strict());
$connection->expects('scalar')
->times(2)
->with('select current_schema()', [], false)
diff --git a/tests/Database/DatabaseProcessorTest.php b/tests/Database/DatabaseProcessorTest.php
index 733d152105..946d343dd9 100755
--- a/tests/Database/DatabaseProcessorTest.php
+++ b/tests/Database/DatabaseProcessorTest.php
@@ -18,10 +18,10 @@ class DatabaseProcessorTest extends TestCase
public function testInsertGetIdProcessing(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('insert')->with('sql', ['foo']);
$connection->expects('getLastInsertId')->with('id')->returns('1');
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getConnection')->times(2)->returns($connection);
$processor = new Processor;
$result = $processor->processInsertGetId($builder, 'sql', ['foo'], 'id');
@@ -31,10 +31,10 @@ public function testInsertGetIdProcessing(): void
public function testInsertGetIdPreservesTheConnectionFailureAfterTheInsertCompletes(): void
{
$failure = new RuntimeException('The database driver could not retrieve the last insert ID.');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('insert')->with('sql', ['foo'])->returns(true);
$connection->expects('getLastInsertId')->with('id')->throws($failure);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('getConnection')->times(2)->returns($connection);
$exception = null;
diff --git a/tests/Database/DatabaseQueryBuilderBindingTest.php b/tests/Database/DatabaseQueryBuilderBindingTest.php
index 21fb51f262..c6ce8a2c87 100644
--- a/tests/Database/DatabaseQueryBuilderBindingTest.php
+++ b/tests/Database/DatabaseQueryBuilderBindingTest.php
@@ -182,7 +182,7 @@ public static function betweenMethods(): iterable
*/
protected function builder(): Builder
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$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 ffc1b44bd6..4671260ac3 100644
--- a/tests/Database/DatabaseQueryBuilderEmbeddingTest.php
+++ b/tests/Database/DatabaseQueryBuilderEmbeddingTest.php
@@ -98,7 +98,7 @@ public static function attachmentPaths(): iterable
*/
protected function builder(): EmbeddingAwareQueryBuilder
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$connection->allows('getDatabaseName')->returns('database');
diff --git a/tests/Database/DatabaseQueryBuilderJoinTest.php b/tests/Database/DatabaseQueryBuilderJoinTest.php
index a35498f488..51d6966b85 100644
--- a/tests/Database/DatabaseQueryBuilderJoinTest.php
+++ b/tests/Database/DatabaseQueryBuilderJoinTest.php
@@ -134,7 +134,7 @@ public static function joinWhereOperands(): iterable
*/
protected function builder(): Builder
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$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 805c1cb8e4..c8b4c74a66 100644
--- a/tests/Database/DatabaseQueryBuilderPaginationTest.php
+++ b/tests/Database/DatabaseQueryBuilderPaginationTest.php
@@ -345,7 +345,7 @@ public function testDirectKeysetPagesPreserveScopesLimitsAndCurrentBindings(): v
$model = new class extends Model {
protected ?string $table = 'posts';
};
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->returns($connection);
$model::setConnectionResolver($resolver);
$query = (new EloquentBuilder($connection->query()))->setModel($model)
@@ -630,7 +630,7 @@ public function testAggregatePreparesCallbacksBeforeSelectingItsBindings(bool $g
public function testGroupedCountTransfersCallbackTimeoutAndRoutingToTheOuterStatement(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$query = new Builder($connection, new MySqlGrammar($connection), new Processor);
$query->from('events')->groupBy('tenant_id')->beforeQuery(function (Builder $query): void {
@@ -651,7 +651,7 @@ public function testGroupedCountTransfersCallbackTimeoutAndRoutingToTheOuterStat
public function testCallbackFailurePreservesIdentityAndRestoresTheOriginalFetchMode(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('');
$query = new Builder($connection, new Grammar($connection), new Processor);
$exception = new RuntimeException('Cannot prepare the query.');
@@ -682,9 +682,9 @@ public function testCallbackFailurePreservesIdentityAndRestoresTheOriginalFetchM
#[DataProvider('tablePrefixes')]
public function testRetainedInnerBindingsBelongToTheDerivedTable(string $prefix): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns($prefix);
- $processor = Double::for(Processor::class);
+ $processor = Double::for(Processor::class)->strict();
$query = new PaginationWithOrderingBuilder($connection, new Grammar($connection), $processor);
$query->from('events')->selectRaw('tenant_id + ? as bucket', [11])
->where('tenant_id', '>', 12)->groupBy('tenant_id')
diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php
index 7d2d5e1fac..0c60b0e868 100755
--- a/tests/Database/DatabaseQueryBuilderTest.php
+++ b/tests/Database/DatabaseQueryBuilderTest.php
@@ -3788,14 +3788,14 @@ public function testRelationSubqueriesCompileInSelectAndFromClausesAcrossDatabas
public function testCrossDatabaseQualificationKeepsQualifiedDerivedTablesAndTablelessSubqueriesUnchanged(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getDatabaseName')->returns('other_database');
$connection->allows('getTablePrefix')->returns('');
- $derived = new Builder($connection, new Grammar($connection), Double::for(Processor::class));
+ $derived = new Builder($connection, new Grammar($connection), Double::for(Processor::class)->strict());
$derived->from('other_database.events');
- $subquery = new Builder($connection, new Grammar($connection), Double::for(Processor::class));
+ $subquery = new Builder($connection, new Grammar($connection), Double::for(Processor::class)->strict());
$subquery->fromSub($derived, 'derived');
$outer = $this->getBuilder()->from('users')->whereIn('id', $subquery);
@@ -3805,7 +3805,7 @@ public function testCrossDatabaseQualificationKeepsQualifiedDerivedTablesAndTabl
$outer->toSql()
);
- $tableless = new Builder($connection, new Grammar($connection), Double::for(Processor::class));
+ $tableless = new Builder($connection, new Grammar($connection), Double::for(Processor::class)->strict());
$tableless->selectRaw('1');
$this->assertSame(
@@ -6165,7 +6165,7 @@ public function testTruncateMethod(): void
$builder->from('users')->truncate();
$builder = $this->getSQLiteBuilder();
- $schemaBuilder = Double::for(SchemaBuilder::class);
+ $schemaBuilder = Double::for(SchemaBuilder::class)->strict();
$schemaBuilder->expects('parseSchemaAndTable')->returns([null, 'users']);
$builder->getConnection()->expects('getSchemaBuilder')->returns($schemaBuilder);
$builder->from('users');
@@ -6183,7 +6183,7 @@ public function testTruncateMethodWithPrefix(): void
$builder->from('users')->truncate();
$builder = $this->getSQLiteBuilder(prefix: 'prefix_');
- $schemaBuilder = Double::for(SchemaBuilder::class);
+ $schemaBuilder = Double::for(SchemaBuilder::class)->strict();
$schemaBuilder->expects('parseSchemaAndTable')->returns([null, 'users']);
$builder->getConnection()->expects('getSchemaBuilder')->returns($schemaBuilder);
$builder->from('users');
@@ -6201,7 +6201,7 @@ public function testTruncateMethodWithPrefixAndSchema(): void
$builder->from('my_schema.users')->truncate();
$builder = $this->getSQLiteBuilder(prefix: 'prefix_');
- $schemaBuilder = Double::for(SchemaBuilder::class);
+ $schemaBuilder = Double::for(SchemaBuilder::class)->strict();
$schemaBuilder->expects('parseSchemaAndTable')->returns(['my_schema', 'users']);
$builder->getConnection()->expects('getSchemaBuilder')->returns($schemaBuilder);
$builder->from('my_schema.users');
@@ -6211,7 +6211,7 @@ public function testTruncateMethodWithPrefixAndSchema(): void
], $builder->getGrammar()->compileTruncate($builder));
$builder = $this->getSQLiteBuilder();
- $schemaBuilder = Double::for(SchemaBuilder::class);
+ $schemaBuilder = Double::for(SchemaBuilder::class)->strict();
$schemaBuilder->expects('parseSchemaAndTable')->returns(['0', 'users']);
$builder->getConnection()->expects('getSchemaBuilder')->returns($schemaBuilder);
$builder->from('0.users');
@@ -9333,7 +9333,7 @@ public function testToRawSql(): void
*/
protected function getConnection(string $prefix = '', string $connectionClass = Connection::class): Connection&DoubleInterface
{
- $connection = Double::for($connectionClass);
+ $connection = Double::for($connectionClass)->strict();
$connection->allows('getDatabaseName')->returns('database');
$connection->allows('getTablePrefix')->returns($prefix);
@@ -9351,14 +9351,14 @@ protected function getConnection(string $prefix = '', string $connectionClass =
*/
protected function getRelationSubquery(string $database = 'database', string $grammarClass = Grammar::class): HasMany
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getDatabaseName')->returns($database);
$connection->allows('getTablePrefix')->returns('');
$query = new EloquentBuilder(new Builder(
$connection,
new $grammarClass($connection),
- Double::for(Processor::class),
+ Double::for(Processor::class)->strict(),
));
$query->setModel(new QueryableSubqueryRelatedModel);
@@ -9444,7 +9444,7 @@ protected function getBuilder(string $prefix = ''): Builder
{
$connection = $this->getConnection(prefix: $prefix);
$grammar = new Grammar($connection);
- $processor = Double::for(Processor::class);
+ $processor = Double::for(Processor::class)->strict();
return new Builder($connection, $grammar, $processor);
}
@@ -9456,7 +9456,7 @@ protected function getPostgresBuilder(string $prefix = ''): Builder
{
$connection = $this->getConnection(prefix: $prefix);
$grammar = new PostgresGrammar($connection);
- $processor = Double::for(Processor::class);
+ $processor = Double::for(Processor::class)->strict();
return new Builder($connection, $grammar, $processor);
}
@@ -9468,7 +9468,7 @@ protected function getMySqlBuilder(string $prefix = ''): Builder
{
$connection = $this->getConnection(prefix: $prefix, connectionClass: MySqlConnection::class);
$grammar = new MySqlGrammar($connection);
- $processor = Double::for(Processor::class);
+ $processor = Double::for(Processor::class)->strict();
return new Builder($connection, $grammar, $processor);
}
@@ -9480,7 +9480,7 @@ protected function getMariaDbBuilder(string $prefix = ''): Builder
{
$connection = $this->getConnection(prefix: $prefix, connectionClass: MariaDbConnection::class);
$grammar = new MariaDbGrammar($connection);
- $processor = Double::for(Processor::class);
+ $processor = Double::for(Processor::class)->strict();
return new Builder($connection, $grammar, $processor);
}
@@ -9492,7 +9492,7 @@ protected function getSQLiteBuilder(string $prefix = ''): Builder
{
$connection = $this->getConnection(prefix: $prefix);
$grammar = new SQLiteGrammar($connection);
- $processor = Double::for(Processor::class);
+ $processor = Double::for(Processor::class)->strict();
return new Builder($connection, $grammar, $processor);
}
diff --git a/tests/Database/DatabaseQueryExceptionTest.php b/tests/Database/DatabaseQueryExceptionTest.php
index 8b52024f51..44e2c7642e 100755
--- a/tests/Database/DatabaseQueryExceptionTest.php
+++ b/tests/Database/DatabaseQueryExceptionTest.php
@@ -185,7 +185,7 @@ public function testMaskingBindingsDoesNotAffectTheAccessors(): void
*/
protected function getMockConnection(): Connection
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new Grammar($connection);
@@ -202,7 +202,7 @@ protected function getMockConnection(): Connection
*/
protected function getConnectionResolver(Connection $connection): ConnectionResolverInterface
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with('default')->returns($connection);
return $resolver;
diff --git a/tests/Database/DatabaseQueryGrammarTest.php b/tests/Database/DatabaseQueryGrammarTest.php
index e03440a7bc..881bf03560 100644
--- a/tests/Database/DatabaseQueryGrammarTest.php
+++ b/tests/Database/DatabaseQueryGrammarTest.php
@@ -27,12 +27,12 @@ public function testJsonContainsBindingRejectsUnencodableValues(): void
{
$this->expectException(JsonException::class);
- (new Grammar(Double::for(Connection::class)))->prepareBindingForJsonContains(NAN);
+ (new Grammar(Double::for(Connection::class)->strict()))->prepareBindingForJsonContains(NAN);
}
public function testWrapIdentifierEscapesOneIdentifierWithoutApplyingTheTablePrefix(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getTablePrefix')->never();
$grammar = new Grammar($connection);
@@ -44,7 +44,7 @@ public function testWrapIdentifierEscapesOneIdentifierWithoutApplyingTheTablePre
public function testQualifiedColumnsPrefixOnlyTheTableSegment(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns('app_');
$grammar = new Grammar($connection);
@@ -122,7 +122,7 @@ public function testRawSqlBindingSubstitutionPreservesParserSemantics(): void
$resourceIdentity = (string) $resource;
try {
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('escape')->with('first', false)->returns("'first'");
$connection->expects('escape')->with($resourceIdentity, false)->returns("'resource'");
@@ -202,7 +202,7 @@ public function escape(string|float|int|bool|null $value, bool $binary = false):
public function testRawSqlBindingSubstitutionHandlesLongBindingLists(): void
{
$bindings = range(1, 250);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('escape')
->times(count($bindings))
->resolves(static fn (int $value, bool $binary): string => (string) $value);
diff --git a/tests/Database/DatabaseReadPoolTest.php b/tests/Database/DatabaseReadPoolTest.php
index bcdfd9ed6f..9dd1f93d83 100644
--- a/tests/Database/DatabaseReadPoolTest.php
+++ b/tests/Database/DatabaseReadPoolTest.php
@@ -29,7 +29,7 @@ public function testReadRecordsAreSelectedForEachPhysicalCreationAndReconnect():
$factory = new ReadPoolConnectionFactory($this->app);
$this->app->instance('db.factory', $factory);
$hosts = [];
- $connector = Double::for(ConnectorInterface::class);
+ $connector = Double::for(ConnectorInterface::class)->strict();
$connector->expects('connect')->times(3)->resolves(static function (array $config) use (&$hosts): PDO {
$hosts[] = $config['host'];
diff --git a/tests/Database/DatabaseSQLiteBuilderTest.php b/tests/Database/DatabaseSQLiteBuilderTest.php
index 4881cda0f9..2d37fd2a64 100644
--- a/tests/Database/DatabaseSQLiteBuilderTest.php
+++ b/tests/Database/DatabaseSQLiteBuilderTest.php
@@ -79,7 +79,7 @@ public function testDropDatabaseIfExists(): void
#[DataProvider('nonFileDatabaseNames')]
public function testCreateDatabaseRejectsNonFileDatabaseNames(string $name): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
File::shouldReceive('put')->never();
@@ -95,7 +95,7 @@ public function testCreateDatabaseRejectsNonFileDatabaseNames(string $name): voi
#[DataProvider('nonFileDatabaseNames')]
public function testDropDatabaseRejectsNonFileDatabaseNames(string $name): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
File::shouldReceive('exists')->never();
@@ -120,7 +120,7 @@ public static function nonFileDatabaseNames(): array
public function testExecuteBlueprintWrapsAKnownRebuildAndMaintainsForeignKeyStateOutsideTheTransaction(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$blueprint = $this->executionBlueprint(
['pragma foreign_keys = 0', 'first statement', 'second statement', 'pragma foreign_keys = 1'],
@@ -142,7 +142,7 @@ public function testExecuteBlueprintWrapsAKnownRebuildAndMaintainsForeignKeyStat
public function testExecuteBlueprintPreservesDisabledForeignKeysOutsideTheTransaction(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$blueprint = $this->executionBlueprint(
['first statement', 'second statement'],
@@ -163,7 +163,7 @@ public function testExecuteBlueprintPreservesDisabledForeignKeysOutsideTheTransa
public function testExecuteBlueprintDoesNotWrapASingleStatement(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$blueprint = $this->executionBlueprint(
['statement'],
@@ -181,7 +181,7 @@ public function testExecuteBlueprintDoesNotWrapASingleStatement(): void
public function testExecuteBlueprintDoesNotWrapCommandsAddedByAnExtensionGrammar(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteBuilderExtensionGrammar($connection);
$connection->expects('getSchemaGrammar')->times(2)->returns($grammar);
@@ -203,7 +203,7 @@ public function testExecuteBlueprintDoesNotWrapCommandsAddedByAnExtensionGrammar
public function testExecuteBlueprintWrapsFrameworkCommandsOverriddenByAnExtensionGrammar(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteBuilderExtensionGrammar($connection);
$connection->expects('getSchemaGrammar')->times(2)->returns($grammar);
@@ -226,7 +226,7 @@ public function testExecuteBlueprintWrapsFrameworkCommandsOverriddenByAnExtensio
public function testExecuteBlueprintRestoresForeignKeysWhenTheTransactionFails(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$blueprint = $this->executionBlueprint(
['pragma foreign_keys = 0', 'failing statement', 'pragma foreign_keys = 1'],
@@ -298,7 +298,7 @@ public function testExecuteBlueprintCommitsSchemaBeforeForeignKeyRestorationFail
public function testExecuteBlueprintRejectsAPopulatedRebuildInsideATransactionWithForeignKeysEnabled(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$blueprint = $this->executionBlueprint(
['pragma foreign_keys = 0', 'first statement', 'second statement', 'pragma foreign_keys = 1'],
@@ -326,7 +326,7 @@ public function testExecuteBlueprintRejectsAPopulatedRebuildInsideATransactionWi
public function testExecuteBlueprintUsesASavepointForAnEmptyRebuildInsideATransaction(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$blueprint = $this->executionBlueprint(
['pragma foreign_keys = 0', 'first statement', 'second statement', 'pragma foreign_keys = 1'],
@@ -351,7 +351,7 @@ public function testExecuteBlueprintUsesASavepointForAnEmptyRebuildInsideATransa
public function testExecuteBlueprintUsesASavepointInsideATransactionWhenForeignKeysAreDisabled(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$blueprint = $this->executionBlueprint(
['first statement', 'second statement'],
@@ -372,7 +372,7 @@ public function testExecuteBlueprintUsesASavepointInsideATransactionWhenForeignK
public function testExecuteBlueprintDoesNotMutateSessionOrTransactionStateWhilePretending(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$blueprint = $this->executionBlueprint(
['pragma foreign_keys = 0', 'first statement', 'second statement', 'pragma foreign_keys = 1'],
@@ -394,7 +394,7 @@ public function testExecuteBlueprintDoesNotMutateSessionOrTransactionStateWhileP
public function testChangingForeignKeyConstraintsInsideATransactionFailsBeforeExecutingThePragma(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -536,7 +536,7 @@ public function testWithoutForeignKeyConstraintsAllowsAnAlreadyDisabledStateInsi
public function testDropAllTablesUsesGuardedCatalogCleanup(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -559,7 +559,7 @@ public function testDropAllTablesUsesGuardedCatalogCleanup(): void
public function testDropAllViewsRestoresAnEnabledWritableSchema(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -582,7 +582,7 @@ public function testDropAllViewsRestoresAnEnabledWritableSchema(): void
public function testDropAllTablesReloadsTheSchemaAfterADeleteFailure(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -607,7 +607,7 @@ public function testDropAllTablesReloadsTheSchemaAfterADeleteFailure(): void
public function testDropAllTablesMarksALegacySessionUnknownWhenVacuumFails(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -634,7 +634,7 @@ public function testDropAllTablesMarksALegacySessionUnknownWhenVacuumFails(): vo
public function testDropAllTablesKeepsAModernSessionKnownWhenVacuumFailsAfterReset(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -661,7 +661,7 @@ public function testDropAllTablesKeepsAModernSessionKnownWhenVacuumFailsAfterRes
public function testDropAllTablesStopsBeforeSchemaReloadWhenWritableSchemaResetFails(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$failure = new PDOException('Failed to reset writable_schema.');
@@ -690,7 +690,7 @@ public function testDropAllTablesStopsBeforeSchemaReloadWhenWritableSchemaResetF
public function testDropAllViewsPropagatesWritableModeRestorationFailure(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$failure = new PDOException('Failed to restore writable_schema.');
@@ -722,7 +722,7 @@ public function testDropAllViewsPropagatesWritableModeRestorationFailure(): void
public function testDropAllTablesRejectsAnActiveTransactionBeforeInspectingTheSchema(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
$connection->expects('transactionLevel')->returns(1);
$connection->expects('scalar')->never();
@@ -736,7 +736,7 @@ public function testDropAllTablesRejectsAnActiveTransactionBeforeInspectingTheSc
public function testDropAllViewsRejectsAnActiveTransactionBeforeInspectingTheSchema(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
$connection->expects('transactionLevel')->returns(1);
$connection->expects('scalar')->never();
@@ -750,7 +750,7 @@ public function testDropAllViewsRejectsAnActiveTransactionBeforeInspectingTheSch
public function testRefreshDatabaseFileUsesTheCanonicalMainDatabasePath(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
$connection->expects('transactionLevel')->returns(0);
$connection->expects('getDatabaseName')->returns('file:database.sqlite?mode=rwc');
@@ -768,7 +768,7 @@ public function testRefreshDatabaseFileUsesTheCanonicalMainDatabasePath(): void
public function testRefreshDatabaseFileRejectsWalForTheConnectedDatabase(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
$connection->expects('transactionLevel')->returns(0);
$connection->expects('getDatabaseName')->returns('/database.sqlite');
@@ -786,7 +786,7 @@ public function testRefreshDatabaseFileRejectsWalForTheConnectedDatabase(): void
public function testRefreshDatabaseFileRejectsAnActiveTransactionBeforeInspectingTheDatabase(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
$connection->expects('transactionLevel')->returns(1);
$connection->expects('getDatabaseName')->never();
@@ -801,7 +801,7 @@ public function testRefreshDatabaseFileRejectsAnActiveTransactionBeforeInspectin
public function testRefreshDatabaseFileWithAnExplicitPathDoesNotInspectTheConnection(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
$connection->expects('transactionLevel')->never();
$connection->expects('getDatabaseName')->never();
@@ -815,7 +815,7 @@ public function testRefreshDatabaseFileWithAnExplicitPathDoesNotInspectTheConnec
#[DataProvider('inMemoryDatabaseNames')]
public function testRefreshDatabaseFileRejectsInMemoryDatabasesWithoutWritingAFile(string $database): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
$connection->expects('transactionLevel')->returns(0);
$connection->expects('getDatabaseName')->returns($database);
@@ -844,7 +844,7 @@ public static function inMemoryDatabaseNames(): array
public function testRefreshDatabaseFileThrowsWhenTheFileCannotBeWritten(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaGrammar')->returns(new SQLiteGrammar($connection));
File::shouldReceive('put')
@@ -866,7 +866,7 @@ public function testRefreshDatabaseFileThrowsWhenTheFileCannotBeWritten(): void
*/
protected function executionBlueprint(array $statements, array $commands): Blueprint
{
- $blueprint = Double::for(Blueprint::class);
+ $blueprint = Double::for(Blueprint::class)->strict();
$blueprint->expects('toSql')->returns($statements);
$blueprint->allows('getCommands')->returns($commands);
diff --git a/tests/Database/DatabaseSQLiteQueryGrammarTest.php b/tests/Database/DatabaseSQLiteQueryGrammarTest.php
index bcaae5685c..bd731eb615 100755
--- a/tests/Database/DatabaseSQLiteQueryGrammarTest.php
+++ b/tests/Database/DatabaseSQLiteQueryGrammarTest.php
@@ -21,7 +21,7 @@ public function testUpdateBindingsRejectUnencodableArrays(): void
{
$this->expectException(JsonException::class);
- (new SQLiteGrammar(Double::for(Connection::class)))
+ (new SQLiteGrammar(Double::for(Connection::class)->strict()))
->prepareBindingsForUpdate([], ['payload' => [NAN]]);
}
diff --git a/tests/Database/DatabaseSQLiteSchemaGrammarTest.php b/tests/Database/DatabaseSQLiteSchemaGrammarTest.php
index 1ff1bf11d0..7682d6ade8 100755
--- a/tests/Database/DatabaseSQLiteSchemaGrammarTest.php
+++ b/tests/Database/DatabaseSQLiteSchemaGrammarTest.php
@@ -703,10 +703,8 @@ public function testAddingJson(): void
public function testAddingNativeJson(): void
{
- $connection = Double::for(Connection::class);
- $connection->expects('getTablePrefix')->returns('');
- $connection->expects('getConfig')->with('use_native_json')->returns(true);
- $connection->expects('getSchemaGrammar')->returns($this->getGrammar($connection));
+ $connection = $this->getConnection();
+ $connection->allows('getConfig')->with('use_native_json')->returns(true);
$blueprint = new Blueprint($connection, 'users');
$blueprint->json('foo');
@@ -728,10 +726,8 @@ public function testAddingJsonb(): void
public function testAddingNativeJsonb(): void
{
- $connection = Double::for(Connection::class);
- $connection->expects('getTablePrefix')->returns('');
- $connection->expects('getConfig')->with('use_native_jsonb')->returns(true);
- $connection->expects('getSchemaGrammar')->returns($this->getGrammar($connection));
+ $connection = $this->getConnection();
+ $connection->allows('getConfig')->with('use_native_jsonb')->returns(true);
$blueprint = new Blueprint($connection, 'users');
$blueprint->jsonb('foo');
@@ -1260,7 +1256,7 @@ protected function getConnection(
?SQLiteBuilder $builder = null,
string $prefix = ''
): Connection&DoubleInterface {
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar ??= $this->getGrammar($connection);
$builder ??= $this->getBuilder();
diff --git a/tests/Database/DatabaseSQLiteSchemaMetadataTest.php b/tests/Database/DatabaseSQLiteSchemaMetadataTest.php
index 3fb8708890..db9ef89a92 100644
--- a/tests/Database/DatabaseSQLiteSchemaMetadataTest.php
+++ b/tests/Database/DatabaseSQLiteSchemaMetadataTest.php
@@ -114,9 +114,9 @@ public function testStoredDefinitionRejectsMultipleColumns(): void
protected function builder(): array
{
- $connection = Double::for(Connection::class);
- $grammar = Double::for(SQLiteGrammar::class);
- $processor = Double::for(SQLiteProcessor::class);
+ $connection = Double::for(Connection::class)->strict();
+ $grammar = Double::for(SQLiteGrammar::class)->strict();
+ $processor = Double::for(SQLiteProcessor::class)->strict();
$connection->allows('getSchemaGrammar')->returns($grammar);
$connection->allows('getPostProcessor')->returns($processor);
diff --git a/tests/Database/DatabaseSchemaBlueprintTest.php b/tests/Database/DatabaseSchemaBlueprintTest.php
index 3021221d42..61014ed171 100755
--- a/tests/Database/DatabaseSchemaBlueprintTest.php
+++ b/tests/Database/DatabaseSchemaBlueprintTest.php
@@ -37,7 +37,7 @@ class DatabaseSchemaBlueprintTest extends TestCase
public function testToSqlRunsCommandsFromBlueprint(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getSchemaGrammar')->returns(new MySqlGrammar($connection));
$connection->expects('statement')->with('foo')->returns(true)->ordered();
$connection->expects('statement')->with('bar')->returns(true)->ordered();
@@ -1022,7 +1022,7 @@ protected function getConnection(?string $grammar = null, string $prefix = ''):
'MySql' => MySqlConnection::class,
'MariaDb' => MariaDbConnection::class,
default => Connection::class,
- });
+ })->strict();
$connection->allows('getTablePrefix')->returns($prefix);
$connection->allows('getConfig')->with('prefix_indexes')->returns(true);
@@ -1030,13 +1030,14 @@ protected function getConnection(?string $grammar = null, string $prefix = ''):
$builderClass = 'Hypervel\Database\Schema\\' . $grammar . 'Builder';
$connection->allows('getSchemaGrammar')->returns(new $grammarClass($connection));
- $connection->allows('getSchemaBuilder')->returns(Double::for($builderClass));
+ $connection->allows('getSchemaBuilder')->returns(Double::for($builderClass)->strict());
if ($grammar === 'SQLite') {
$connection->allows('getServerVersion')->returns('3.35');
}
if ($connection instanceof MySqlConnection) {
+ $connection->allows('isMaria')->returns($connection instanceof MariaDbConnection);
$connection->allows('usesBackslashEscapes')->returns(true);
}
diff --git a/tests/Database/DatabaseSchemaBuilderTest.php b/tests/Database/DatabaseSchemaBuilderTest.php
index dfd1c0e6fd..161908b0bb 100644
--- a/tests/Database/DatabaseSchemaBuilderTest.php
+++ b/tests/Database/DatabaseSchemaBuilderTest.php
@@ -27,9 +27,9 @@ class DatabaseSchemaBuilderTest extends TestCase
#[DataProvider('metadataMethods')]
public function testMetadataReadsUseTheOverridableWriterHook(string $method, array $arguments, string $compile, array $compileArguments, string $process): void
{
- $connection = Double::for(Connection::class);
- $grammar = Double::for(Grammar::class);
- $processor = Double::for(Processor::class);
+ $connection = Double::for(Connection::class)->strict();
+ $grammar = Double::for(Grammar::class)->strict();
+ $processor = Double::for(Processor::class)->strict();
$rows = [(object) ['name' => 'id']];
$processed = [['name' => 'id']];
$connection->allows('getSchemaGrammar')->returns($grammar);
@@ -62,8 +62,8 @@ public static function metadataMethods(): array
#[DataProvider('tableExistenceResults')]
public function testTableExistenceUsesTheMetadataHookAndPreservesScalarValidation(array $rows, ?bool $expected): void
{
- $connection = Double::for(Connection::class);
- $grammar = Double::for(Grammar::class);
+ $connection = Double::for(Connection::class)->strict();
+ $grammar = Double::for(Grammar::class)->strict();
$connection->allows('getSchemaGrammar')->returns($grammar);
$connection->allows('getTablePrefix')->returns('prefix_');
$grammar->expects('compileTableExists')->with('public', 'prefix_users')->returns('exists sql');
@@ -96,7 +96,7 @@ public static function tableExistenceResults(): array
public function testCreateDatabase(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new class($connection) extends Grammar {
};
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -108,7 +108,7 @@ public function testCreateDatabase(): void
public function testDropDatabaseIfExists(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new class($connection) extends Grammar {
};
$connection->expects('getSchemaGrammar')->returns($grammar);
@@ -120,11 +120,11 @@ public function testDropDatabaseIfExists(): void
public function testTruncateTablesChecksWriteRowsAndSkipsEmptyTables(): void
{
- $connection = Double::for(Connection::class);
- $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class));
+ $connection = Double::for(Connection::class)->strict();
+ $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class)->strict());
foreach (['public.populated' => true, 'public.empty' => false] as $name => $hasRows) {
- $query = Double::for(QueryBuilder::class);
+ $query = Double::for(QueryBuilder::class)->strict();
$connection->expects('table')->with($name)->returns($query);
$query->expects('useWritePdo')->returns($query);
$query->expects('exists')->returns($hasRows);
@@ -142,8 +142,8 @@ public function testTruncateTablesChecksWriteRowsAndSkipsEmptyTables(): void
#[DataProvider('partitionSelections')]
public function testWithoutCoveredPartitionsKeepsOnlyPartitionsOfTablesOutsideTheSelection(array $tables, array $except, ?array $missingParents, array $links, array $expected): void
{
- $connection = Double::for(Connection::class);
- $grammar = Double::for(Grammar::class);
+ $connection = Double::for(Connection::class)->strict();
+ $grammar = Double::for(Grammar::class)->strict();
$connection->allows('getSchemaGrammar')->returns($grammar);
if ($missingParents === null) {
@@ -190,9 +190,9 @@ public static function partitionSelections(): array
public function testExecuteBlueprintCompilesOnceAndExecutesStatementsInOrder(): void
{
- $connection = Double::for(Connection::class);
- $grammar = Double::for(Grammar::class);
- $blueprint = Double::for(Blueprint::class);
+ $connection = Double::for(Connection::class)->strict();
+ $grammar = Double::for(Grammar::class)->strict();
+ $blueprint = Double::for(Blueprint::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$blueprint->expects('toSql')->returns(['first statement', 'second statement']);
@@ -204,9 +204,9 @@ public function testExecuteBlueprintCompilesOnceAndExecutesStatementsInOrder():
public function testExecuteBlueprintThrowsWhenAStatementReturnsFalse(): void
{
- $connection = Double::for(Connection::class);
- $grammar = Double::for(Grammar::class);
- $blueprint = Double::for(Blueprint::class);
+ $connection = Double::for(Connection::class)->strict();
+ $grammar = Double::for(Grammar::class)->strict();
+ $blueprint = Double::for(Blueprint::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$blueprint->expects('toSql')->returns(['failed statement', 'unreached statement']);
@@ -221,9 +221,9 @@ public function testExecuteBlueprintThrowsWhenAStatementReturnsFalse(): void
public function testWithoutForeignKeyConstraintsNestsAcrossBuilderInstances(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$connection = new PdoConnection($pdo, 'test');
- $grammar = Double::for(Grammar::class);
+ $grammar = Double::for(Grammar::class)->strict();
$connection->setSchemaGrammar($grammar);
$grammar->expects('compileDisableForeignKeyConstraints')->returns('disable constraints');
@@ -252,7 +252,7 @@ static function () use (&$resolutions): PDO {
},
'test'
);
- $grammar = Double::for(Grammar::class);
+ $grammar = Double::for(Grammar::class)->strict();
$connection->setSchemaGrammar($grammar);
$grammar->expects('compileDisableForeignKeyConstraints')->returns('disable constraints');
@@ -271,9 +271,9 @@ static function () use (&$resolutions): PDO {
public function testWithoutForeignKeyConstraintsMarksTheSessionUnknownWhenRestorationFails(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$connection = new PdoConnection($pdo, 'test');
- $grammar = Double::for(Grammar::class);
+ $grammar = Double::for(Grammar::class)->strict();
$connection->setSchemaGrammar($grammar);
$failure = new PDOException('Failed to restore foreign key constraints.');
@@ -297,9 +297,9 @@ public function testWithoutForeignKeyConstraintsMarksTheSessionUnknownWhenRestor
public function testWithoutForeignKeyConstraintsPreservesNativeExceptionChainingWhenCallbackAndRestorationFail(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
$connection = new PdoConnection($pdo, 'test');
- $grammar = Double::for(Grammar::class);
+ $grammar = Double::for(Grammar::class)->strict();
$connection->setSchemaGrammar($grammar);
$callbackFailure = new RuntimeException('callback failed');
$restorationFailure = new RuntimeException('restoration failed');
@@ -324,9 +324,9 @@ public function testWithoutForeignKeyConstraintsPreservesNativeExceptionChaining
public function testHasTableCorrectlyCallsGrammar(): void
{
- $connection = Double::for(Connection::class);
- $grammar = Double::for(Grammar::class);
- $processor = Double::for(Processor::class);
+ $connection = Double::for(Connection::class)->strict();
+ $grammar = Double::for(Grammar::class)->strict();
+ $processor = Double::for(Processor::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$connection->expects('getPostProcessor')->returns($processor);
$builder = new Builder($connection);
@@ -341,8 +341,8 @@ public function testHasTableCorrectlyCallsGrammar(): void
public function testTableHasColumns(): void
{
- $connection = Double::for(Connection::class);
- $grammar = Double::for(Grammar::class);
+ $connection = Double::for(Connection::class)->strict();
+ $grammar = Double::for(Grammar::class)->strict();
$connection->expects('getSchemaGrammar')->returns($grammar);
$builder = Double::for(new Builder($connection))->passthru();
$builder->expects('getColumnListing')->with('users')->times(2)->returns(['id', 'firstname']);
@@ -354,8 +354,8 @@ public function testTableHasColumns(): void
#[DataProvider('columnNames')]
public function testColumnExistenceMatchesUnicodeWithoutCoercingNumericNames(string $column, bool $exists): void
{
- $connection = Double::for(Connection::class);
- $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class));
+ $connection = Double::for(Connection::class)->strict();
+ $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class)->strict());
$builder = Double::for(new Builder($connection))->passthru();
$builder->expects('getColumnListing')->with('users')->times(2)->returns(['Émail', '01']);
@@ -383,8 +383,8 @@ public function testColumnLookupPrefersExactNamesBeforeCaseInsensitiveMatches(st
['name' => 'FOO', 'type_name' => 'varchar', 'type' => 'varchar(255)'],
['name' => 'Émail', 'type_name' => 'text', 'type' => 'text'],
];
- $connection = Double::for(Connection::class);
- $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class));
+ $connection = Double::for(Connection::class)->strict();
+ $connection->expects('getSchemaGrammar')->returns(Double::for(Grammar::class)->strict());
$builder = Double::for(new Builder($connection))->passthru();
$builder->expects('getColumns')->with('users')->times(3)->returns($columns);
@@ -408,7 +408,7 @@ public static function columnLookups(): array
public function testGetColumnTypeAddsPrefix(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new class($connection) extends Grammar {
/**
* Compile the query to determine the columns.
diff --git a/tests/Database/DatabaseSchemaDumpCommandTest.php b/tests/Database/DatabaseSchemaDumpCommandTest.php
index e7d9f3865f..2f9ed2e723 100644
--- a/tests/Database/DatabaseSchemaDumpCommandTest.php
+++ b/tests/Database/DatabaseSchemaDumpCommandTest.php
@@ -11,6 +11,7 @@
use Hypervel\Testbench\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
class DatabaseSchemaDumpCommandTest extends TestCase
@@ -53,15 +54,15 @@ public function testDumpUsesAndIsNamedAfterTheMigrationConnection(array $options
'database.connections.pgsql' => ['driver' => 'pgsql'],
]);
- $connection = Double::for(Connection::class);
- $state = Double::for(SchemaState::class);
+ $connection = Double::for(Connection::class)->strict();
+ $state = Double::for(SchemaState::class)->strict();
$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'));
+ $state->expects('dump')->with(Argument::same($connection), database_path('schema/pgsql-schema.sql'));
- $connections = Double::for(ConnectionResolverInterface::class);
+ $connections = Double::for(ConnectionResolverInterface::class)->strict();
$connections->expects('connection')->with('pgsql')->returns($connection);
$this->app->instance(ConnectionResolverInterface::class, $connections);
diff --git a/tests/Database/DatabaseSeederTest.php b/tests/Database/DatabaseSeederTest.php
index da37a2dc9c..fec55d0ffb 100755
--- a/tests/Database/DatabaseSeederTest.php
+++ b/tests/Database/DatabaseSeederTest.php
@@ -151,14 +151,14 @@ protected function setUp(): void
public function testCallResolveTheClassAndCallsRun(): void
{
$seeder = new TestSeeder;
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$seeder->setContainer($container->instance());
- $output = Double::for(OutputStyle::class);
+ $output = Double::for(OutputStyle::class)->strict();
$output->expects('writeln')->times(3);
- $command = Double::for(Command::class);
+ $command = Double::for(Command::class)->strict();
$command->expects('getOutput')->times(3)->returns($output);
$seeder->setCommand($command);
- $child = Double::for(Seeder::class);
+ $child = Double::for(Seeder::class)->strict();
$container->expects('make')->with('ClassName')->returns($child);
$child->expects('setContainer')->with(Argument::same($container->instance()))->returns($child);
$child->expects('setCommand')->with(Argument::same($command))->returns($child);
@@ -183,7 +183,7 @@ public function testSetCommand(): void
public function testInjectDependenciesOnRunMethod(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('call');
$seeder = new TestDepsSeeder;
@@ -196,7 +196,7 @@ public function testInjectDependenciesOnRunMethod(): void
public function testSendParamsOnCallMethodWithDeps(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('call');
$seeder = new TestDepsSeeder;
diff --git a/tests/Database/DatabaseSqliteSchemaStateTest.php b/tests/Database/DatabaseSqliteSchemaStateTest.php
index 77059c1164..26037f58d0 100644
--- a/tests/Database/DatabaseSqliteSchemaStateTest.php
+++ b/tests/Database/DatabaseSqliteSchemaStateTest.php
@@ -24,11 +24,16 @@ class DatabaseSqliteSchemaStateTest extends TestCase
public function testLoadSchemaToDatabase(string $database): void
{
$config = ['driver' => 'sqlite', 'database' => $database, 'prefix' => '', 'foreign_key_constraints' => true, 'name' => 'sqlite'];
- $connection = Double::for(SQLiteConnection::class);
+ $connection = Double::for(SQLiteConnection::class)->strict();
$connection->expects('getConfig')->returns($config);
$connection->expects('getDatabaseName')->returns($config['database']);
- $process = Double::for(Process::class);
+ $process = Double::for(Process::class)->strict();
+ $process->allows('stop')->with(0.0)->returns(0); // Symfony stops the process in its destructor.
+ $process->expects('mustRun')->with(null, [
+ 'HYPERVEL_LOAD_DATABASE' => $database,
+ 'HYPERVEL_LOAD_PATH' => 'database/schema/sqlite-schema.dump',
+ ]);
$command = null;
$processFactory = function (string $givenCommand) use ($process, &$command): Process {
$command = $givenCommand;
@@ -40,11 +45,6 @@ public function testLoadSchemaToDatabase(string $database): void
$schemaState->load('database/schema/sqlite-schema.dump');
$this->assertSame('sqlite3 "${:HYPERVEL_LOAD_DATABASE}" < "${:HYPERVEL_LOAD_PATH}"', $command);
-
- $process->received('mustRun')->with(null, [
- 'HYPERVEL_LOAD_DATABASE' => $database,
- 'HYPERVEL_LOAD_PATH' => 'database/schema/sqlite-schema.dump',
- ]);
}
/**
@@ -63,20 +63,18 @@ public static function fileDatabaseProvider(): array
#[DataProvider('inMemoryDatabaseProvider')]
public function testLoadSchemaToInMemory(string $database): void
{
- $config = ['driver' => 'sqlite', 'database' => $database, 'prefix' => '', 'foreign_key_constraints' => true, 'name' => 'sqlite'];
- $connection = Double::for(SQLiteConnection::class);
- $connection->expects('getDatabaseName')->returns($config['database']);
- $pdo = Double::for(PDO::class);
- $pdo->expects('exec')->returns(0);
+ $sql = 'CREATE TABLE IF NOT EXISTS "migrations" ("id" integer not null primary key autoincrement, "migration" varchar not null, "batch" integer not null);';
+ $connection = Double::for(SQLiteConnection::class)->strict();
+ $connection->expects('getDatabaseName')->returns($database);
+ $pdo = Double::for(PDO::class)->strict();
+ $pdo->expects('exec')->with($sql)->returns(0);
$connection->expects('getPdo')->returns($pdo);
- $files = Double::for(Filesystem::class);
- $files->expects('get')->returns('CREATE TABLE IF NOT EXISTS "migrations" ("id" integer not null primary key autoincrement, "migration" varchar not null, "batch" integer not null);');
+ $files = Double::for(Filesystem::class)->strict();
+ $files->expects('get')->with('database/schema/sqlite-schema.dump')->returns($sql);
$schemaState = new SqliteSchemaState($connection, $files);
$schemaState->load('database/schema/sqlite-schema.dump');
-
- $pdo->received('exec')->with('CREATE TABLE IF NOT EXISTS "migrations" ("id" integer not null primary key autoincrement, "migration" varchar not null, "batch" integer not null);');
}
/**
@@ -95,10 +93,10 @@ public static function inMemoryDatabaseProvider(): array
public function testLoadSchemaToInMemoryRequiresPdoConnection(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getDatabaseName')->returns(':memory:');
- $schemaState = new SqliteSchemaState($connection, Double::for(Filesystem::class));
+ $schemaState = new SqliteSchemaState($connection, Double::for(Filesystem::class)->strict());
$this->expectException(LogicException::class);
$this->expectExceptionMessageIs('In-memory SQLite schema loading requires a PDO-backed connection.');
@@ -120,14 +118,10 @@ public function testDumpRemovesShadowTables(): void
$connection->statement('create index examples_body_index on examples (body)');
$connection->statement('create virtual table temp.logs using fts5(message)');
- $files = Double::for(Filesystem::class);
-
- (new SqliteSchemaState($connection, $files))
- ->withMigrationTable(null)
- ->dump($connection, 'schema.sql');
+ $files = Double::for(Filesystem::class)->strict();
// Literals that look like removed statements are kept, and a quoted table name gets IF NOT EXISTS, as in .schema.
- $files->received('put')->with('schema.sql', <<<'SQL'
+ $files->expects('put')->with('schema.sql', <<<'SQL'
CREATE VIRTUAL TABLE posts using fts5(body);
CREATE TABLE IF NOT EXISTS "logs_data" ("id" integer primary key autoincrement);
CREATE TABLE examples (body text default 'CREATE TABLE sqlite_bad(x);
@@ -137,5 +131,9 @@ public function testDumpRemovesShadowTables(): void
CREATE INDEX examples_body_index on examples (body);
SQL . PHP_EOL);
+
+ (new SqliteSchemaState($connection, $files))
+ ->withMigrationTable(null)
+ ->dump($connection, 'schema.sql');
}
}
diff --git a/tests/Database/DatabaseTransactionsTest.php b/tests/Database/DatabaseTransactionsTest.php
index b73bf433c8..c7415c8a42 100644
--- a/tests/Database/DatabaseTransactionsTest.php
+++ b/tests/Database/DatabaseTransactionsTest.php
@@ -73,7 +73,7 @@ protected function tearDown(): void
public function testTransactionIsRecordedAndCommitted(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$transactionManager->expects('begin')->with('default', 1);
$transactionManager->expects('commit')->with('default', 1, 0);
@@ -92,7 +92,7 @@ public function testTransactionIsRecordedAndCommitted(): void
public function testTransactionIsRecordedAndCommittedUsingTheSeparateMethods(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$transactionManager->expects('begin')->with('default', 1);
$transactionManager->expects('commit')->with('default', 1, 0);
@@ -111,7 +111,7 @@ public function testTransactionIsRecordedAndCommittedUsingTheSeparateMethods():
public function testNestedTransactionIsRecordedAndCommitted(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$transactionManager->expects('begin')->with('default', 1);
$transactionManager->expects('begin')->with('default', 2);
$transactionManager->expects('commit')->with('default', 2, 1);
@@ -138,7 +138,7 @@ public function testNestedTransactionIsRecordedAndCommitted(): void
public function testNestedTransactionIsRecordeForDifferentConnectionsdAndCommitted(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$transactionManager->expects('begin')->with('default', 1);
$transactionManager->expects('begin')->with('second_connection', 1);
$transactionManager->expects('begin')->with('second_connection', 2);
@@ -174,7 +174,7 @@ public function testNestedTransactionIsRecordeForDifferentConnectionsdAndCommitt
public function testTransactionIsRolledBack(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$transactionManager->expects('begin')->with('default', 1);
$transactionManager->expects('rollback')->with('default', 0);
$transactionManager->expects('commit')->never();
@@ -231,7 +231,7 @@ public function testFailedCommitRollsBackTheTransactionsManager(): void
public function testTransactionIsRolledBackUsingSeparateMethods(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$transactionManager->expects('begin')->with('default', 1);
$transactionManager->expects('rollback')->with('default', 0);
$transactionManager->expects('commit')->never();
@@ -253,7 +253,7 @@ public function testTransactionIsRolledBackUsingSeparateMethods(): void
public function testNestedTransactionsAreRolledBack(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$transactionManager->expects('begin')->with('default', 1);
$transactionManager->expects('begin')->with('default', 2);
$transactionManager->expects('rollback')->with('default', 1);
@@ -286,7 +286,7 @@ public function testNestedTransactionsAreRolledBack(): void
public function testAfterCommitRegistersTheCurrentConnectionName(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$callback = static function (): void {
};
@@ -326,7 +326,7 @@ public function testApplicableTransactionsExcludeTestWrappersButIncludeApplicati
$manager = new TestingTransactionsManager(['default', 'second_connection']);
$first = $this->connection();
$second = $this->connection('second_connection');
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with('default')->returns($first);
$database->expects('connection')->with('second_connection')->returns($second);
$manager->beginTransactions($database);
@@ -381,7 +381,7 @@ public function testAfterCommitOrNowRunsImmediatelyWithoutAManagerOrTransaction(
public function testAfterCommitOrNowDelegatesToTheTransactionManager(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$callback = static function (): void {
};
@@ -410,7 +410,7 @@ public function testAfterCommitOrNowRequiresAManagerDuringATransaction(): void
public function testAfterRollbackRegistersTheCurrentConnectionName(): void
{
- $transactionManager = Double::for(new DatabaseTransactionsManager);
+ $transactionManager = Double::for(new DatabaseTransactionsManager)->strict();
$callback = static function (): void {
};
diff --git a/tests/Database/DatabaseWipeCommandTest.php b/tests/Database/DatabaseWipeCommandTest.php
index e34c6edccd..d19c419ea4 100644
--- a/tests/Database/DatabaseWipeCommandTest.php
+++ b/tests/Database/DatabaseWipeCommandTest.php
@@ -24,16 +24,16 @@ class DatabaseWipeCommandTest extends TestCase
public function testWipeCommandDropsSchemaObjectsAndDisconnectsConnection(): void
{
- $schemaBuilder = Double::for(Builder::class);
+ $schemaBuilder = Double::for(Builder::class)->strict();
$schemaBuilder->expects('dropAllViews');
$schemaBuilder->expects('dropAllTables');
$schemaBuilder->expects('dropAllTypes');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaBuilder')->times(3)->returns($schemaBuilder);
$connection->expects('disconnect');
- $db = Double::for(DatabaseManager::class);
+ $db = Double::for(DatabaseManager::class)->strict();
$db->expects('connection')->times(4)->with('pgsql')->returns($connection);
$db->expects('purge')->never();
@@ -55,14 +55,14 @@ public function testWipeCommandDropsSchemaObjectsAndDisconnectsConnection(): voi
public function testWipeCommandRoutesToMigrationsConnection(): void
{
- $schemaBuilder = Double::for(Builder::class);
+ $schemaBuilder = Double::for(Builder::class)->strict();
$schemaBuilder->expects('dropAllTables');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaBuilder')->returns($schemaBuilder);
$connection->expects('disconnect');
- $db = Double::for(DatabaseManager::class);
+ $db = Double::for(DatabaseManager::class)->strict();
// db:wipe --database=pgsql-pooled should route to 'pgsql' because
// pgsql-pooled has migrations_connection => 'pgsql'. Schema drops
// need a direct (unpooled) connection.
@@ -97,14 +97,14 @@ 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 = Double::for(Builder::class);
+ $schemaBuilder = Double::for(Builder::class)->strict();
$schemaBuilder->expects('dropAllTables');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaBuilder')->returns($schemaBuilder);
$connection->expects('disconnect');
- $db = Double::for(DatabaseManager::class);
+ $db = Double::for(DatabaseManager::class)->strict();
$db->expects('connection')->times(2)->with('pgsql')->returns($connection);
$db->expects('purge')->never();
@@ -135,14 +135,14 @@ 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 = Double::for(Builder::class);
+ $schemaBuilder = Double::for(Builder::class)->strict();
$schemaBuilder->expects('dropAllTables');
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getSchemaBuilder')->returns($schemaBuilder);
$connection->expects('disconnect');
- $db = Double::for(DatabaseManager::class);
+ $db = Double::for(DatabaseManager::class)->strict();
$db->expects('connection')->times(2)->with('tenant-direct')->returns($connection);
$db->expects('purge')->never();
diff --git a/tests/Database/Eloquent/CustomBuilderForwardingTest.php b/tests/Database/Eloquent/CustomBuilderForwardingTest.php
index e9da8d47f7..e1fcc11762 100644
--- a/tests/Database/Eloquent/CustomBuilderForwardingTest.php
+++ b/tests/Database/Eloquent/CustomBuilderForwardingTest.php
@@ -73,7 +73,7 @@ public function testScopesWinOverQueryForwardingButNotNativeEloquentOrRelationMe
*/
private function builder(Model $model): ForwardingTestBuilder
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$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 8087bae7ac..a5cf721589 100644
--- a/tests/Database/Eloquent/ModelBootTest.php
+++ b/tests/Database/Eloquent/ModelBootTest.php
@@ -145,7 +145,7 @@ public function testBootedCallbackFailureLeavesTheModelPublishedAndClearsOwnersh
public function testBootedEventFailureLeavesTheModelPublishedAndClearsOwnership(): void
{
$failure = new RuntimeException('booted event failure');
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')
->with('eloquent.booting: ' . PostPublicationFailureModel::class, Argument::type(PostPublicationFailureModel::class))
->returns(null);
diff --git a/tests/Database/Eloquent/NewBaseQueryBuilderTest.php b/tests/Database/Eloquent/NewBaseQueryBuilderTest.php
index ce13371ebd..2330e693f3 100644
--- a/tests/Database/Eloquent/NewBaseQueryBuilderTest.php
+++ b/tests/Database/Eloquent/NewBaseQueryBuilderTest.php
@@ -26,14 +26,14 @@ class NewBaseQueryBuilderTest extends TestCase
public function testModelUsesConnectionQueryMethod(): void
{
- $mockConnection = Double::for(Connection::class);
+ $mockConnection = Double::for(Connection::class)->strict();
$customBuilder = new CustomQueryBuilder(
$mockConnection,
new Grammar($mockConnection),
new Processor
);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('query')->returns($customBuilder);
$model = new NewBaseQueryBuilderTestModel;
@@ -47,14 +47,14 @@ public function testModelUsesConnectionQueryMethod(): void
public function testPivotUsesConnectionQueryMethod(): void
{
- $mockConnection = Double::for(Connection::class);
+ $mockConnection = Double::for(Connection::class)->strict();
$customBuilder = new CustomQueryBuilder(
$mockConnection,
new Grammar($mockConnection),
new Processor
);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('query')->returns($customBuilder);
$pivot = new NewBaseQueryBuilderTestPivot;
@@ -68,14 +68,14 @@ public function testPivotUsesConnectionQueryMethod(): void
public function testMorphPivotUsesConnectionQueryMethod(): void
{
- $mockConnection = Double::for(Connection::class);
+ $mockConnection = Double::for(Connection::class)->strict();
$customBuilder = new CustomQueryBuilder(
$mockConnection,
new Grammar($mockConnection),
new Processor
);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('query')->returns($customBuilder);
$morphPivot = new NewBaseQueryBuilderTestMorphPivot;
diff --git a/tests/Database/Eloquent/UseEloquentBuilderTest.php b/tests/Database/Eloquent/UseEloquentBuilderTest.php
index 53ec7f8d84..5ab1347581 100644
--- a/tests/Database/Eloquent/UseEloquentBuilderTest.php
+++ b/tests/Database/Eloquent/UseEloquentBuilderTest.php
@@ -19,7 +19,7 @@ class UseEloquentBuilderTest extends TestCase
public function testNewModelBuilderReturnsDefaultBuilderWhenNoAttribute(): void
{
$model = new UseEloquentBuilderTestModel;
- $query = Double::for(QueryBuilder::class);
+ $query = Double::for(QueryBuilder::class)->strict();
$builder = $model->newEloquentBuilder($query);
@@ -30,7 +30,7 @@ public function testNewModelBuilderReturnsDefaultBuilderWhenNoAttribute(): void
public function testNewModelBuilderReturnsCustomBuilderWhenAttributePresent(): void
{
$model = new UseEloquentBuilderTestModelWithAttribute;
- $query = Double::for(QueryBuilder::class);
+ $query = Double::for(QueryBuilder::class)->strict();
$builder = $model->newEloquentBuilder($query);
@@ -41,7 +41,7 @@ public function testNewModelBuilderCachesResolvedBuilderClass(): void
{
$model1 = new UseEloquentBuilderTestModelWithAttribute;
$model2 = new UseEloquentBuilderTestModelWithAttribute;
- $query = Double::for(QueryBuilder::class);
+ $query = Double::for(QueryBuilder::class)->strict();
// First call should resolve and cache
$builder1 = $model1->newEloquentBuilder($query);
@@ -76,7 +76,7 @@ public function testDifferentModelsUseDifferentCaches(): void
{
$modelWithoutAttribute = new UseEloquentBuilderTestModel;
$modelWithAttribute = new UseEloquentBuilderTestModelWithAttribute;
- $query = Double::for(QueryBuilder::class);
+ $query = Double::for(QueryBuilder::class)->strict();
$builder1 = $modelWithoutAttribute->newEloquentBuilder($query);
$builder2 = $modelWithAttribute->newEloquentBuilder($query);
diff --git a/tests/Database/MigratorCoroutineIsolationTest.php b/tests/Database/MigratorCoroutineIsolationTest.php
index e70f4fe26a..6d30212a69 100644
--- a/tests/Database/MigratorCoroutineIsolationTest.php
+++ b/tests/Database/MigratorCoroutineIsolationTest.php
@@ -163,7 +163,7 @@ public function testNonCoroutineStateIsPreservedAcrossIndependentCoroutineRuns()
public function testReplacementMigratorDoesNotInheritReleasedInstanceState(): void
{
run(function (): void {
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$repository = new DatabaseMigrationRepository($resolver, 'migrations');
$files = new Filesystem;
$output = new BufferedOutput;
@@ -185,8 +185,8 @@ public function testReplacementMigratorDoesNotInheritReleasedInstanceState(): vo
public function testReplacementRepositoryDoesNotInheritReleasedInstanceConnection(): void
{
run(function (): void {
- $connection = Double::for(Connection::class);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $connection = Double::for(Connection::class)->strict();
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->with(null)->returns($connection);
$repository = new DatabaseMigrationRepository($resolver, 'migrations');
$repository->setSource('previous');
@@ -205,9 +205,9 @@ public function testReplacementRepositoryDoesNotInheritReleasedInstanceConnectio
*/
private function migrator(): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->allows('connection')->resolves(static function (?string $name): Connection {
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getName')->returns($name ?? 'default');
return $connection;
diff --git a/tests/Database/PoolManagerTest.php b/tests/Database/PoolManagerTest.php
index b0540d8f00..77110af2b5 100644
--- a/tests/Database/PoolManagerTest.php
+++ b/tests/Database/PoolManagerTest.php
@@ -442,9 +442,9 @@ public function testPurgeAllClearsCachedPools(): void
public function testPurgeAllDetachesPoolsBeforeClosingThem(): void
{
- $container = Double::for(ContainerContract::class, override: true);
- $original = Double::for(DatabasePool::class);
- $replacement = Double::for(DatabasePool::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $original = Double::for(DatabasePool::class)->strict();
+ $replacement = Double::for(DatabasePool::class)->strict();
$original->expects('start');
$replacement->expects('start');
$replacement->allows('isClosed')->returns(false);
@@ -472,9 +472,9 @@ public function testPurgeAllContinuesClosingAndPreservesFirstFailure(): void
{
$firstFailure = new RuntimeException('first close failed');
$secondFailure = new RuntimeException('second close failed');
- $firstPool = Double::for(DatabasePool::class);
- $secondPool = Double::for(DatabasePool::class);
- $thirdPool = Double::for(DatabasePool::class);
+ $firstPool = Double::for(DatabasePool::class)->strict();
+ $secondPool = Double::for(DatabasePool::class)->strict();
+ $thirdPool = Double::for(DatabasePool::class)->strict();
$firstPool->expects('start');
$secondPool->expects('start');
$thirdPool->expects('start');
@@ -482,7 +482,7 @@ public function testPurgeAllContinuesClosingAndPreservesFirstFailure(): void
$secondPool->expects('close')->throws($secondFailure);
$thirdPool->expects('close');
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$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);
@@ -535,9 +535,9 @@ public function testPurgeOnlyRemovesNamedPool(): void
public function testPurgeDetachesPoolBeforeClosingIt(): void
{
- $container = Double::for(ContainerContract::class, override: true);
- $original = Double::for(DatabasePool::class);
- $replacement = Double::for(DatabasePool::class);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $original = Double::for(DatabasePool::class)->strict();
+ $replacement = Double::for(DatabasePool::class)->strict();
$original->expects('start');
$replacement->expects('start');
$replacement->allows('isClosed')->returns(false);
@@ -733,10 +733,10 @@ public function testPurgeForConnectionDetachesSelectionAndPrioritizesCancellatio
{
$ordinaryFailure = new RuntimeException('write pool close failed');
$cancellation = new CanceledException;
- $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());
+ $writePool = Double::for(DatabasePool::class)->strict();
+ $readPool = Double::for(DatabasePool::class)->strict();
+ $cachePool = Double::for(DatabasePool::class)->strict();
+ $poolManager = new PoolManager(Double::for(ContainerContract::class, override: true)->strict()->instance());
$detachedPools = null;
$writePool->expects('close')->resolves(
@@ -798,7 +798,7 @@ private function mockContainerWithPools(?array $connections = null): ContainerCo
],
]);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$factory = new ConnectionFactory($container->instance());
$container->allows('make')->with('config')->returns($config);
diff --git a/tests/Database/SeedCommandTest.php b/tests/Database/SeedCommandTest.php
index a2c28aad67..35005919bc 100644
--- a/tests/Database/SeedCommandTest.php
+++ b/tests/Database/SeedCommandTest.php
@@ -39,7 +39,7 @@ protected function setUp(): void
public function testHandle(): void
{
- $seeder = Double::for(Seeder::class);
+ $seeder = Double::for(Seeder::class)->strict();
$seeder->expects('setContainer')->returns($seeder);
$seeder->expects('setCommand')->returns($seeder);
$seeder->expects('__invoke')->resolves(function (): void {
@@ -50,7 +50,7 @@ public function testHandle(): void
);
});
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub([
ConnectionResolverInterface::class => $resolver,
@@ -75,7 +75,7 @@ public function testHandle(): void
public function testReportsProgressForExplicitSeedersOnly(array $arguments, bool $reportsProgress): void
{
$seeder = new RecordsRootSeeder;
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub([
ConnectionResolverInterface::class => $resolver,
'DatabaseSeeder' => $seeder,
@@ -121,7 +121,7 @@ public static function seederProgressProvider(): array
public function testRootSeederConstructorCanMassAssignModels(): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub;
$command = new SeedCommand($resolver);
$command->setHypervel($app);
@@ -138,7 +138,7 @@ public function testRootSeederConstructorCanMassAssignModels(): void
public function testFailedSeederResolutionDoesNotReportProgress(): void
{
$exception = new RuntimeException('Seeder resolution failed');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub;
$app->bind(RecordsRootSeeder::class, fn () => throw $exception);
$command = new SeedCommand($resolver);
@@ -169,7 +169,7 @@ public function testFailedSeederRestoresPreviousDefaultConnection(): void
// seeder throws, not leak 'sqlite' or clear it entirely.
CoroutineContext::set(ConnectionResolver::DEFAULT_CONNECTION_CONTEXT_KEY, 'pgsql');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub([
ConnectionResolverInterface::class => $resolver,
@@ -214,7 +214,7 @@ public function testWithoutModelEvents(): void
$seeder->expects('setContainer')->returns($seeder);
$seeder->expects('setCommand')->returns($seeder);
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub([
ConnectionResolverInterface::class => $resolver,
@@ -241,7 +241,7 @@ public function testWithoutModelEvents(): void
public function testProhibitable(): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub([
ConnectionResolverInterface::class => $resolver,
@@ -264,7 +264,7 @@ public function testHandleWithoutDatabaseOptionUsesResolverDefault(): void
// from the resolver (which respects an active Context override)
// rather than going straight to config. This lets an outer scope's
// Context override flow through to db:seed correctly.
- $seeder = Double::for(Seeder::class);
+ $seeder = Double::for(Seeder::class)->strict();
$seeder->expects('setContainer')->returns($seeder);
$seeder->expects('setCommand')->returns($seeder);
$seeder->expects('__invoke')->resolves(function (): void {
@@ -275,7 +275,7 @@ public function testHandleWithoutDatabaseOptionUsesResolverDefault(): void
);
});
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('getDefaultConnection')->returns('tenant_reporting');
$app = new ApplicationDatabaseSeedStub([
@@ -291,7 +291,7 @@ public function testHandleWithoutDatabaseOptionUsesResolverDefault(): void
public function testHandlePreservesZeroDatabaseOption(): void
{
- $seeder = Double::for(Seeder::class);
+ $seeder = Double::for(Seeder::class)->strict();
$seeder->expects('setContainer')->returns($seeder);
$seeder->expects('setCommand')->returns($seeder);
$seeder->expects('__invoke')->resolves(function (): void {
@@ -301,7 +301,7 @@ public function testHandlePreservesZeroDatabaseOption(): void
);
});
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub([
ConnectionResolverInterface::class => $resolver,
@@ -319,7 +319,7 @@ public function testHandlePreservesZeroDatabaseOption(): void
public function testHandleWithEmptyDatabaseOptionUsesResolverDefault(): void
{
- $seeder = Double::for(Seeder::class);
+ $seeder = Double::for(Seeder::class)->strict();
$seeder->expects('setContainer')->returns($seeder);
$seeder->expects('setCommand')->returns($seeder);
$seeder->expects('__invoke')->resolves(function (): void {
@@ -329,7 +329,7 @@ public function testHandleWithEmptyDatabaseOptionUsesResolverDefault(): void
);
});
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('getDefaultConnection')->returns('tenant_reporting');
$app = new ApplicationDatabaseSeedStub([
@@ -350,12 +350,12 @@ public function testHandleDoesNotMutateConfigDatabaseDefault(): void
{
// Regression: db:seed must use Context, not config mutation. config
// ('database.default') should be untouched after a seed run.
- $seeder = Double::for(Seeder::class);
+ $seeder = Double::for(Seeder::class)->strict();
$seeder->expects('setContainer')->returns($seeder);
$seeder->expects('setCommand')->returns($seeder);
$seeder->expects('__invoke');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$config = new Repository(['database' => ['default' => 'pgsql']]);
@@ -382,7 +382,7 @@ public function testHandleDoesNotMutateConfigDatabaseDefault(): void
public function testHandleResolvesAFreshUnboundRootSeederForEachRun(): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$app = new ApplicationDatabaseSeedStub([
ConnectionResolverInterface::class => $resolver,
diff --git a/tests/Database/SimpleConnectionResolverIsolationTest.php b/tests/Database/SimpleConnectionResolverIsolationTest.php
index 611f83c10a..c31042b95b 100644
--- a/tests/Database/SimpleConnectionResolverIsolationTest.php
+++ b/tests/Database/SimpleConnectionResolverIsolationTest.php
@@ -31,8 +31,8 @@ class SimpleConnectionResolverIsolationTest extends TestCase
public function testTwoInstancesHaveIndependentDefaults(): void
{
- $resolverA = new SimpleConnectionResolver(Double::for(DatabaseManager::class));
- $resolverB = new SimpleConnectionResolver(Double::for(DatabaseManager::class));
+ $resolverA = new SimpleConnectionResolver(Double::for(DatabaseManager::class)->strict());
+ $resolverB = new SimpleConnectionResolver(Double::for(DatabaseManager::class)->strict());
$resolverA->setDefaultConnection('alpha');
$resolverB->setDefaultConnection('beta');
@@ -43,7 +43,7 @@ public function testTwoInstancesHaveIndependentDefaults(): void
public function testSetDefaultConnectionDoesNotWriteToSharedContext(): void
{
- $resolver = new SimpleConnectionResolver(Double::for(DatabaseManager::class));
+ $resolver = new SimpleConnectionResolver(Double::for(DatabaseManager::class)->strict());
// 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 5135290a03..1a755a129f 100644
--- a/tests/Di/Bootstrap/GenerateProxiesTest.php
+++ b/tests/Di/Bootstrap/GenerateProxiesTest.php
@@ -76,7 +76,7 @@ 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 = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
if ($aspects === 'none') {
$app->expects('bootstrapPath')->never();
diff --git a/tests/Di/ServiceProviderDiTest.php b/tests/Di/ServiceProviderDiTest.php
index e13dfa3a43..3a1326d7c9 100644
--- a/tests/Di/ServiceProviderDiTest.php
+++ b/tests/Di/ServiceProviderDiTest.php
@@ -64,7 +64,7 @@ public function testClassMapDelegatesToClassMapManager(): void
*/
protected function createMockApp(): ApplicationContract
{
- return Double::for(ApplicationContract::class, override: true)->instance();
+ return Double::for(ApplicationContract::class, override: true)->strict()->instance();
}
}
diff --git a/tests/Doctor/Feature/Diagnostics/CacheStoreIsReachableTest.php b/tests/Doctor/Feature/Diagnostics/CacheStoreIsReachableTest.php
index fc7af05ad4..86d539d979 100644
--- a/tests/Doctor/Feature/Diagnostics/CacheStoreIsReachableTest.php
+++ b/tests/Doctor/Feature/Diagnostics/CacheStoreIsReachableTest.php
@@ -370,7 +370,7 @@ public function testCleanupPreservesPrimaryFailuresAndCancellation(bool $primary
$cleanupCanceled => new CanceledException('cleanup canceled'),
default => new RuntimeException('cleanup failed'),
};
- $store = Double::for(Store::class);
+ $store = Double::for(Store::class)->strict();
$store->expects('put')->throws($primary);
$store->expects('forget')->throws($cleanup);
Cache::extend('probe', fn (): Repository => new Repository($store));
diff --git a/tests/Doctor/Feature/Diagnostics/DatabaseConnectionIsReachableTest.php b/tests/Doctor/Feature/Diagnostics/DatabaseConnectionIsReachableTest.php
index 1700b37a7e..cadcb30c31 100644
--- a/tests/Doctor/Feature/Diagnostics/DatabaseConnectionIsReachableTest.php
+++ b/tests/Doctor/Feature/Diagnostics/DatabaseConnectionIsReachableTest.php
@@ -146,7 +146,7 @@ public function testCustomDriverNeutralConnectionsAreProbedAndDisconnected(bool
'database.default' => 'analytics',
'database.connections.analytics' => ['driver' => 'custom', 'options' => 'transport-owned'],
]);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$version = $connection->expects('getServerVersion');
if ($fails) {
@@ -268,7 +268,7 @@ public function testReadRecordExtensionsFollowTheRequestedConnectionRole(string
'read' => ['driver' => 'replica', 'options' => 'transport-owned'],
],
]);
- $custom = Double::for(Connection::class);
+ $custom = Double::for(Connection::class)->strict();
if ($suffix === '::read') {
$custom->expects('getServerVersion')->returns('1.0');
$custom->expects('disconnect');
diff --git a/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php b/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php
index 04e882bb6e..3316b00891 100644
--- a/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php
+++ b/tests/Doctor/Feature/Diagnostics/MigrationsAreUpToDateTest.php
@@ -153,7 +153,7 @@ public function up(): void
#[DataProvider('migrationFailures')]
public function testReportsWhenPendingMigrationsCannotBeApplied(?string $exceptionClass): void
{
- $kernel = Double::for(Kernel::class);
+ $kernel = Double::for(Kernel::class)->strict();
Artisan::swap($kernel);
$command = $kernel->expects('call')->with('migrate', ['--no-interaction' => true]);
diff --git a/tests/Doctor/Feature/Diagnostics/PublicStorageLinkExistsTest.php b/tests/Doctor/Feature/Diagnostics/PublicStorageLinkExistsTest.php
index 08b349d70d..044aa12799 100644
--- a/tests/Doctor/Feature/Diagnostics/PublicStorageLinkExistsTest.php
+++ b/tests/Doctor/Feature/Diagnostics/PublicStorageLinkExistsTest.php
@@ -162,7 +162,7 @@ public function testPreservesConflictingPathsAndDoesNotOfferAMixedRepair(string
'filesystems.disks.public' => ['driver' => 'local', 'root' => $root],
'filesystems.links' => [$link => $root, $this->basePath . '/missing' => $root],
]);
- $kernel = Double::for(Kernel::class);
+ $kernel = Double::for(Kernel::class)->strict();
$kernel->expects('call')->never();
Artisan::swap($kernel);
$diagnostic = new PublicStorageLinkExists;
@@ -201,7 +201,7 @@ public function testReportsWhenTheCommandDoesNotRepairTheLink(int $exitCode, ?st
'filesystems.disks.public' => ['driver' => 'local', 'root' => $root],
'filesystems.links' => [$this->basePath . '/uploads' => $root],
]);
- $kernel = Double::for(Kernel::class);
+ $kernel = Double::for(Kernel::class)->strict();
Artisan::swap($kernel);
$command = $kernel->expects('call')->with('storage:link');
diff --git a/tests/Doctor/Feature/Diagnostics/QueueConnectionIsReachableTest.php b/tests/Doctor/Feature/Diagnostics/QueueConnectionIsReachableTest.php
index 441634ca76..5cc6b4b091 100644
--- a/tests/Doctor/Feature/Diagnostics/QueueConnectionIsReachableTest.php
+++ b/tests/Doctor/Feature/Diagnostics/QueueConnectionIsReachableTest.php
@@ -119,7 +119,7 @@ public function testBuiltInNullConnectionNeedsNoConfigurationRecord(): void
public function testRemoteQueuesMustCompleteAReadOnlyOperation(string $driver, bool $fails): void
{
config(['queue.default' => 'remote', 'queue.connections.remote' => ['driver' => $driver]]);
- $queue = Double::for(QueueContract::class);
+ $queue = Double::for(QueueContract::class)->strict();
$probe = $queue->expects('size')->with(Argument::none());
if ($fails) {
diff --git a/tests/Doctor/Feature/Diagnostics/RecommendedPhpExtensionsAreLoadedTest.php b/tests/Doctor/Feature/Diagnostics/RecommendedPhpExtensionsAreLoadedTest.php
index 4ed0dbf104..d4cf81b644 100644
--- a/tests/Doctor/Feature/Diagnostics/RecommendedPhpExtensionsAreLoadedTest.php
+++ b/tests/Doctor/Feature/Diagnostics/RecommendedPhpExtensionsAreLoadedTest.php
@@ -20,7 +20,7 @@ class RecommendedPhpExtensionsAreLoadedTest extends TestCase
#[RequiresPhpExtension('Zend OPcache')]
public function testRecognizesComposerNormalizedExtensionNames(): void
{
- $composer = Double::for(ComposerJson::class);
+ $composer = Double::for(ComposerJson::class)->strict();
$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 e8e6879f69..1855fed950 100644
--- a/tests/Doctor/Feature/Diagnostics/SessionDriverIsReachableTest.php
+++ b/tests/Doctor/Feature/Diagnostics/SessionDriverIsReachableTest.php
@@ -122,7 +122,7 @@ public static function redisConnections(): array
public function testDatabaseSessionsKeepTheDefaultSchemaConnection(): void
{
config(['session.driver' => 'database', 'session.connection' => null, 'session.table' => 'custom_sessions']);
- $schema = Double::for(Builder::class);
+ $schema = Double::for(Builder::class)->strict();
$schema->expects('hasTable')->with('custom_sessions')->returns(true);
Schema::shouldReceive('connection')->with(null)->andReturn($schema);
diff --git a/tests/Doctor/Feature/Support/InstalledPackagesTest.php b/tests/Doctor/Feature/Support/InstalledPackagesTest.php
index 33116bd338..101ccc4afb 100644
--- a/tests/Doctor/Feature/Support/InstalledPackagesTest.php
+++ b/tests/Doctor/Feature/Support/InstalledPackagesTest.php
@@ -131,7 +131,7 @@ public function testDoesNotInventAnUnknownRootSelfVersion(): void
*/
private function snapshot(array $root): array
{
- $composer = Double::for(ComposerJson::class);
+ $composer = Double::for(ComposerJson::class)->strict();
$composer->allows('contents')->returns($root);
return $this->packages->platformRequirements($composer);
diff --git a/tests/Encryption/CryptFacadeTest.php b/tests/Encryption/CryptFacadeTest.php
index 7b1277b153..9d1434ab99 100644
--- a/tests/Encryption/CryptFacadeTest.php
+++ b/tests/Encryption/CryptFacadeTest.php
@@ -25,7 +25,7 @@ protected function setUp(): void
public function testDynamicCallsForwardTheirMethodArgumentsAndReturnValue(): void
{
- $root = Double::for(CryptFacadeRoot::class);
+ $root = Double::for(CryptFacadeRoot::class)->strict();
$root->expects('probe')
->with('value', 42)
->returns('result');
diff --git a/tests/Engine/CoroutineTest.php b/tests/Engine/CoroutineTest.php
index 2b99f7ba55..3909e68437 100644
--- a/tests/Engine/CoroutineTest.php
+++ b/tests/Engine/CoroutineTest.php
@@ -31,24 +31,26 @@ public function testCoroutineIdRequiresExecution(): void
public function testCoroutineCreate(): void
{
- $coroutine = new Coroutine(function () {
- $this->assertTrue(true);
+ $id = null;
+ $coroutine = new Coroutine(static function () use (&$id): void {
+ $id = Coroutine::id();
});
$coroutine->execute();
$this->assertInstanceOf(CoroutineInterface::class, $coroutine);
- $this->assertIsInt($coroutine->getId());
+ $this->assertSame($coroutine->getId(), $id);
}
public function testCoroutineCreateStatic(): void
{
- $coroutine = Coroutine::create(function () {
- $this->assertTrue(true);
+ $id = null;
+ $coroutine = Coroutine::create(static function () use (&$id): void {
+ $id = Coroutine::id();
});
$this->assertInstanceOf(CoroutineInterface::class, $coroutine);
- $this->assertIsInt($coroutine->getId());
+ $this->assertSame($coroutine->getId(), $id);
}
public function testCreatedCoroutineKeepsErrorReportingEnabledAfterSuspension(): void
diff --git a/tests/Engine/SocketTest.php b/tests/Engine/SocketTest.php
index 07eef53ffe..57493e2674 100644
--- a/tests/Engine/SocketTest.php
+++ b/tests/Engine/SocketTest.php
@@ -15,6 +15,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use Psr\Log\LoggerInterface;
use ReflectionProperty;
@@ -355,10 +356,11 @@ function (int $port) use ($peerClosed): void {
if ($throw) {
try {
$socket->sendAll('after-close');
- $this->fail('A closed SafeSocket should reject later sends.');
} catch (SocketClosedException) {
- $this->addToAssertionCount(1);
+ continue;
}
+
+ $this->fail('A closed SafeSocket should reject later sends.');
} else {
$this->assertFalse($socket->sendAll('after-close'));
}
@@ -374,12 +376,12 @@ public function testSafeSocketClosesAndReportsWhenItsLoggerFails(): void
{
$sendFailure = new RuntimeException('Send failed.');
$loggingFailure = new RuntimeException('Logging failed.');
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($loggingFailure);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($loggingFailure));
$container = new Container;
$container->instance(ExceptionHandler::class, $handler);
Container::setInstance($container);
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->expects('critical')->with((string) $sendFailure)->throws($loggingFailure);
$nativeSocket = new FailingSendSocket($sendFailure);
$socket = new SafeSocket($nativeSocket, logger: $logger);
diff --git a/tests/Events/BroadcastedEventsTest.php b/tests/Events/BroadcastedEventsTest.php
index 4541958c95..43bcc42ff5 100644
--- a/tests/Events/BroadcastedEventsTest.php
+++ b/tests/Events/BroadcastedEventsTest.php
@@ -53,9 +53,9 @@ public function testShouldBroadcastSuccess(): void
public function testShouldBroadcastAsQueuedAndCallNormalListeners(): void
{
unset($_SERVER['__event.test']);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$d = new Dispatcher($container->instance());
- $broadcast = Double::for(BroadcastFactory::class);
+ $broadcast = Double::for(BroadcastFactory::class)->strict();
$broadcast->expects('queue');
$container->expects('make')->with(BroadcastFactory::class)->returns($broadcast);
@@ -90,9 +90,9 @@ public function testShouldBroadcastFail(): void
public function testBroadcastWithMultipleChannels(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$d = new Dispatcher($container->instance());
- $broadcast = Double::for(BroadcastFactory::class);
+ $broadcast = Double::for(BroadcastFactory::class)->strict();
$broadcast->expects('queue');
$container->expects('make')->with(BroadcastFactory::class)->returns($broadcast);
@@ -108,9 +108,9 @@ public function broadcastOn(): array
public function testBroadcastWithCustomConnectionName(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$d = new Dispatcher($container->instance());
- $broadcast = Double::for(BroadcastFactory::class);
+ $broadcast = Double::for(BroadcastFactory::class)->strict();
$broadcast->expects('queue');
$container->expects('make')->with(BroadcastFactory::class)->returns($broadcast);
@@ -128,9 +128,9 @@ public function broadcastOn(): array
public function testBroadcastWithCustomEventName(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$d = new Dispatcher($container->instance());
- $broadcast = Double::for(BroadcastFactory::class);
+ $broadcast = Double::for(BroadcastFactory::class)->strict();
$broadcast->expects('queue');
$container->expects('make')->with(BroadcastFactory::class)->returns($broadcast);
@@ -151,9 +151,9 @@ public function broadcastAs(): string
public function testBroadcastWithCustomPayload(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$d = new Dispatcher($container->instance());
- $broadcast = Double::for(BroadcastFactory::class);
+ $broadcast = Double::for(BroadcastFactory::class)->strict();
$broadcast->expects('queue');
$container->expects('make')->with(BroadcastFactory::class)->returns($broadcast);
@@ -177,7 +177,7 @@ public function broadcastWith(): array
public function testEventBroadcastsUsingNamedArguments(): void
{
$container = new Container;
- $broadcast = Double::for(BroadcastFactory::class);
+ $broadcast = Double::for(BroadcastFactory::class)->strict();
$container->instance(BroadcastFactory::class, $broadcast);
$originalContainer = Container::getInstance();
@@ -187,19 +187,16 @@ public function testEventBroadcastsUsingNamedArguments(): void
$pendingBroadcast = new PendingBroadcastWithoutDestructor(new Dispatcher, new stdClass);
$broadcast->expects('event')
- ->with(Argument::satisfies(function (mixed $event): bool {
- $this->assertInstanceOf(BroadcastableNamedArgumentsEvent::class, $event);
- $this->assertSame('first-value', $event->first);
- $this->assertSame('second-value', $event->second);
-
- return true;
- }))
+ ->with(Argument::capture($event))
->returns($pendingBroadcast);
$this->assertSame(
$pendingBroadcast,
BroadcastableNamedArgumentsEvent::broadcast(second: 'second-value', first: 'first-value')
);
+ $this->assertInstanceOf(BroadcastableNamedArgumentsEvent::class, $event);
+ $this->assertSame('first-value', $event->first);
+ $this->assertSame('second-value', $event->second);
} finally {
Container::setInstance($originalContainer);
}
diff --git a/tests/Events/EventsDispatcherTest.php b/tests/Events/EventsDispatcherTest.php
index 99c26ba787..8bbb65ba89 100755
--- a/tests/Events/EventsDispatcherTest.php
+++ b/tests/Events/EventsDispatcherTest.php
@@ -204,20 +204,16 @@ public function testHaltingEventExecution(): void
{
unset($_SERVER['__event.test']);
$d = new Dispatcher;
- $d->listen('foo', function ($foo) {
- $this->assertTrue(true);
-
- return 'here';
- });
+ $d->listen('foo', fn ($foo) => $foo);
$d->listen('foo', function ($foo) {
throw new Exception('should not be called');
});
$response = $d->dispatch('foo', ['bar'], true);
- $this->assertSame('here', $response);
+ $this->assertSame('bar', $response);
$response = $d->until('foo', ['bar']);
- $this->assertSame('here', $response);
+ $this->assertSame('bar', $response);
}
public function testResponseWhenNoListenersAreSet(): void
diff --git a/tests/Events/EventsSubscriberTest.php b/tests/Events/EventsSubscriberTest.php
index d9c0e42583..c466a700d3 100644
--- a/tests/Events/EventsSubscriberTest.php
+++ b/tests/Events/EventsSubscriberTest.php
@@ -17,7 +17,7 @@ class EventsSubscriberTest extends TestCase
public function testEventSubscribeCanAcceptObject(): void
{
$d = new Dispatcher;
- $subs = Double::for(ExampleSubscriber::class);
+ $subs = Double::for(ExampleSubscriber::class)->strict();
$subs->expects('subscribe')->with(Argument::same($d));
$d->subscribe($subs);
diff --git a/tests/Events/QueuedEventsTest.php b/tests/Events/QueuedEventsTest.php
index aa62fcb67e..266b7b7440 100644
--- a/tests/Events/QueuedEventsTest.php
+++ b/tests/Events/QueuedEventsTest.php
@@ -117,8 +117,8 @@ public function testQueueIsSetByGetQueue(): void
public function testQueueIsSetByGetConnection(): void
{
$d = new Dispatcher;
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$factory->expects('connection')->with('some_other_connection')->returns($queue);
$queue->expects('pushOn')->with(null, Argument::type(CallQueuedListener::class));
@@ -134,8 +134,8 @@ public function testQueueIsSetByGetConnection(): void
public function testEnumQueueAndConnectionResultsAreNormalizedBeforeDispatch(): void
{
$dispatcher = new Dispatcher;
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$factory->expects('connection')->with('0')->returns($queue);
$queue->expects('pushOn')->with('1', Argument::type(CallQueuedListener::class));
@@ -148,8 +148,8 @@ public function testEnumQueueAndConnectionResultsAreNormalizedBeforeDispatch():
public function testDelayIsSetByWithDelay(): void
{
$d = new Dispatcher;
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$factory->expects('connection')->with(null)->returns($queue);
$queue->expects('laterOn')->with(null, 20, Argument::type(CallQueuedListener::class));
@@ -165,8 +165,8 @@ public function testDelayIsSetByWithDelay(): void
public function testDelayIsSetByAttribute(): void
{
$d = new Dispatcher;
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$factory->expects('connection')->with(null)->returns($queue);
$queue->expects('laterOn')->with(null, 30, Argument::type(CallQueuedListener::class));
@@ -182,8 +182,8 @@ public function testDelayIsSetByAttribute(): void
public function testWithDelayOverridesDelayAttribute(): void
{
$d = new Dispatcher;
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$factory->expects('connection')->with(null)->returns($queue);
$queue->expects('laterOn')->with(null, 20, Argument::type(CallQueuedListener::class));
@@ -247,7 +247,7 @@ public function testQueueIsSetUsingQueueRoutes(): void
$queueRoutes->set(TestDispatcherQueueRoutes::class, 'event-queue', 'event-connection');
$container->instance('queue.routes', $queueRoutes);
- $factory = Double::for(QueueFactory::class);
+ $factory = Double::for(QueueFactory::class)->strict();
$queue = new QueueFake($container);
$factory->expects('connection')->with('event-connection')->returns($queue);
@@ -274,7 +274,7 @@ public function testConnectionIsSetUsingForwardedQueue(): void
$queueRoutes->forward('reports', 'processing', 'cloud');
$container->instance('queue.routes', $queueRoutes);
- $factory = Double::for(QueueFactory::class);
+ $factory = Double::for(QueueFactory::class)->strict();
$queue = new QueueFake($container);
$factory->expects('connection')->with('cloud')->returns($queue);
@@ -295,8 +295,8 @@ public function testForwardedConnectionUsesTheDynamicallySelectedQueue(): void
$routes->forward('my_queue', 'unused', 'wrong-connection');
$routes->forward('some_other_queue', 'processing', 'cloud');
$container->instance('queue.routes', $routes);
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$factory->expects('connection')->with('cloud')->returns($queue);
$queue->expects('pushOn')->with('some_other_queue', Argument::type(CallQueuedListener::class));
@@ -308,8 +308,8 @@ public function testForwardedConnectionUsesTheDynamicallySelectedQueue(): void
public function testDelayIsSetByWithDelayDynamically(): void
{
$d = new Dispatcher;
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$factory->expects('connection')->with(null)->returns($queue);
$queue->expects('laterOn')->with(null, 60, Argument::type(CallQueuedListener::class));
@@ -526,12 +526,12 @@ public function testQueuePropagatesShouldBeUnique(): void
$d = new Dispatcher($container);
$fakeQueue = new QueueFake($container);
- $cache = Double::for(Cache::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$container->instance(Cache::class, $cache);
- $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class));
+ $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)->strict());
$cache->expects('lock')->returns($lock);
$lock->expects('get')->returns(true);
$lock->expects('owner')->returns('unique-lock-owner');
@@ -557,12 +557,12 @@ public function testUniqueListenerNotQueuedWhenLockNotAcquired(): void
$d = new Dispatcher($container);
$fakeQueue = new QueueFake($container);
- $cache = Double::for(Cache::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$container->instance(Cache::class, $cache);
- $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class));
+ $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)->strict());
$cache->expects('lock')->returns($lock);
$lock->expects('get')->returns(false);
@@ -582,12 +582,12 @@ public function testQueuePropagatesShouldBeUniqueUntilProcessing(): void
$d = new Dispatcher($container);
$fakeQueue = new QueueFake($container);
- $cache = Double::for(Cache::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$container->instance(Cache::class, $cache);
- $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class));
+ $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)->strict());
$cache->expects('lock')->returns($lock);
$lock->expects('get')->returns(true);
$lock->expects('owner')->returns('unique-lock-owner');
@@ -611,12 +611,12 @@ public function testQueuePropagatesUniqueIdFromMethod(): void
$d = new Dispatcher($container);
$fakeQueue = new QueueFake($container);
- $cache = Double::for(Cache::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$container->instance(Cache::class, $cache);
- $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class));
+ $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)->strict());
$cache->expects('lock')->returns($lock);
$lock->expects('get')->returns(true);
$lock->expects('owner')->returns('unique-lock-owner');
@@ -652,8 +652,8 @@ public function testUniqueLockIsAcquiredWithListenerClassName(): void
$d = new Dispatcher($container);
$fakeQueue = new QueueFake($container);
- $cache = Double::for(Cache::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$container->instance(Cache::class, $cache);
@@ -662,7 +662,7 @@ public function testUniqueLockIsAcquiredWithListenerClassName(): void
$cache->expects('lock')
->with($expectedKey, 60)
->returns($lock);
- $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class));
+ $cache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)->strict());
$lock->expects('get')->returns(true);
$lock->expects('owner')->returns('unique-lock-owner');
@@ -682,9 +682,9 @@ public function testUniqueViaUsesListenerCacheRepository(): void
$d = new Dispatcher($container);
$fakeQueue = new QueueFake($container);
- $defaultCache = Double::for(Cache::class, LockProvider::class);
- $uniqueCache = Double::for(Cache::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $defaultCache = Double::for(Cache::class, LockProvider::class)->strict();
+ $uniqueCache = Double::for(Cache::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$container->instance(Cache::class, $defaultCache);
@@ -697,7 +697,7 @@ public function testUniqueViaUsesListenerCacheRepository(): void
$uniqueCache->expects('lock')
->with($expectedKey, 60)
->returns($lock);
- $uniqueCache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class));
+ $uniqueCache->expects('getStore')->returns(Double::for(CacheStore::class, LockProvider::class)->strict());
$lock->expects('get')->returns(true);
$lock->expects('owner')->returns('unique-lock-owner');
@@ -714,8 +714,8 @@ public function testUniqueViaUsesListenerCacheRepository(): void
public function testUniqueLockIsReleasedOnProcessingWithListenerClassName(): void
{
$container = new Container;
- $cache = Double::for(Cache::class, LockProvider::class);
- $lock = Double::for(Lock::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
+ $lock = Double::for(Lock::class)->strict();
$container->instance(Cache::class, $cache);
$container->instance(BusDispatcher::class, new BusDispatcher($container));
@@ -800,8 +800,8 @@ public function testExplicitListenerDelayTakesPrecedenceOverDebounceDelay(): voi
{
$container = new Container;
$dispatcher = new Dispatcher($container);
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$cache = new Repository(new ArrayStore);
$container->instance(Cache::class, $cache);
@@ -825,8 +825,8 @@ public function testDebouncedListenerMaxWaitForcesImmediateExecution(): void
$container = new Container;
$dispatcher = new Dispatcher($container);
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$cache = new Repository(new ArrayStore);
$container->instance(Cache::class, $cache);
@@ -883,7 +883,7 @@ public function testDebouncedListenerCannotAlsoBeUnique(): void
$container = new Container;
$dispatcher = new Dispatcher($container);
$queue = new QueueFake($container);
- $cache = Double::for(Cache::class, LockProvider::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
$cache->expects('put')->never();
$cache->expects('lock')->never();
@@ -902,7 +902,7 @@ public function testUniqueListenerLockIsReleasedWhenQueueResolutionFails(): void
{
$container = new Container;
$dispatcher = new Dispatcher($container);
- $factory = Double::for(QueueFactory::class);
+ $factory = Double::for(QueueFactory::class)->strict();
$cache = new Repository(new ArrayStore);
$failure = new Exception('Queue unavailable.');
$lockKey = 'laravel_unique_job:' . hash('xxh128', TestDispatcherShouldBeUnique::class) . ':unique-listener-id';
@@ -929,8 +929,8 @@ public function testDebouncedListenerPublicationFailureReleasesItsOwnership(): v
{
$container = new Container;
$dispatcher = new Dispatcher($container);
- $factory = Double::for(QueueFactory::class);
- $queue = Double::for(Queue::class);
+ $factory = Double::for(QueueFactory::class)->strict();
+ $queue = Double::for(Queue::class)->strict();
$cache = new Repository(new ArrayStore);
$failure = new Exception('Queue unavailable.');
$lockKey = 'laravel_debounced_job:' . hash('xxh128', TestDispatcherDebouncedHandlerWithMaxWait::class) . ':event-123';
diff --git a/tests/Filesystem/AwsS3V3AdapterTest.php b/tests/Filesystem/AwsS3V3AdapterTest.php
index 6ad14b2bea..12cd9e4c19 100644
--- a/tests/Filesystem/AwsS3V3AdapterTest.php
+++ b/tests/Filesystem/AwsS3V3AdapterTest.php
@@ -333,9 +333,9 @@ function (CommandInterface $request) use (&$command): Result {
'options' => ['@http' => ['timeout' => 12]],
]);
$adapter->getDriver()->allows('fileExists')->returns(true);
- $emptyDriver = Double::for(FilesystemOperator::class);
+ $emptyDriver = Double::for(FilesystemOperator::class)->strict();
$emptyDriver->allows('fileExists')->returns(false);
- $empty = new FilesystemAdapter($emptyDriver, Double::for(FlysystemAdapter::class));
+ $empty = new FilesystemAdapter($emptyDriver, Double::for(FlysystemAdapter::class)->strict());
$pools = new PoolManager;
$definition = new PoolDefinition('filesystem:read-through-range', 's3', 'test', PoolOptions::fromArray([]));
$cloud = match ($poolType) {
@@ -354,7 +354,7 @@ function (CommandInterface $request) use (&$command): Result {
),
null => $adapter,
};
- $exceptionHandler = Double::for(ExceptionHandler::class);
+ $exceptionHandler = Double::for(ExceptionHandler::class)->strict();
$exceptionHandler->expects('report')->never();
Container::getInstance()->instance(ExceptionHandler::class, $exceptionHandler);
$manager = new FilesystemManager(Container::getInstance());
@@ -435,7 +435,7 @@ public function testReadStreamRangePreservesCancellationWithoutReporting(bool $w
{
$cancellation = new CanceledException('read canceled');
$failure = $wrapped ? new S3Exception('SDK request canceled.', new Command('GetObject'), previous: $cancellation) : $cancellation;
- $exceptionHandler = Double::for(ExceptionHandler::class);
+ $exceptionHandler = Double::for(ExceptionHandler::class)->strict();
$exceptionHandler->expects('report')->never();
Container::getInstance()->bind(ExceptionHandler::class, static fn () => $exceptionHandler);
$handler = new MockHandler([$failure]);
@@ -459,7 +459,7 @@ public function testReadStreamRangePreservesCancellationWithoutReporting(bool $w
public function testReadStreamRangeRejectsAResultWithoutAResource(): void
{
- $body = Double::for(StreamInterface::class);
+ $body = Double::for(StreamInterface::class)->strict();
$body->allows('isReadable')->returns(false);
$body->allows('isWritable')->returns(false);
$handler = new MockHandler([new Result(['Body' => $body])]);
@@ -533,8 +533,8 @@ private function adapter(MockHandler $handler, array $config): AwsS3V3Adapter
]);
return new AwsS3V3Adapter(
- Double::for(FilesystemOperator::class),
- Double::for(FlysystemAdapter::class),
+ Double::for(FilesystemOperator::class)->strict(),
+ Double::for(FlysystemAdapter::class)->strict(),
$config,
$client,
);
diff --git a/tests/Filesystem/ClientPooledFilesystemTest.php b/tests/Filesystem/ClientPooledFilesystemTest.php
index 355740bef8..686724e4f9 100644
--- a/tests/Filesystem/ClientPooledFilesystemTest.php
+++ b/tests/Filesystem/ClientPooledFilesystemTest.php
@@ -142,7 +142,7 @@ static function (object $client) use ($root): FilesystemAdapter {
$this->assertFalse($source->exists('file.txt'));
$source->put('file.txt', 'retained');
- $failedDestination = Double::for(FilesystemContract::class);
+ $failedDestination = Double::for(FilesystemContract::class)->strict();
$stream = null;
$failedDestination->expects('writeStream')->with('file.txt', Argument::satisfies(is_resource(...)))->resolves(function (string $path, mixed $resource) use (&$stream): bool {
$stream = $resource;
@@ -451,7 +451,7 @@ public function testBufferedReadStreamReleasesTheClientBeforeConsumption(): void
fwrite($buffer, 'buffered contents');
rewind($buffer);
- $stack = Double::for(FilesystemAdapter::class);
+ $stack = Double::for(FilesystemAdapter::class)->strict();
$stack->expects('readStream')->with('file.txt')->returns($buffer);
$disk = $this->disk(
$clientCreations,
@@ -477,7 +477,7 @@ public function testNonResourceReadStreamResultReleasesImmediately(): void
{
$clientCreations = 0;
$stackCreations = 0;
- $stack = Double::for(FilesystemAdapter::class);
+ $stack = Double::for(FilesystemAdapter::class)->strict();
$stack->expects('readStream')->with('missing.txt')->returns(null);
$disk = $this->disk(
$clientCreations,
@@ -517,14 +517,14 @@ public function testDiscardFailureDoesNotMaskAStackFactoryFailure(): void
$client = new ClientPooledFilesystemClient;
$stackFailure = new RuntimeException('stack failed');
$discardFailure = new RuntimeException('discard failed');
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($discardFailure);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($discardFailure));
$container->instance(ExceptionHandler::class, $handler);
- $pool = Double::for(ObjectPoolContract::class);
+ $pool = Double::for(ObjectPoolContract::class)->strict();
$pool->expects('borrow')->returns($client);
- $pool->expects('discard')->with($client)->throws($discardFailure);
- $factory = Double::for(Factory::class);
+ $pool->expects('discard')->with(Argument::same($client))->throws($discardFailure);
+ $factory = Double::for(Factory::class)->strict();
$factory->expects('getOrCreate')->returns($pool);
$disk = new ClientPooledFilesystem(
$this->definition(),
@@ -611,12 +611,12 @@ public function testOperationExceptionStaysPrimaryWhenReleaseCallbackAlsoThrows(
$container = Container::getInstance();
$operationFailure = new RuntimeException('operation failed');
$releaseFailure = new RuntimeException('release failed');
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($releaseFailure);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($releaseFailure));
$container->instance(ExceptionHandler::class, $handler);
$clientCreations = 0;
$stackCreations = 0;
- $stack = Double::for(FilesystemAdapter::class);
+ $stack = Double::for(FilesystemAdapter::class)->strict();
$stack->expects('get')->with('file.txt')->throws($operationFailure);
$disk = $this->disk(
$clientCreations,
@@ -643,7 +643,7 @@ public function testReleaseCancellationSupersedesAnOperationFailure(): void
$releaseCancellation = new CanceledException('release canceled');
$clientCreations = 0;
$stackCreations = 0;
- $stack = Double::for(FilesystemAdapter::class);
+ $stack = Double::for(FilesystemAdapter::class)->strict();
$stack->expects('get')->with('file.txt')->throws($operationFailure);
$disk = $this->disk(
$clientCreations,
diff --git a/tests/Filesystem/FileResponseBuilderTest.php b/tests/Filesystem/FileResponseBuilderTest.php
index 3845244e57..af1225d8b8 100644
--- a/tests/Filesystem/FileResponseBuilderTest.php
+++ b/tests/Filesystem/FileResponseBuilderTest.php
@@ -17,6 +17,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use League\Flysystem\UnableToReadFile;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
@@ -420,8 +421,8 @@ public function testWriterFailureStaysPrimaryWhenClosingAlsoFails(): void
Container::setInstance($container);
$writerFailure = new RuntimeException('writer failed');
$closeFailure = new RuntimeException('close failed');
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($closeFailure);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($closeFailure));
$container->instance(ExceptionHandler::class, $handler);
$state = new FileResponseBuilderStreamState('contents', closeFailure: $closeFailure);
$response = $this->build(
diff --git a/tests/Filesystem/FilesystemAdapterTest.php b/tests/Filesystem/FilesystemAdapterTest.php
index c06b1b7a5b..d8773d002a 100644
--- a/tests/Filesystem/FilesystemAdapterTest.php
+++ b/tests/Filesystem/FilesystemAdapterTest.php
@@ -485,7 +485,7 @@ public function testPrepend(): void
public function testPrependDoesNotOverwriteAnUnreadableExistingFile(): void
{
- $driver = Double::for(FilesystemOperator::class);
+ $driver = Double::for(FilesystemOperator::class)->strict();
$driver->expects('fileExists')->with('file.txt')->returns(true);
$driver->expects('read')->with('file.txt')->throws(UnableToReadFile::fromLocation('file.txt'));
$driver->expects('write')->never();
@@ -504,7 +504,7 @@ public function testAppend(): void
public function testAppendDoesNotOverwriteAnUnreadableExistingFile(): void
{
- $driver = Double::for(FilesystemOperator::class);
+ $driver = Double::for(FilesystemOperator::class)->strict();
$driver->expects('fileExists')->with('file.txt')->returns(true);
$driver->expects('read')->with('file.txt')->throws(UnableToReadFile::fromLocation('file.txt'));
$driver->expects('write')->never();
@@ -564,7 +564,7 @@ public function testCopyToDisk(): void
$backupFilesystem = new Filesystem($backupAdapter = new LocalFilesystemAdapter($this->tempDir . '/backup'));
- $filesystemFactory = Double::for(FilesystemFactory::class);
+ $filesystemFactory = Double::for(FilesystemFactory::class)->strict();
$filesystemFactory->expects('disk')->returns(new FilesystemAdapter($backupFilesystem, $backupAdapter));
Container::getInstance()->instance(FilesystemFactory::class, $filesystemFactory);
@@ -582,7 +582,7 @@ public function testMoveToDisk(): void
$backupFilesystem = new Filesystem($backupAdapter = new LocalFilesystemAdapter($this->tempDir . '/backup'));
- $filesystemFactory = Double::for(FilesystemFactory::class);
+ $filesystemFactory = Double::for(FilesystemFactory::class)->strict();
$filesystemFactory->expects('disk')->returns(new FilesystemAdapter($backupFilesystem, $backupAdapter));
Container::getInstance()->instance(FilesystemFactory::class, $filesystemFactory);
@@ -600,7 +600,7 @@ public function testCopyToDiskRejectsSameDiskAndPath(): void
$filesystemAdapter = new FilesystemAdapter($this->filesystem, $this->adapter);
- $filesystemFactory = Double::for(FilesystemFactory::class);
+ $filesystemFactory = Double::for(FilesystemFactory::class)->strict();
$filesystemFactory->expects('disk')->returns($filesystemAdapter);
Container::getInstance()->instance(FilesystemFactory::class, $filesystemFactory);
@@ -868,13 +868,9 @@ public function testReadStreamRangeThrowsAndClosesAStalledStreamWhenConfigured()
public function testReadStreamRangeReportsAndClosesAStalledStreamWhenConfigured(): void
{
[$reader, $writer] = $this->openStalledNonSeekableStream();
- $exceptionHandler = Double::for(ExceptionHandler::class);
+ $exceptionHandler = Double::for(ExceptionHandler::class)->strict();
$exceptionHandler->expects('report')
- ->with(Argument::satisfies(static function (UnableToReadFile $exception): bool {
- self::assertInstanceOf(RuntimeException::class, $exception->getPrevious());
-
- return true;
- }));
+ ->with(Argument::capture($exception));
Container::getInstance()->bind(ExceptionHandler::class, static fn () => $exceptionHandler);
$filesystemAdapter = Double::for(new FilesystemAdapter(
$this->filesystem,
@@ -885,13 +881,16 @@ public function testReadStreamRangeReportsAndClosesAStalledStreamWhenConfigured(
$this->assertNull($filesystemAdapter->readStreamRange('file.txt', 3, 5));
+ $this->assertInstanceOf(UnableToReadFile::class, $exception);
+ $this->assertInstanceOf(RuntimeException::class, $exception->getPrevious());
+
$this->assertFalse(is_resource($reader));
fclose($writer);
}
public function testReadStreamRangePreservesCancellationAndClosesTheSourceWithoutReporting(): void
{
- $exceptionHandler = Double::for(ExceptionHandler::class);
+ $exceptionHandler = Double::for(ExceptionHandler::class)->strict();
$exceptionHandler->expects('report')->never();
Container::getInstance()->bind(ExceptionHandler::class, static fn () => $exceptionHandler);
$originalHookFlags = Runtime::getHookFlags();
@@ -975,7 +974,7 @@ public function testPutWithDecodedStreamPreservesProducerCancellationAndClosesTh
public function testPutWithStreamAllowsTheWriterToCloseItsInput(): void
{
$body = new CachingStream(new Stream(fopen('php://temp', 'w+b')));
- $driver = Double::for(FilesystemOperator::class);
+ $driver = Double::for(FilesystemOperator::class)->strict();
$driver->expects('writeStream')->resolves(
static function (string $path, mixed $stream): void {
fclose($stream);
@@ -1324,10 +1323,10 @@ public function testCallbackMutatorsCanClearPreviouslyConfiguredCallbacks(): voi
#[DataProvider('canceledFilesystemOperations')]
public function testCancellationBypassesTheFilesystemFailurePolicy(string $method, array $arguments, string $driverMethod, Throwable $failure): void
{
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->never();
$this->app->instance(ExceptionHandler::class, $handler);
- $driver = Double::for(Filesystem::class);
+ $driver = Double::for(Filesystem::class)->strict();
$driver->expects($driverMethod)->throws($failure);
$adapter = new FilesystemAdapter($driver, $this->adapter, ['throw' => false, 'report' => true]);
$stream = $method === 'writeStream' ? fopen('php://memory', 'w+b') : null;
@@ -1391,7 +1390,7 @@ public function testRangeReadPreservesCancellationFromTheStreamProducerAndCloses
]);
}
$stream = StreamWrapper::detach($body);
- $driver = Double::for(FilesystemOperator::class);
+ $driver = Double::for(FilesystemOperator::class)->strict();
$driver->expects('readStream')->returns($stream);
$adapter = new FilesystemAdapter($driver, $this->adapter);
$caught = null;
@@ -1420,30 +1419,16 @@ public function testThrowExceptionsForGet(): void
{
$adapter = new FilesystemAdapter($this->filesystem, $this->adapter, ['throw' => true]);
- try {
- $adapter->get('/foo.txt');
- } catch (UnableToReadFile) {
- $this->assertTrue(true);
-
- return;
- }
-
- $this->fail('Exception was not thrown.');
+ $this->expectException(UnableToReadFile::class);
+ $adapter->get('/foo.txt');
}
public function testThrowExceptionsForReadStream(): void
{
$adapter = new FilesystemAdapter($this->filesystem, $this->adapter, ['throw' => true]);
- try {
- $adapter->readStream('/foo.txt');
- } catch (UnableToReadFile) {
- $this->assertTrue(true);
-
- return;
- }
-
- $this->fail('Exception was not thrown.');
+ $this->expectException(UnableToReadFile::class);
+ $adapter->readStream('/foo.txt');
}
public function testThrowExceptionsForPut(): void
@@ -1459,16 +1444,11 @@ public function testThrowExceptionsForPut(): void
$adapter = new FilesystemAdapter($this->filesystem, $this->adapter, ['throw' => true]);
+ $this->expectException(UnableToWriteFile::class);
$adapter->put('/foo.txt', 'Hello World!');
- } catch (UnableToWriteFile) {
- $this->assertTrue(true);
-
- return;
} finally {
chmod($this->tempDir . '/foo.txt', 0600);
}
-
- $this->fail('Exception was not thrown.');
}
public function testThrowExceptionsForMimeType(): void
@@ -1477,15 +1457,8 @@ public function testThrowExceptionsForMimeType(): void
$adapter = new FilesystemAdapter($this->filesystem, $this->adapter, ['throw' => true]);
- try {
- $adapter->mimeType('unknown.mime-type');
- } catch (UnableToRetrieveMetadata) {
- $this->assertTrue(true);
-
- return;
- }
-
- $this->fail('Exception was not thrown.');
+ $this->expectException(UnableToRetrieveMetadata::class);
+ $adapter->mimeType('unknown.mime-type');
}
public function testReportExceptionsForGet(): void
diff --git a/tests/Filesystem/FilesystemManagerTest.php b/tests/Filesystem/FilesystemManagerTest.php
index 90f4f481ca..ba0608017e 100644
--- a/tests/Filesystem/FilesystemManagerTest.php
+++ b/tests/Filesystem/FilesystemManagerTest.php
@@ -332,7 +332,7 @@ public function testCanBuildOnDemandDisk(): void
public function testCanSetDiskUsingEnum(): void
{
$filesystem = new FilesystemManager($this->getContainer());
- $filesystem->set(FilesystemManagerTestDisk::Local, $disk = Double::for(Filesystem::class));
+ $filesystem->set(FilesystemManagerTestDisk::Local, $disk = Double::for(Filesystem::class)->strict());
$this->assertSame($disk, $filesystem->disk('local'));
}
@@ -340,8 +340,8 @@ public function testCanSetDiskUsingEnum(): void
public function testCanForgetDiskUsingEnum(): void
{
$filesystem = $this->filesystemManagerWithLocalDisks();
- $filesystem->set('local', $local = Double::for(Filesystem::class));
- $filesystem->set('backup', $backup = Double::for(Filesystem::class));
+ $filesystem->set('local', $local = Double::for(Filesystem::class)->strict());
+ $filesystem->set('backup', $backup = Double::for(Filesystem::class)->strict());
$filesystem->forgetDisk(FilesystemManagerTestDisk::Local);
@@ -360,7 +360,7 @@ public function testCanForgetDiskUsingEnum(): void
public function testCanPurgeDiskUsingEnum(UnitEnum $name, string $key): void
{
$filesystem = $this->filesystemManagerWithLocalDisks();
- $filesystem->set($key, $local = Double::for(Filesystem::class));
+ $filesystem->set($key, $local = Double::for(Filesystem::class)->strict());
$filesystem->purge($name);
@@ -513,9 +513,9 @@ public function testScopedLocalDiskUsesItsNearestServedRouteForSignedUrls(): voi
],
]);
$expiration = new DateTimeImmutable('+5 minutes');
- $url = Double::for(UrlGenerator::class);
+ $url = Double::for(UrlGenerator::class)->strict();
$url->expects('temporarySignedRoute')
- ->with('storage.local', $expiration, ['path' => 'tenant/file.txt'], false)
+ ->with('storage.local', Argument::same($expiration), ['path' => 'tenant/file.txt'], false)
->returns('/signed/file.txt');
$url->expects('to')
->with('/signed/file.txt')
@@ -553,9 +553,9 @@ public function testNestedScopedLocalDiskUsesOriginalRoutePrefixes(): void
],
]);
$expiration = new DateTimeImmutable('+5 minutes');
- $url = Double::for(UrlGenerator::class);
+ $url = Double::for(UrlGenerator::class)->strict();
$url->expects('temporarySignedRoute')
- ->with('storage.local', $expiration, ['path' => 'tenant/documents/file.txt'], false)
+ ->with('storage.local', Argument::same($expiration), ['path' => 'tenant/documents/file.txt'], false)
->returns('/signed/file.txt');
$url->expects('to')
->with('/signed/file.txt')
@@ -611,9 +611,9 @@ public function testAnonymousScopedDiskCanUseANamedServedAncestorRoute(): void
],
]);
$expiration = new DateTimeImmutable('+5 minutes');
- $url = Double::for(UrlGenerator::class);
+ $url = Double::for(UrlGenerator::class)->strict();
$url->expects('temporarySignedRoute')
- ->with('storage.local', $expiration, ['path' => 'tenant/file.txt'], false)
+ ->with('storage.local', Argument::same($expiration), ['path' => 'tenant/file.txt'], false)
->returns('/signed/file.txt');
$url->expects('to')
->with('/signed/file.txt')
@@ -659,7 +659,7 @@ public function testScopedDiskPreservesViewBehaviorAndPoolOverrides(): void
],
]);
Container::setInstance($container);
- $exceptionHandler = Double::for(ExceptionHandler::class);
+ $exceptionHandler = Double::for(ExceptionHandler::class)->strict();
$exceptionHandler->expects('report')->with(Argument::type(UnableToWriteFile::class));
$container->instance(ExceptionHandler::class, $exceptionHandler);
$filesystem = (new FilesystemManager($container))->addPoolableDriver('local');
@@ -718,9 +718,9 @@ public function testServedOuterScopedDiskUsesItsOwnRouteWithoutAPathPrefix(): vo
],
]);
$expiration = new DateTimeImmutable('+5 minutes');
- $url = Double::for(UrlGenerator::class);
+ $url = Double::for(UrlGenerator::class)->strict();
$url->expects('temporarySignedRoute')
- ->with('storage.uploads', $expiration, ['path' => 'file.txt'], false)
+ ->with('storage.uploads', Argument::same($expiration), ['path' => 'file.txt'], false)
->returns('/signed/file.txt');
$url->expects('to')
->with('/signed/file.txt')
@@ -761,9 +761,9 @@ public function testNamedOnDemandLocalDiskUsesTheMatchingConfiguredRoute(): void
];
$container = $this->getContainer(['disks' => ['public' => $config]]);
$expiration = new DateTimeImmutable('+5 minutes');
- $url = Double::for(UrlGenerator::class);
+ $url = Double::for(UrlGenerator::class)->strict();
$url->expects('temporarySignedRoute')
- ->with('storage.public', $expiration, ['path' => 'file.txt'], false)
+ ->with('storage.public', Argument::same($expiration), ['path' => 'file.txt'], false)
->returns('/signed/file.txt');
$url->expects('to')
->with('/signed/file.txt')
@@ -1124,7 +1124,7 @@ public function testReadThroughPromotionCancellationClosesOwnedStreams(bool $wra
$temporary = null;
$cancellation = new CanceledException('promotion canceled');
$failure = $wrapped ? UnableToWriteFile::atLocation('file.txt', previous: $cancellation) : $cancellation;
- $primary = Double::for(FilesystemOperator::class);
+ $primary = Double::for(FilesystemOperator::class)->strict();
$primary->expects('fileExists')->times(2)->with('file.txt')->returns(false);
$primary->expects('writeStream')->resolves(
static function (string $path, mixed $stream) use (&$temporary, $failure): never {
@@ -1133,7 +1133,7 @@ static function (string $path, mixed $stream) use (&$temporary, $failure): never
throw $failure;
},
);
- $fallback = Double::for(FilesystemOperator::class);
+ $fallback = Double::for(FilesystemOperator::class)->strict();
$fallback->expects('readStream')->with('file.txt')->returns($source);
$adapter = new ReadThroughFilesystemAdapter($primary, $fallback);
@@ -1168,10 +1168,10 @@ static function (string $path, mixed $stream) use (&$temporary, $failure): never
public function testReadThroughPromotionPreservesWrappedCancellationForStringReads(): void
{
$failure = UnableToWriteFile::atLocation('file.txt', previous: new CanceledException);
- $primary = Double::for(FilesystemOperator::class);
+ $primary = Double::for(FilesystemOperator::class)->strict();
$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 = Double::for(FilesystemOperator::class)->strict();
$fallback->expects('read')->with('file.txt')->returns('contents');
$adapter = new ReadThroughFilesystemAdapter($primary, $fallback);
$caught = null;
@@ -1191,7 +1191,7 @@ public function testReadThroughPromotionRetainsItsStreamWhenThePrimaryClosesItsI
$filesystem = $this->readThroughFilesystemManager();
$fallback = $filesystem->disk('fallback');
$fallback->put('file.txt', 'fallback contents');
- $primary = Double::for(FilesystemOperator::class);
+ $primary = Double::for(FilesystemOperator::class)->strict();
$primary->expects('fileExists')->times(2)->with('file.txt')->returns(false);
$primary->expects('writeStream')->resolves(
function (string $path, mixed $stream) use ($fails): void {
@@ -1231,7 +1231,7 @@ public function testReadThroughFallbackTransfersAllowThePrimaryToCloseItsInput(s
$filesystem = $this->readThroughFilesystemManager();
$fallback = $filesystem->disk('fallback');
$fallback->put('source.txt', 'contents');
- $primary = Double::for(FilesystemOperator::class);
+ $primary = Double::for(FilesystemOperator::class)->strict();
$primary->expects('fileExists')->with('source.txt')->returns(false);
$primary->expects('writeStream')->resolves(
function (string $path, mixed $stream, array $config): void {
@@ -2501,12 +2501,12 @@ function (CommandInterface $command) use ($expectedAcl): Result {
]);
$disk = $filesystem->buildS3DiskForTest($client, $config);
} else {
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('upload')->with(
'contents',
Argument::satisfies(fn (array $options): bool => $options['predefinedAcl'] === $expectedAcl),
);
- $client = Double::for(GcsClient::class);
+ $client = Double::for(GcsClient::class)->strict();
$client->expects('bucket')->with('documents')->returns($bucket);
$disk = $filesystem->buildGcsDiskForTest($client, $config);
}
@@ -2547,8 +2547,8 @@ public function testGcsClientConfigSupportsFlatKeysAndTheFullExplicitSdkSurface(
public function testGcsDiskUsesTheSharedFlysystemStackConfiguration(): void
{
- $bucket = Double::for(Bucket::class);
- $client = Double::for(GcsClient::class);
+ $bucket = Double::for(Bucket::class)->strict();
+ $client = Double::for(GcsClient::class)->strict();
$client->expects('bucket')->with('documents')->returns($bucket);
$filesystem = new InspectableFilesystemManager($this->getContainer());
$disk = $filesystem->buildGcsDiskForTest($client, [
@@ -2590,8 +2590,8 @@ public function testGcsDiskUsesTheSharedFlysystemStackConfiguration(): void
public function testGcsDiskDefaultsStreamingReadsAndAllowsOptOut(): void
{
- $bucket = Double::for(Bucket::class);
- $client = Double::for(GcsClient::class);
+ $bucket = Double::for(Bucket::class)->strict();
+ $client = Double::for(GcsClient::class)->strict();
$client->expects('bucket')->times(2)->with('documents')->returns($bucket);
$filesystem = new InspectableFilesystemManager($this->getContainer());
diff --git a/tests/Filesystem/FilesystemPoolProxyTest.php b/tests/Filesystem/FilesystemPoolProxyTest.php
index 0bca434581..8c0222312a 100644
--- a/tests/Filesystem/FilesystemPoolProxyTest.php
+++ b/tests/Filesystem/FilesystemPoolProxyTest.php
@@ -295,7 +295,7 @@ function (object $filesystem) use (&$releaseCalls): void {
#[DataProvider('bufferedReadProvider')]
public function testBufferedReadsReleaseTheWholeDriverImmediately(string $uri, ?int $start, ?int $end, string $expected): void
{
- $driver = Double::for(FilesystemOperator::class);
+ $driver = Double::for(FilesystemOperator::class)->strict();
$driver->expects('readStream')->with('file.txt')->resolves(static function () use ($uri): mixed {
$stream = fopen($uri, 'w+b');
fwrite($stream, '0123456789');
@@ -342,7 +342,7 @@ public function testCachedLiveRangeKeepsTheWholeDriverBorrowedUntilClose(): void
return ++$reads === 1 ? 'remote bytes' : false;
});
$range = StreamWrapper::getResource(new LimitStream(new CachingStream($source), 3));
- $driver = Double::for(FilesystemOperator::class);
+ $driver = Double::for(FilesystemOperator::class)->strict();
$driver->expects('readStream')->with('file.txt')->returns($range);
$proxy = $this->proxy(fn (): FilesystemAdapter => new FilesystemAdapter($driver, $this->adapter));
$stream = $proxy->readStream('file.txt');
@@ -457,7 +457,7 @@ public function testUnknownMethodsAreRejectedInsteadOfDynamicallyForwarded(): vo
public function testContractOnlyFilesystemPoolsWhenCallbacksAreUnset(): void
{
- $filesystem = Double::for(FilesystemContract::class);
+ $filesystem = Double::for(FilesystemContract::class)->strict();
$filesystem->expects('exists')->with('file.txt')->returns(true);
$proxy = $this->proxy(static fn (): FilesystemContract => $filesystem);
@@ -468,7 +468,7 @@ public function testContractOnlyFilesystemPoolsWhenCallbacksAreUnset(): void
public function testSettingCallbacksOnAContractOnlyFilesystemFailsAndDiscardsIt(): void
{
- $filesystem = Double::for(FilesystemContract::class);
+ $filesystem = Double::for(FilesystemContract::class)->strict();
$proxy = $this->proxy(static fn (): FilesystemContract => $filesystem);
$proxy->buildTemporaryUrlsUsing(static fn (): string => 'url');
diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php
index 2f1a24417f..ca33275645 100755
--- a/tests/Filesystem/FilesystemTest.php
+++ b/tests/Filesystem/FilesystemTest.php
@@ -797,9 +797,9 @@ public function testRelativeLinkThrowsWhenLinkCreationFails(): void
public function testRelativeLinkAcceptsTheWindowsNullResult(): void
{
- (new StubLinkFilesystem(null))->relativeLink('/root/target.txt', '/root/link.txt');
+ $this->expectNotToPerformAssertions();
- $this->addToAssertionCount(1);
+ (new StubLinkFilesystem(null))->relativeLink('/root/target.txt', '/root/link.txt');
}
public function testNameReturnsName(): void
diff --git a/tests/Filesystem/GoogleCloudStorageAdapterTest.php b/tests/Filesystem/GoogleCloudStorageAdapterTest.php
index 5c58bb9538..0a5d5ec5b7 100644
--- a/tests/Filesystem/GoogleCloudStorageAdapterTest.php
+++ b/tests/Filesystem/GoogleCloudStorageAdapterTest.php
@@ -116,7 +116,7 @@ public function testReadThroughPromotionRetainsItsStreamAfterGoogleUploads(bool
$source = fopen('php://temp', 'w+b');
fwrite($source, 'fallback contents');
rewind($source);
- $fallback = Double::for(FilesystemOperator::class);
+ $fallback = Double::for(FilesystemOperator::class)->strict();
$fallback->expects('readStream')->with('file.txt')->returns($source);
$adapter = new ReadThroughFilesystemAdapter($primary, $fallback);
$stream = null;
@@ -140,7 +140,7 @@ public function testReadThroughPromotionRetainsItsStreamAfterGoogleUploads(bool
public function testUrlUsesTheConfiguredApiUriOrBucketEndpoint(): void
{
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$path = 'nested/report%2F v?x#y+z.txt';
$encodedPath = 'nested/report%252F%20v%3Fx%23y%2Bz.txt';
@@ -161,7 +161,7 @@ public function testUrlUsesTheConfiguredApiUriOrBucketEndpoint(): void
public function testReadStreamRangeSendsANativeRangeHeaderForThePrefixedObject(): void
{
$stream = Utils::streamFor('range-body');
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')
->with([
'restOptions' => [
@@ -170,9 +170,9 @@ public function testReadStreamRangeSendsANativeRangeHeaderForThePrefixedObject()
],
])
->returns($stream);
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('tenant/file.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, [
'bucket' => 'bucket',
@@ -189,16 +189,16 @@ public function testReadStreamRangeSendsANativeRangeHeaderForThePrefixedObject()
public function testReadStreamRangeSupportsOpenAndSuffixRangesWithoutForcingStreaming(): void
{
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')
->with(['restOptions' => ['headers' => ['Range' => 'bytes=3-']]])
->returns(Utils::streamFor('open'));
$object->expects('downloadAsStream')
->with(['restOptions' => ['headers' => ['Range' => 'bytes=-3']]])
->returns(Utils::streamFor('suffix'));
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->times(2)->with('file.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->times(2)->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, [
'bucket' => 'bucket',
@@ -217,13 +217,13 @@ public function testReadStreamRangeSupportsOpenAndSuffixRangesWithoutForcingStre
public function testReadStreamRangeWithoutBoundsDelegatesToTheFullStream(): void
{
$body = Utils::streamFor('full-body');
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')
->with(['restOptions' => ['stream' => true]])
->returns($body);
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('file.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, ['bucket' => 'bucket']);
@@ -240,13 +240,13 @@ public function testReadStreamDefaultsToLazyCoroutineSafeStreaming(): void
$this->assertIsArray($sockets);
[$reader, $writer] = $sockets;
$this->assertTrue(stream_set_timeout($reader, 1));
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')
->with(['restOptions' => ['stream' => true]])
->returns(Utils::streamFor($reader));
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('file.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, ['bucket' => 'bucket']);
$stream = null;
@@ -292,11 +292,11 @@ public function testReadStreamRangeRejectsInvalidArgumentsBeforeClientIo(): void
public function testReadStreamRangeWrapsClientFailures(): void
{
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')->throws(new RuntimeException('GCS failed'));
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('file.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, ['bucket' => 'bucket', 'throw' => true]);
@@ -314,14 +314,14 @@ public function testReadStreamRangePreservesCancellationWithoutReporting(bool $w
{
$cancellation = new CanceledException('read canceled');
$failure = $wrapped ? new ServiceException('SDK request canceled.', 0, $cancellation) : $cancellation;
- $exceptionHandler = Double::for(ExceptionHandler::class);
+ $exceptionHandler = Double::for(ExceptionHandler::class)->strict();
$exceptionHandler->expects('report')->never();
Container::getInstance()->bind(ExceptionHandler::class, static fn () => $exceptionHandler);
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')->throws($failure);
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('file.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, [
'bucket' => 'bucket',
@@ -343,14 +343,14 @@ public function testReadStreamRangePreservesCancellationWithoutReporting(bool $w
public function testReadStreamRangeRejectsAResultWithoutAResourceWhenConfigured(): void
{
- $stream = Double::for(StreamInterface::class);
+ $stream = Double::for(StreamInterface::class)->strict();
$stream->allows('isReadable')->returns(false);
$stream->allows('isWritable')->returns(false);
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')->returns($stream);
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('file.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, ['bucket' => 'bucket', 'throw' => true]);
@@ -362,12 +362,12 @@ public function testReadStreamRangeRejectsAResultWithoutAResourceWhenConfigured(
public function testReadFailuresReturnNullWhenExceptionsAreDisabled(): void
{
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')->times(2)->throws(new RuntimeException('GCS failed'));
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('plain.txt')->returns($object);
$bucket->expects('object')->with('range.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->times(2)->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, ['bucket' => 'bucket']);
@@ -379,11 +379,11 @@ public function testNonResourceReturnsNullWhenExceptionsAreDisabled(): void
{
$stream = Utils::streamFor('contents');
fclose($stream->detach());
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')->returns($stream);
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('file.txt')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, ['bucket' => 'bucket']);
@@ -401,11 +401,11 @@ public function testDecodedReadStreamPreservesCancellationAndClosesItsBody(bool
$body = new InflateBodyStream($cancel
? new PumpStream(static fn () => throw $failure)
: Utils::streamFor($native));
- $object = Double::for(StorageObject::class);
+ $object = Double::for(StorageObject::class)->strict();
$object->expects('downloadAsStream')->returns($body);
- $bucket = Double::for(Bucket::class);
+ $bucket = Double::for(Bucket::class)->strict();
$bucket->expects('object')->with('file.gz')->returns($object);
- $client = Double::for(StorageClient::class);
+ $client = Double::for(StorageClient::class)->strict();
$client->expects('bucket')->with('bucket')->returns($bucket);
$adapter = $this->adapter($client, ['bucket' => 'bucket']);
$resource = $adapter->readStream('file.gz');
@@ -441,8 +441,8 @@ public function testDecodedReadStreamPreservesCancellationAndClosesItsBody(bool
private function adapter(StorageClient $client, array $config): GoogleCloudStorageAdapter
{
return new GoogleCloudStorageAdapter(
- Double::for(FilesystemOperator::class),
- Double::for(FlysystemGoogleCloudAdapter::class),
+ Double::for(FilesystemOperator::class)->strict(),
+ Double::for(FlysystemGoogleCloudAdapter::class)->strict(),
$config,
$client,
);
diff --git a/tests/Filesystem/LeasedStreamTest.php b/tests/Filesystem/LeasedStreamTest.php
index 55bd09f6a0..52b82a38b3 100644
--- a/tests/Filesystem/LeasedStreamTest.php
+++ b/tests/Filesystem/LeasedStreamTest.php
@@ -15,6 +15,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
use stdClass;
use Swoole\Coroutine\CanceledException;
@@ -175,8 +176,8 @@ public function testReleaseFailureDuringCloseIsReportedAndSwallowed(): void
$container = new Container;
Container::setInstance($container);
$failure = new RuntimeException('release cleanup failed');
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($failure);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($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 63d224421d..486816fa1c 100644
--- a/tests/Filesystem/ScopedFilesystemProxyTest.php
+++ b/tests/Filesystem/ScopedFilesystemProxyTest.php
@@ -21,6 +21,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use League\Flysystem\CorruptedPathDetected;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemOperator;
@@ -72,9 +73,9 @@ public function testTransfersUseContractMethodsAndResolveSourceOnce(string $meth
$stream = fopen('php://temp', 'w+b');
fwrite($stream, 'contents');
rewind($stream);
- $source = Double::for(FilesystemContract::class);
+ $source = Double::for(FilesystemContract::class)->strict();
$source->expects('readStream')->with('tenant/file.txt')->returns($stream);
- $destination = $sameDisk ? $source : Double::for(FilesystemContract::class);
+ $destination = $sameDisk ? $source : Double::for(FilesystemContract::class)->strict();
$destination->expects('writeStream')
->with(($sameDisk ? 'tenant/' : '') . ($to ?? 'file.txt'), $stream)->returns(true);
@@ -194,7 +195,7 @@ public static function mappedMethodProvider(): array
'json' => ['json', ['file.json', JSON_THROW_ON_ERROR], ['tenant/file.json', JSON_THROW_ON_ERROR], ['ok' => true], ['ok' => true]],
'json scalar' => ['json', ['value.json'], ['tenant/value.json', 0], 'value', 'value'],
'response' => ['response', ['file.txt', 'name.txt', ['X-Test' => 'yes'], 'attachment'], ['tenant/file.txt', 'name.txt', ['X-Test' => 'yes'], 'attachment'], $streamedResponse, $streamedResponse],
- 'serve' => ['serve', [$request, 'file.txt', 'name.txt', ['X-Test' => 'yes']], [$request, 'tenant/file.txt', 'name.txt', ['X-Test' => 'yes']], $response, $response],
+ 'serve' => ['serve', [$request, 'file.txt', 'name.txt', ['X-Test' => 'yes']], [Argument::same($request), 'tenant/file.txt', 'name.txt', ['X-Test' => 'yes']], $response, $response],
'download' => ['download', ['file.txt', 'name.txt', ['X-Test' => 'yes']], ['tenant/file.txt', 'name.txt', ['X-Test' => 'yes']], $streamedResponse, $streamedResponse],
'put boolean' => ['put', ['file.txt', 'contents', ['visibility' => 'private']], ['tenant/file.txt', 'contents', ['visibility' => 'private']], true, true],
'put stored path' => ['put', ['file.txt', 'contents'], ['tenant/file.txt', 'contents', []], 'tenant/stored.txt', 'stored.txt'],
@@ -211,8 +212,8 @@ public static function mappedMethodProvider(): array
'mimeType' => ['mimeType', ['file.txt'], ['tenant/file.txt'], 'text/plain', 'text/plain'],
'lastModified' => ['lastModified', ['file.txt'], ['tenant/file.txt'], 123, 123],
'readStreamRange' => ['readStreamRange', ['file.txt', 2, 4], ['tenant/file.txt', 2, 4], null, null],
- 'temporaryUrl' => ['temporaryUrl', ['file.txt', $expiration, ['option' => true]], ['tenant/file.txt', $expiration, ['option' => true]], 'https://temporary', 'https://temporary'],
- 'temporaryUploadUrl' => ['temporaryUploadUrl', ['file.txt', $expiration, ['option' => true]], ['tenant/file.txt', $expiration, ['option' => true]], ['url' => 'https://upload'], ['url' => 'https://upload']],
+ 'temporaryUrl' => ['temporaryUrl', ['file.txt', $expiration, ['option' => true]], ['tenant/file.txt', Argument::same($expiration), ['option' => true]], 'https://temporary', 'https://temporary'],
+ 'temporaryUploadUrl' => ['temporaryUploadUrl', ['file.txt', $expiration, ['option' => true]], ['tenant/file.txt', Argument::same($expiration), ['option' => true]], ['url' => 'https://upload'], ['url' => 'https://upload']],
'files at root' => ['files', [], ['tenant', false], ['tenant/a.txt', 'tenant/dir/b.txt'], ['a.txt', 'dir/b.txt']],
'files recursive' => ['files', ['dir', true], ['tenant/dir', true], ['tenant/dir/a.txt'], ['dir/a.txt']],
'allFiles' => ['allFiles', ['dir'], ['tenant/dir'], ['tenant/dir/a.txt'], ['dir/a.txt']],
@@ -230,9 +231,9 @@ public static function mappedMethodProvider(): array
private function expectInnerCall(string $method, array $arguments, mixed $result): FilesystemAdapter
{
if (method_exists(FilesystemAdapter::class, $method)) {
- $inner = $target = Double::for(FilesystemAdapter::class);
+ $inner = $target = Double::for(FilesystemAdapter::class)->strict();
} else {
- $target = Double::for(FilesystemOperator::class);
+ $target = Double::for(FilesystemOperator::class)->strict();
$inner = new FilesystemAdapter($target, $this->disk->getAdapter());
}
@@ -278,7 +279,7 @@ public function testFlysystemMethodsAndConditionableUseTheScopedBoundary(): void
public function testReadAndWriteStreamsAreMappedWithoutConsumingDeferredResults(): void
{
- $inner = Double::for(FilesystemAdapter::class);
+ $inner = Double::for(FilesystemAdapter::class)->strict();
$readStream = fopen('php://temp', 'r+');
$writeStream = fopen('php://temp', 'r+');
$this->assertIsResource($readStream);
@@ -306,12 +307,12 @@ public function testPutFileOverloadsPrefixAndStripReturnedPaths(): void
$path = $this->tempDir . '/upload.txt';
file_put_contents($path, 'upload');
$upload = new UploadedFile($path, 'upload.txt', test: true);
- $inner = Double::for(FilesystemAdapter::class);
+ $inner = Double::for(FilesystemAdapter::class)->strict();
$inner->expects('putFile')
- ->with('tenant', $upload, [])
+ ->with('tenant', Argument::same($upload), [])
->returns('tenant/generated.txt');
$inner->expects('putFileAs')
- ->with('tenant/named.txt', $upload, '', [])
+ ->with('tenant/named.txt', Argument::same($upload), '', [])
->returns('tenant/named.txt');
$prefixCalls = 0;
$proxy = new ScopedFilesystemProxy($inner, function () use (&$prefixCalls): string {
@@ -347,7 +348,7 @@ public function testPutFileAsRejectsFinalTargetEscapeBeforeWriting(): void
public function testImageCapturesTheNormalizedPrefixAndResolvedDiskBeforeLazyReading(): void
{
$readCalls = 0;
- $first = Double::for(FilesystemContract::class);
+ $first = Double::for(FilesystemContract::class)->strict();
$first->expects('get')
->with('tenants/first/photo.jpg')
->resolves(function () use (&$readCalls): string {
@@ -355,7 +356,7 @@ public function testImageCapturesTheNormalizedPrefixAndResolvedDiskBeforeLazyRea
return 'first image';
});
- $second = Double::for(FilesystemContract::class);
+ $second = Double::for(FilesystemContract::class)->strict();
$second->expects('get')->never();
$currentDisk = $first;
$currentPrefix = 'tenants/first/images/..';
@@ -411,7 +412,7 @@ public function testImageHonorsExplicitRootPassthrough(): void
public function testMissingImageReportsOnlyTheCallerPath(): void
{
- $inner = Double::for(FilesystemContract::class);
+ $inner = Double::for(FilesystemContract::class)->strict();
$inner->expects('get')->with('secret-tenant/missing.jpg')->returns(null);
$proxy = new ScopedFilesystemProxy($inner, static fn (): string => 'secret-tenant');
$image = $proxy->image('missing.jpg');
@@ -430,7 +431,7 @@ public function testMissingImageReportsOnlyTheCallerPath(): void
public function testNoPathMethodsDoNotResolveThePrefix(): void
{
- $inner = Double::for(FilesystemAdapter::class);
+ $inner = Double::for(FilesystemAdapter::class)->strict();
$inner->expects('providesTemporaryUrls')->returns(true);
$inner->expects('providesTemporaryUploadUrls')->returns(false);
$inner->expects('getConfig')->returns(['driver' => 'local']);
@@ -446,7 +447,7 @@ public function testNoPathMethodsDoNotResolveThePrefix(): void
public function testNoPathMethodsResolveTheDiskOncePerCallWithoutResolvingThePrefix(): void
{
- $inner = Double::for(FilesystemAdapter::class);
+ $inner = Double::for(FilesystemAdapter::class)->strict();
$inner->expects('providesTemporaryUrls')->returns(true);
$inner->expects('providesTemporaryUploadUrls')->returns(false);
$inner->expects('getConfig')->returns(['driver' => 'local']);
@@ -468,7 +469,7 @@ function () use ($inner, &$diskCalls): FilesystemContract {
public function testEveryAssertionMapsPathsAndReturnsTheScopedProxy(): void
{
- $inner = Double::for(FilesystemAdapter::class);
+ $inner = Double::for(FilesystemAdapter::class)->strict();
$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);
@@ -548,7 +549,7 @@ public function testPrefixTraversalIsRejected(): void
public function testInternalTraversalNormalizesWhilePercentEncodingRemainsLiteral(): void
{
- $inner = Double::for(FilesystemAdapter::class);
+ $inner = Double::for(FilesystemAdapter::class)->strict();
$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');
@@ -560,7 +561,7 @@ public function testInternalTraversalNormalizesWhilePercentEncodingRemainsLitera
#[DataProvider('foreignReturnedPathProvider')]
public function testReturnedPathsOutsideTheNormalizedPrefixFailClosed(string $returned): void
{
- $inner = Double::for(FilesystemAdapter::class);
+ $inner = Double::for(FilesystemAdapter::class)->strict();
$inner->expects('files')->with('tenant', false)->returns([$returned]);
$proxy = new ScopedFilesystemProxy($inner, static fn (): string => 'tenant');
@@ -604,9 +605,9 @@ function () use ($proxy): void {
public function testDiskIsResolvedPerOperation(): void
{
- $first = Double::for(FilesystemContract::class);
+ $first = Double::for(FilesystemContract::class)->strict();
$first->expects('get')->with('tenant/file.txt')->returns('first');
- $second = Double::for(FilesystemContract::class);
+ $second = Double::for(FilesystemContract::class)->strict();
$second->expects('get')->with('tenant/file.txt')->returns('second');
$current = $first;
$diskCalls = 0;
@@ -717,7 +718,7 @@ public function testUnknownMethodsAndUnsupportedInnerCapabilitiesAreRejected():
$this->assertStringContainsString('unmapped calls could bypass', $exception->getMessage());
}
- $inner = Double::for(FilesystemContract::class);
+ $inner = Double::for(FilesystemContract::class)->strict();
$proxy = new ScopedFilesystemProxy($inner, static fn (): string => 'tenant');
$this->expectException(BadMethodCallException::class);
@@ -756,7 +757,7 @@ function () use (&$diskCalls): FilesystemContract {
public function testResolvedDiskWithoutMappedCapabilityIsRejected(): void
{
- $inner = Double::for(FilesystemContract::class);
+ $inner = Double::for(FilesystemContract::class)->strict();
$proxy = new ScopedFilesystemProxy(
static fn (): FilesystemContract => $inner,
static fn (): string => 'tenant',
@@ -770,7 +771,7 @@ public function testResolvedDiskWithoutMappedCapabilityIsRejected(): void
public function testCloudVariantMapsUrlAndResolvesPrefixOnce(): void
{
- $inner = Double::for(Cloud::class);
+ $inner = Double::for(Cloud::class)->strict();
$inner->expects('url')->with('tenant/file.txt')->returns('https://example.test/file.txt');
$prefixCalls = 0;
$proxy = new ScopedCloudFilesystemProxy($inner, function () use (&$prefixCalls): string {
@@ -785,7 +786,7 @@ public function testCloudVariantMapsUrlAndResolvesPrefixOnce(): void
public function testCloudVariantResolvesTheDiskOnce(): void
{
- $inner = Double::for(Cloud::class);
+ $inner = Double::for(Cloud::class)->strict();
$inner->expects('url')->with('tenant/file.txt')->returns('https://example.test/file.txt');
$diskCalls = 0;
$proxy = new ScopedCloudFilesystemProxy(
@@ -804,7 +805,7 @@ function () use ($inner, &$diskCalls): Cloud {
public function testCloudVariantInheritsLazyImageScoping(): void
{
$readCalls = 0;
- $inner = Double::for(Cloud::class);
+ $inner = Double::for(Cloud::class)->strict();
$inner->expects('get')
->with('tenant/photo.jpg')
->resolves(function () use (&$readCalls): string {
@@ -823,7 +824,7 @@ public function testCloudVariantInheritsLazyImageScoping(): void
public function testCloudVariantRejectsANonCloudResolvedDisk(): void
{
- $inner = Double::for(FilesystemContract::class);
+ $inner = Double::for(FilesystemContract::class)->strict();
$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 93724133a2..8cd80a8949 100644
--- a/tests/Fortify/Console/InstallCommandTest.php
+++ b/tests/Fortify/Console/InstallCommandTest.php
@@ -172,7 +172,7 @@ public function testInstallCommandStopsAfterPublishedFileReplacementFails(): voi
$laterFile = $this->publishedSupportFiles()[1];
(new Filesystem)->replace($laterFile, 'strict();
$files->expects('replace')->throws(new RuntimeException('replace failed'));
$this->app->instance(Filesystem::class, $files);
diff --git a/tests/Fortify/FortifyApiTest.php b/tests/Fortify/FortifyApiTest.php
index 2e67474c63..b46e2ace4c 100644
--- a/tests/Fortify/FortifyApiTest.php
+++ b/tests/Fortify/FortifyApiTest.php
@@ -199,7 +199,7 @@ public function testConfirmPasswordDispatchesThroughProtectedCustomCallbackMetho
$action = new FortifyApiConfirmPassword;
- $this->assertTrue($action(Double::for(StatefulGuard::class), new User, 'secret'));
+ $this->assertTrue($action(Double::for(StatefulGuard::class)->strict(), new User, 'secret'));
$this->assertTrue($action->customCallbackInvoked);
}
diff --git a/tests/Fortify/FortifyServiceProviderTest.php b/tests/Fortify/FortifyServiceProviderTest.php
index 3a1a85cbc8..5240161a98 100644
--- a/tests/Fortify/FortifyServiceProviderTest.php
+++ b/tests/Fortify/FortifyServiceProviderTest.php
@@ -71,7 +71,7 @@ public function toResponse(Request $request): Response
public function testNamedViewsReceiveTheRequest(): void
{
- $factory = Double::for(ResponseFactory::class);
+ $factory = Double::for(ResponseFactory::class)->strict();
$factory->expects('view')->with('auth.login', Argument::satisfies(
static fn (array $parameters): bool => $parameters['request'] instanceof Request,
))->returns(new HttpResponse('Login'));
@@ -263,7 +263,7 @@ public function testRecoveryCodeGenerationCanBeCustomized(): void
public function testActionsCanBeRegisteredWithNonClosureCallables(): void
{
- $creator = Double::for(CreatesNewUsers::class);
+ $creator = Double::for(CreatesNewUsers::class)->strict();
Fortify::createUsersUsing(new class($creator) {
public function __construct(
diff --git a/tests/Fortify/NewPasswordControllerTest.php b/tests/Fortify/NewPasswordControllerTest.php
index a623c92f65..113c617f1f 100644
--- a/tests/Fortify/NewPasswordControllerTest.php
+++ b/tests/Fortify/NewPasswordControllerTest.php
@@ -94,7 +94,7 @@ public function testPasswordResetCanFailWithJson(): void
public function testPasswordCanBeResetWithCustomizedEmailAddressField(): void
{
$this->app->make('config')->set('fortify.email', 'emailAddress');
- Password::shouldReceive('broker')->andReturn($broker = Double::for(PasswordBroker::class));
+ Password::shouldReceive('broker')->andReturn($broker = Double::for(PasswordBroker::class)->strict());
$user = User::forceCreate(UserFactory::new()->raw());
$rememberToken = $user->remember_token;
diff --git a/tests/Fortify/PasswordResetLinkRequestControllerTest.php b/tests/Fortify/PasswordResetLinkRequestControllerTest.php
index 25ebcf614f..f7bc4f6d04 100644
--- a/tests/Fortify/PasswordResetLinkRequestControllerTest.php
+++ b/tests/Fortify/PasswordResetLinkRequestControllerTest.php
@@ -78,7 +78,7 @@ public function testResetLinkRequestCanFailWithJson(): void
public function testResetLinkCanBeSuccessfullyRequestedWithCustomizedEmailField(): void
{
$this->app->make('config')->set('fortify.email', 'emailAddress');
- Password::shouldReceive('broker')->andReturn($broker = Double::for(PasswordBroker::class));
+ Password::shouldReceive('broker')->andReturn($broker = Double::for(PasswordBroker::class)->strict());
$broker->expects('sendResetLink')->returns(Password::RESET_LINK_SENT);
diff --git a/tests/Fortify/TwoFactorAuthenticationProviderTest.php b/tests/Fortify/TwoFactorAuthenticationProviderTest.php
index 24ef75a487..9ab6c36c2d 100644
--- a/tests/Fortify/TwoFactorAuthenticationProviderTest.php
+++ b/tests/Fortify/TwoFactorAuthenticationProviderTest.php
@@ -130,7 +130,7 @@ public function testReplayCacheKeyIncludesSecretAndCode(): void
$secondKey = 'fortify.2fa_codes.' . hash('xxh128', $secondSecret . '|' . $code);
$timecode = intdiv(self::TIMESTAMP, TOTPInterface::DEFAULT_PERIOD);
$ttl = 90;
- $cache = Double::for(CacheRepositoryContract::class);
+ $cache = Double::for(CacheRepositoryContract::class)->strict();
$this->assertSame($code, $this->codeAt($secondSecret, self::TIMESTAMP));
$this->assertNotSame($firstKey, $secondKey);
@@ -169,7 +169,7 @@ public function testReplayCacheTtlCoversFullAcceptedWindow(): void
foreach ([0 => 30, 1 => 90, 2 => 150] as $window => $ttl) {
Features::twoFactorAuthentication(['window' => $window]);
- $cache = Double::for(CacheRepositoryContract::class);
+ $cache = Double::for(CacheRepositoryContract::class)->strict();
$key = 'fortify.2fa_codes.' . hash('xxh128', self::SECRET . '|' . $this->codeAt(self::SECRET, self::TIMESTAMP));
$timecode = intdiv(self::TIMESTAMP, TOTPInterface::DEFAULT_PERIOD);
diff --git a/tests/Foundation/Auth/EmailVerificationRequestTest.php b/tests/Foundation/Auth/EmailVerificationRequestTest.php
index e528ae22fa..c63f84277c 100644
--- a/tests/Foundation/Auth/EmailVerificationRequestTest.php
+++ b/tests/Foundation/Auth/EmailVerificationRequestTest.php
@@ -79,7 +79,7 @@ public function testFulfillDispatchesEventForUserUsingOnlyTheVerificationTrait()
{
Event::fake([Verified::class]);
- $user = Double::for(User::class);
+ $user = Double::for(User::class)->strict();
$user->allows('getKey')->returns(123);
$user->allows('getAuthIdentifier')->returns(123);
$user->allows('getEmailForVerification')->returns('user@example.com');
@@ -143,7 +143,7 @@ public function testRulesReturnsEmptyArray(): void
*/
private function mockUser(int|string $id, string $email): Authenticatable&MustVerifyEmail
{
- $user = Double::for(EmailVerificationUser::class);
+ $user = Double::for(EmailVerificationUser::class)->strict();
$user->allows('getKey')->returns($id);
$user->allows('getAuthIdentifier')->returns($id);
$user->allows('getEmailForVerification')->returns($email);
diff --git a/tests/Foundation/Bootstrap/HandleExceptionsTest.php b/tests/Foundation/Bootstrap/HandleExceptionsTest.php
index 75f1b44b77..59e32300d2 100644
--- a/tests/Foundation/Bootstrap/HandleExceptionsTest.php
+++ b/tests/Foundation/Bootstrap/HandleExceptionsTest.php
@@ -231,7 +231,7 @@ public function testNullValueAsChannelUsesNullDriver(): void
public function testMissingDeprecationOptionsUseTheNullChannelWithoutATrace(): void
{
- $logger = Double::for(LogManager::class);
+ $logger = Double::for(LogManager::class)->strict();
$this->app->instance(LogManager::class, $logger);
$this->config->set('logging.deprecations', []);
@@ -261,7 +261,7 @@ public function testMissingDeprecationOptionsUseTheNullChannelWithoutATrace(): v
#[DataProvider('invalidDeprecationConfigurationProvider')]
public function testInvalidDeprecationConfigurationFailsLoudly(mixed $configuration, string $key): void
{
- $this->app->instance(LogManager::class, Double::for(LogManager::class));
+ $this->app->instance(LogManager::class, Double::for(LogManager::class)->strict());
$this->config->set('logging.deprecations', $configuration);
$this->expectException(InvalidArgumentException::class);
@@ -391,7 +391,7 @@ public function testDoNotOverrideExistingNullLogDriver(): void
public function testDeprecationsDriverIsDerivedAgainFromTheRebuiltConfiguration(): void
{
- $logger = Double::for(LogManager::class);
+ $logger = Double::for(LogManager::class)->strict();
$this->app->instance(LogManager::class, $logger);
$logger->expects('channel')->with('deprecations')->returns($logger);
@@ -430,7 +430,7 @@ public function testNoDeprecationsDriverIfNoDeprecationsHereSend(): void
public function testErrors(): void
{
- $logger = Double::for(LogManager::class);
+ $logger = Double::for(LogManager::class)->strict();
$this->app->instance(LogManager::class, $logger);
$logger->expects('channel')->never();
@@ -466,7 +466,7 @@ public function testConsoleThrowableRendersToStandardError(): void
{
$exception = new RuntimeException('Test exception');
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('renderForConsole')->with(
Argument::satisfies(function (mixed $output): bool {
if (! $output instanceof StreamOutput) {
@@ -486,7 +486,7 @@ public function testConsoleThrowableRendersToStandardError(): void
public function testNonConsoleExceptionIsReportedWithoutRenderingAResponse(): void
{
$exception = new RuntimeException('uncaught coroutine failure');
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->with(Argument::same($exception));
$handler->expects('render')->never();
$handler->expects('renderForConsole')->never();
@@ -506,7 +506,7 @@ public function testNonConsoleReporterFailureFallsBackToThePhpErrorLog(): void
$errorLog = $directory . '/php-error.log';
$previousErrorLog = ini_set('error_log', $errorLog);
$exception = new RuntimeException('uncaught coroutine failure');
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->with(Argument::same($exception))->throws(new Error('reporting failed'));
$handler->expects('render')->never();
$handler->expects('renderForConsole')->never();
@@ -533,7 +533,7 @@ public function testNonConsoleReporterFailureFallsBackToThePhpErrorLog(): void
public function testIgnoresDeprecationsUntilConfigurationIsBound(): void
{
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$this->app = $app->instance();
$app->expects('hasBeenBootstrapped')->returns(true);
$app->expects('runningUnitTests')->returns(false);
@@ -551,7 +551,12 @@ public function testIgnoresDeprecationsUntilConfigurationIsBound(): void
#[TestWith([Error::class])]
public function testIgnoreDeprecationIfLoggerUnresolvable(string $exceptionClass): void
{
- $this->app->bind(LogManager::class, static fn (): never => throw new $exceptionClass);
+ $attempted = false;
+ $this->app->bind(LogManager::class, static function () use ($exceptionClass, &$attempted): never {
+ $attempted = true;
+
+ throw new $exceptionClass;
+ });
$this->handleExceptions()->handleError(
E_DEPRECATED,
@@ -560,14 +565,14 @@ public function testIgnoreDeprecationIfLoggerUnresolvable(string $exceptionClass
17
);
- $this->assertTrue(true);
+ $this->assertTrue($attempted);
}
public function testIgnoreDeprecationIfLoggingFails(): void
{
// The real LogManager turns channel creation failures into its emergency
// logger, so the mock is what reaches the handler's own failure guard.
- $logger = Double::for(LogManager::class);
+ $logger = Double::for(LogManager::class)->strict();
$this->app->instance(LogManager::class, $logger);
$logger->expects('channel')->with('deprecations')->throws(new Error('Class "Monolog\Logger" not found'));
@@ -806,7 +811,7 @@ public function testReleaseLeavesHandlersAndSettingsChangedAfterTheApplication()
*/
protected function bootstrappableApplication(bool $testing = true): Application
{
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->allows('environment')->with('testing')->returns($testing);
return $app->instance();
diff --git a/tests/Foundation/Bootstrap/RegisterFacadesTest.php b/tests/Foundation/Bootstrap/RegisterFacadesTest.php
index 91a8ae9298..83a3f70d6a 100644
--- a/tests/Foundation/Bootstrap/RegisterFacadesTest.php
+++ b/tests/Foundation/Bootstrap/RegisterFacadesTest.php
@@ -20,14 +20,14 @@ class RegisterFacadesTest extends TestCase
// only explicit facade aliases.
public function testRegisterAliases(): void
{
- $config = Double::for(Repository::class);
+ $config = Double::for(Repository::class)->strict();
$config->expects('array')
->with('app.aliases')
->returns([
'FooAlias' => 'FooClass',
]);
- $manifest = Double::for(PackageManifest::class);
+ $manifest = Double::for(PackageManifest::class)->strict();
$manifest->expects('aliases')
->returns([
'TestAlias' => 'TestClass',
diff --git a/tests/Foundation/Bootstrap/RegisterProvidersTest.php b/tests/Foundation/Bootstrap/RegisterProvidersTest.php
index 38a607750c..9fb5796dac 100644
--- a/tests/Foundation/Bootstrap/RegisterProvidersTest.php
+++ b/tests/Foundation/Bootstrap/RegisterProvidersTest.php
@@ -21,7 +21,7 @@ class RegisterProvidersTest extends TestCase
public function testRegisterProviders(): void
{
$mergedProviders = null;
- $config = Double::for(Repository::class);
+ $config = Double::for(Repository::class)->strict();
$config->expects('array')
->times(2)
->with('app.providers')
@@ -33,7 +33,7 @@ public function testRegisterProviders(): void
->resolves(function (string $key, array $value) use (&$mergedProviders) {
$mergedProviders = $value;
});
- $manifest = Double::for(PackageManifest::class);
+ $manifest = Double::for(PackageManifest::class)->strict();
$manifest->expects('providers')
->returns([
TestOneServiceProvider::class,
diff --git a/tests/Foundation/Configuration/MiddlewareTest.php b/tests/Foundation/Configuration/MiddlewareTest.php
index 63d33c1062..f222e4adb2 100644
--- a/tests/Foundation/Configuration/MiddlewareTest.php
+++ b/tests/Foundation/Configuration/MiddlewareTest.php
@@ -10,8 +10,10 @@
use Hypervel\Contracts\Foundation\Application;
use Hypervel\Cookie\Middleware\EncryptCookies;
use Hypervel\Encryption\Encrypter;
+use Hypervel\Events\Dispatcher;
use Hypervel\Foundation\Application as FoundationApplication;
use Hypervel\Foundation\Configuration\Middleware;
+use Hypervel\Foundation\Http\Kernel;
use Hypervel\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
use Hypervel\Foundation\Http\Middleware\PreventRequestForgery;
use Hypervel\Foundation\Http\Middleware\PreventRequestsDuringMaintenance;
@@ -598,14 +600,9 @@ public function testStatefulApiAddsEnsureFrontendRequestsAreStateful(): void
public function testDefaultMiddlewarePriority(): void
{
- $kernel = new \Hypervel\Foundation\Http\Kernel(
- Double::for(Application::class, override: true)->instance(),
- Double::for(Router::class)
- );
+ $kernel = $this->makeKernel();
- $reflection = new ReflectionClass($kernel);
- $property = $reflection->getProperty('middlewarePriority');
- $priority = $property->getValue($kernel);
+ $priority = $kernel->getMiddlewarePriority();
$this->assertSame([
\Hypervel\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
@@ -624,10 +621,7 @@ public function testDefaultMiddlewarePriority(): void
public function testWithMiddlewareAppliesPriorityToKernel(): void
{
- $kernel = new \Hypervel\Foundation\Http\Kernel(
- Double::for(Application::class, override: true)->instance(),
- Double::for(Router::class)
- );
+ $kernel = $this->makeKernel();
$middleware = new Middleware;
$middleware->priority([
@@ -638,22 +632,16 @@ public function testWithMiddlewareAppliesPriorityToKernel(): void
$kernel->setMiddlewarePriority($middleware->getMiddlewarePriority());
- $reflection = new ReflectionClass($kernel);
- $property = $reflection->getProperty('middlewarePriority');
-
$this->assertSame([
'FirstMiddleware',
'SecondMiddleware',
'ThirdMiddleware',
- ], $property->getValue($kernel));
+ ], $kernel->getMiddlewarePriority());
}
public function testWithMiddlewareAppliesAppendsToPriority(): void
{
- $kernel = new \Hypervel\Foundation\Http\Kernel(
- Double::for(Application::class, override: true)->instance(),
- Double::for(Router::class)
- );
+ $kernel = $this->makeKernel();
$middleware = new Middleware;
$middleware->appendToPriorityList(
@@ -665,8 +653,7 @@ public function testWithMiddlewareAppliesAppendsToPriority(): void
$kernel->addToMiddlewarePriorityAfter($after, $newMiddleware);
}
- $reflection = new ReflectionClass($kernel);
- $priority = $reflection->getProperty('middlewarePriority')->getValue($kernel);
+ $priority = $kernel->getMiddlewarePriority();
$bindingsIndex = array_search(\Hypervel\Routing\Middleware\SubstituteBindings::class, $priority);
$appendedIndex = array_search('AppendedMiddleware', $priority);
@@ -677,10 +664,7 @@ public function testWithMiddlewareAppliesAppendsToPriority(): void
public function testWithMiddlewareAppliesPrependsToPriority(): void
{
- $kernel = new \Hypervel\Foundation\Http\Kernel(
- Double::for(Application::class, override: true)->instance(),
- Double::for(Router::class)
- );
+ $kernel = $this->makeKernel();
$middleware = new Middleware;
$middleware->prependToPriorityList(
@@ -692,8 +676,7 @@ public function testWithMiddlewareAppliesPrependsToPriority(): void
$kernel->addToMiddlewarePriorityBefore($before, $newMiddleware);
}
- $reflection = new ReflectionClass($kernel);
- $priority = $reflection->getProperty('middlewarePriority')->getValue($kernel);
+ $priority = $kernel->getMiddlewarePriority();
$bindingsIndex = array_search(\Hypervel\Routing\Middleware\SubstituteBindings::class, $priority);
$prependedIndex = array_search('PrependedMiddleware', $priority);
@@ -704,10 +687,7 @@ public function testWithMiddlewareAppliesPrependsToPriority(): void
public function testWithMiddlewareAppliesGlobalGroupsAndAliasesToKernel(): void
{
- $kernel = new \Hypervel\Foundation\Http\Kernel(
- Double::for(Application::class, override: true)->instance(),
- Double::for(Router::class)
- );
+ $kernel = $this->makeKernel();
$middleware = new Middleware;
$middleware->use(['CustomGlobalMiddleware']);
@@ -718,18 +698,13 @@ public function testWithMiddlewareAppliesGlobalGroupsAndAliasesToKernel(): void
$kernel->setMiddlewareGroups($middleware->getMiddlewareGroups());
$kernel->setMiddlewareAliases($middleware->getMiddlewareAliases());
- $reflection = new ReflectionClass($kernel);
+ $this->assertSame(['CustomGlobalMiddleware'], $kernel->getGlobalMiddleware());
- $this->assertSame(
- ['CustomGlobalMiddleware'],
- $reflection->getProperty('middleware')->getValue($kernel)
- );
-
- $groups = $reflection->getProperty('middlewareGroups')->getValue($kernel);
+ $groups = $kernel->getMiddlewareGroups();
$this->assertArrayHasKey('custom', $groups);
$this->assertSame(['CustomGroupMiddleware'], $groups['custom']);
- $aliases = $reflection->getProperty('middlewareAliases')->getValue($kernel);
+ $aliases = $kernel->getMiddlewareAliases();
$this->assertSame('CustomAliasMiddleware', $aliases['custom-alias']);
}
@@ -752,8 +727,7 @@ public function testWithMiddlewareWiresConfigThroughApplicationBuilder(): void
$kernel = $app->make(\Hypervel\Contracts\Http\Kernel::class);
- $reflection = new ReflectionClass($kernel);
- $priority = $reflection->getProperty('middlewarePriority')->getValue($kernel);
+ $priority = $kernel->getMiddlewarePriority();
// Verify appended middleware is after SubstituteBindings
$bindingsIndex = array_search(\Hypervel\Routing\Middleware\SubstituteBindings::class, $priority);
@@ -768,12 +742,23 @@ public function testWithMiddlewareWiresConfigThroughApplicationBuilder(): void
$this->assertSame($encryptIndex - 1, $prependedIndex);
// Verify custom group was applied
- $groups = $reflection->getProperty('middlewareGroups')->getValue($kernel);
+ $groups = $kernel->getMiddlewareGroups();
$this->assertArrayHasKey('custom', $groups);
$this->assertSame(['CustomGroupMiddleware'], $groups['custom']);
// Verify custom alias was applied
- $aliases = $reflection->getProperty('middlewareAliases')->getValue($kernel);
+ $aliases = $kernel->getMiddlewareAliases();
$this->assertSame('CustomAliasMiddleware', $aliases['custom-alias']);
}
+
+ /**
+ * Create a kernel with a router to receive its middleware configuration.
+ */
+ private function makeKernel(): Kernel
+ {
+ return new Kernel(
+ Double::for(Application::class, override: true)->strict()->instance(),
+ new Router(new Dispatcher),
+ );
+ }
}
diff --git a/tests/Foundation/Console/AboutCommandTest.php b/tests/Foundation/Console/AboutCommandTest.php
index e9a40f1d93..eb4954f57e 100644
--- a/tests/Foundation/Console/AboutCommandTest.php
+++ b/tests/Foundation/Console/AboutCommandTest.php
@@ -48,7 +48,7 @@ public static function jsonDataProvider(): iterable
public function testItReportsNoPhpFilesWhenGlobCannotEnumerateThePath(): void
{
- $command = new TestableAboutCommand(Double::for(Composer::class));
+ $command = new TestableAboutCommand(Double::for(Composer::class)->strict());
$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 5610ef6e57..4e32bcb17c 100644
--- a/tests/Foundation/Console/KernelEventReroutingTest.php
+++ b/tests/Foundation/Console/KernelEventReroutingTest.php
@@ -84,7 +84,7 @@ public function testRerouteSymfonyCommandEventsWiresDispatcherBeforeArtisanCreat
public function testReroutedEventsAreNotDispatchedWithoutListeners(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(CommandStarting::class)->returns(false);
$events->expects('hasListeners')->with(CommandFinished::class)->returns(false);
$events->expects('dispatch')->never();
diff --git a/tests/Foundation/Console/KernelTerminateTest.php b/tests/Foundation/Console/KernelTerminateTest.php
index a55a84bf24..e5931cb28b 100644
--- a/tests/Foundation/Console/KernelTerminateTest.php
+++ b/tests/Foundation/Console/KernelTerminateTest.php
@@ -44,19 +44,9 @@ public function testTerminateDispatchesTerminatingEventAndAppTerminateInOrder():
], $called);
}
- public function testTerminateDispatchesTerminatingEventEvenWithoutHandle(): void
- {
- // Calling terminate without a prior handle should not throw.
- $kernel = $this->app->make(KernelContract::class);
- $kernel->terminate(new StringInput(''), 0);
-
- // If we reach here without exception, the test passes.
- $this->assertTrue(true);
- }
-
public function testTerminateDoesNotConstructOrDispatchAnEventWithoutListeners(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')
->with(Terminating::class)
->returns(false);
diff --git a/tests/Foundation/Console/KernelTest.php b/tests/Foundation/Console/KernelTest.php
index 0b792f87ba..99fa865f9e 100644
--- a/tests/Foundation/Console/KernelTest.php
+++ b/tests/Foundation/Console/KernelTest.php
@@ -49,7 +49,7 @@ protected function useTokyoApplicationTimezone(ApplicationContract $app): void
public function testHandleCatchesExceptionsAndReturnsOne(): void
{
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$handler->expects('report');
$handler->expects('renderForConsole');
$this->app->instance(ExceptionHandlerContract::class, $handler);
@@ -77,8 +77,8 @@ public function testHandleRetainsTheOriginalExceptionWhenReportingFails(): void
$original = new RuntimeException('Bootstrap failed');
$reportingFailure = new RuntimeException('Reporting failed');
- $handler = Double::for(ExceptionHandlerContract::class);
- $handler->expects('report')->with($original, [])->throws($reportingFailure);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
+ $handler->expects('report')->with(Argument::same($original), [])->throws($reportingFailure);
$handler->expects('renderForConsole')->never();
$this->app->instance(ExceptionHandlerContract::class, $handler);
@@ -111,7 +111,7 @@ public function bootstrap(): void
public function testHandlePreservesCancellationWithoutReportingOrRenderingIt(): void
{
$cancellation = new CanceledException('canceled');
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$handler->expects('report')->never();
$handler->expects('renderForConsole')->never();
$this->app->instance(ExceptionHandlerContract::class, $handler);
@@ -367,8 +367,8 @@ public function testReportExceptionDelegatesToExceptionHandler(): void
{
$exception = new RuntimeException('Test exception');
- $handler = Double::for(ExceptionHandlerContract::class);
- $handler->expects('report')->with($exception, []);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
+ $handler->expects('report')->with(Argument::same($exception), []);
$this->app->instance(ExceptionHandlerContract::class, $handler);
$kernel = new Kernel($this->app, $this->app->make('events'));
@@ -382,8 +382,8 @@ public function testRenderExceptionDelegatesToExceptionHandler(): void
$exception = new RuntimeException('Test exception');
$output = new BufferedOutput;
- $handler = Double::for(ExceptionHandlerContract::class);
- $handler->expects('renderForConsole')->with($output, $exception);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
+ $handler->expects('renderForConsole')->with(Argument::same($output), Argument::same($exception));
$this->app->instance(ExceptionHandlerContract::class, $handler);
$kernel = new Kernel($this->app, $this->app->make('events'));
@@ -399,8 +399,8 @@ public function testRenderThrowableUsesConsoleErrorOutput(): void
$errorOutput = new BufferedOutput;
$output->setErrorOutput($errorOutput);
- $handler = Double::for(ExceptionHandlerContract::class);
- $handler->expects('renderForConsole')->with($errorOutput, $exception);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
+ $handler->expects('renderForConsole')->with(Argument::same($errorOutput), Argument::same($exception));
$this->app->instance(ExceptionHandlerContract::class, $handler);
$kernel = new Kernel($this->app, $this->app->make('events'));
@@ -413,7 +413,7 @@ public function testHandleWithNullOutputPreservesOriginalThrowable(): void
{
$reportedException = null;
- $handler = Double::for(ExceptionHandlerContract::class);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
$handler->expects('report')->resolves(function (RuntimeException $exception) use (&$reportedException): void {
$reportedException = $exception;
});
diff --git a/tests/Foundation/Console/ViewCacheCommandTest.php b/tests/Foundation/Console/ViewCacheCommandTest.php
index 64c6d1f7a1..f5f2939c39 100644
--- a/tests/Foundation/Console/ViewCacheCommandTest.php
+++ b/tests/Foundation/Console/ViewCacheCommandTest.php
@@ -76,14 +76,14 @@ public function testPathsRetainFilesystemRoot(): void
*/
protected function commandWithPaths(array $paths, array $hints = []): TestViewCacheCommand
{
- $finder = Double::for(ViewFinderInterface::class);
+ $finder = Double::for(ViewFinderInterface::class)->strict();
$finder->expects('getPaths')->returns($paths);
$finder->expects('getHints')->returns($hints);
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$factory->expects('getFinder')->returns($finder);
- $application = Double::for(Application::class, override: true);
+ $application = Double::for(Application::class, override: true)->strict();
$application->expects('make')->with('view')->returns($factory);
$command = new TestViewCacheCommand;
diff --git a/tests/Foundation/DeferredCallbacksTest.php b/tests/Foundation/DeferredCallbacksTest.php
index 7d302595aa..c2daf0e019 100644
--- a/tests/Foundation/DeferredCallbacksTest.php
+++ b/tests/Foundation/DeferredCallbacksTest.php
@@ -114,7 +114,7 @@ public function testJobLifecycleOwnsCallbacksRegisteredByNestedCommand(): void
$this->assertSame([], DeferredCallbacksTestState::$calls);
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->allows('hasFailed')->returns(false);
$this->app->make(Dispatcher::class)->dispatch(
@@ -135,7 +135,7 @@ public function testCanceledJobAttemptSkipsEveryDeferredCallback(): void
})->always();
$this->app->make(Dispatcher::class)->dispatch(
- new JobAttempted('database', Double::for(Job::class), new CanceledException, canceled: true)
+ new JobAttempted('database', Double::for(Job::class)->strict(), new CanceledException, canceled: true)
);
$this->assertSame([], DeferredCallbacksTestState::$calls);
@@ -143,7 +143,7 @@ public function testCanceledJobAttemptSkipsEveryDeferredCallback(): void
public function testJobWithoutDeferredCallbacksDoesNotResolveTheCollection(): void
{
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->expects('hasFailed')->never();
$this->app->make(Dispatcher::class)->dispatch(
@@ -160,7 +160,7 @@ public function testJobAttemptedRunsDeferredCallbacksForSuccessfulJobs(string $c
DeferredCallbacksTestState::record('job');
});
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->allows('hasFailed')->returns(false);
$this->app->make(Dispatcher::class)->dispatch(
@@ -193,7 +193,7 @@ public function testJobAttemptedSkipsFailedJobsAndSyncConnectionsUnlessAlwaysTru
DeferredCallbacksTestState::record('always');
}, always: true);
- $failedJob = Double::for(Job::class);
+ $failedJob = Double::for(Job::class)->strict();
$failedJob->allows('hasFailed')->returns(true);
$this->app->make(Dispatcher::class)->dispatch(
@@ -208,7 +208,7 @@ public function testJobAttemptedSkipsFailedJobsAndSyncConnectionsUnlessAlwaysTru
DeferredCallbacksTestState::record('sync');
});
- $syncJob = Double::for(Job::class);
+ $syncJob = Double::for(Job::class)->strict();
$syncJob->expects('hasFailed')->never();
$this->app->make(Dispatcher::class)->dispatch(
diff --git a/tests/Foundation/Exceptions/Renderer/ExceptionTest.php b/tests/Foundation/Exceptions/Renderer/ExceptionTest.php
index 83edc91dec..b156a2498c 100644
--- a/tests/Foundation/Exceptions/Renderer/ExceptionTest.php
+++ b/tests/Foundation/Exceptions/Renderer/ExceptionTest.php
@@ -21,7 +21,7 @@ class ExceptionTest extends TestCase
public function testApplicationQueriesPreserveBindingText(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getName')->returns(null);
$connection->expects('prepareBindings')->resolves(fn (array $bindings): array => $bindings);
diff --git a/tests/Foundation/Exceptions/Renderer/ListenerContextIsolationTest.php b/tests/Foundation/Exceptions/Renderer/ListenerContextIsolationTest.php
index 32b56a8546..f09fc2870a 100644
--- a/tests/Foundation/Exceptions/Renderer/ListenerContextIsolationTest.php
+++ b/tests/Foundation/Exceptions/Renderer/ListenerContextIsolationTest.php
@@ -39,7 +39,7 @@ public function testQueriesAreIsolatedBetweenCoroutines(): void
private function recordQueries(string $connectionName, array $queries): array
{
$listener = new Listener;
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getName')->returns($connectionName);
$connection->allows('prepareBindings')->returns([]);
diff --git a/tests/Foundation/Exceptions/Renderer/ListenerTest.php b/tests/Foundation/Exceptions/Renderer/ListenerTest.php
index aaa2a13cd1..3b3b5b7f7a 100644
--- a/tests/Foundation/Exceptions/Renderer/ListenerTest.php
+++ b/tests/Foundation/Exceptions/Renderer/ListenerTest.php
@@ -59,7 +59,7 @@ public function testListenerCapsAt100Queries(): void
{
$listener = new Listener;
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getName')->times(150)->returns('testing');
$connection->expects('prepareBindings')->times(100)->resolves(fn (array $bindings): array => $bindings);
@@ -176,7 +176,7 @@ public function testNormalQuerySkipsTruncation(): void
public function testLongQueriesAndBindingsAreBounded(): void
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getName')->returns('testing');
$connection->expects('prepareBindings')
->with(['first', 'second', 'third'])
diff --git a/tests/Foundation/FoundationApplicationTest.php b/tests/Foundation/FoundationApplicationTest.php
index e7ea7ef888..40ef1ae865 100644
--- a/tests/Foundation/FoundationApplicationTest.php
+++ b/tests/Foundation/FoundationApplicationTest.php
@@ -61,7 +61,7 @@ protected function tearDown(): void
public function testSetLocaleSetsLocaleAndFiresLocaleChangedEvent(): void
{
$events = new EventFake(new EventDispatcher);
- $translator = Double::for(TranslatorContract::class);
+ $translator = Double::for(TranslatorContract::class)->strict();
$translator->expects('getLocale')->returns('bar')->ordered();
$translator->expects('setLocale')->with('foo')->ordered()->resolves(function () use ($events): void {
$events->assertNothingDispatched();
@@ -86,10 +86,10 @@ public function testSetLocaleSetsLocaleAndFiresLocaleChangedEvent(): void
public function testSetLocaleDoesNotDispatchWhenLocaleEventHasNoListeners(): void
{
- $translator = Double::for(TranslatorContract::class);
+ $translator = Double::for(TranslatorContract::class)->strict();
$translator->expects('getLocale')->returns('bar');
$translator->expects('setLocale')->with('foo');
- $events = Double::for(DispatcherContract::class);
+ $events = Double::for(DispatcherContract::class)->strict();
$events->expects('hasListeners')->with(LocaleUpdated::class)->returns(false);
$events->expects('dispatch')->never();
@@ -102,7 +102,7 @@ public function testSetLocaleDoesNotDispatchWhenLocaleEventHasNoListeners(): voi
public function testSetFallbackLocaleSetsTranslatorFallback(): void
{
- $translator = Double::for(TranslatorContract::class);
+ $translator = Double::for(TranslatorContract::class)->strict();
$translator->expects('setFallback')->with('fr');
$config = new Repository(['app' => ['fallback_locale' => 'en']]);
@@ -127,7 +127,7 @@ public function testLoggerInterfaceResolvesAfterFacadesAreRegisteredBeforeConfig
],
]));
- $manifest = Double::for(PackageManifest::class);
+ $manifest = Double::for(PackageManifest::class)->strict();
$manifest->expects('aliases')->returns([]);
$app->singleton(PackageManifest::class, fn (): PackageManifest => $manifest);
@@ -142,7 +142,7 @@ public function testLoggerInterfaceResolvesAfterFacadesAreRegisteredBeforeConfig
public function testGetLocaleReadsFromTranslator(): void
{
- $translator = Double::for(TranslatorContract::class);
+ $translator = Double::for(TranslatorContract::class)->strict();
$translator->expects('getLocale')->returns('en');
$app = new Application;
@@ -153,7 +153,7 @@ public function testGetLocaleReadsFromTranslator(): void
public function testGetFallbackLocaleReadsFromTranslator(): void
{
- $translator = Double::for(TranslatorContract::class);
+ $translator = Double::for(TranslatorContract::class)->strict();
$translator->expects('getFallback')->returns('en');
$app = new Application;
@@ -540,7 +540,7 @@ public function testBootResolvesTheBoundHttpKernelBeforeBootingCallbacks(): void
$application->singleton(HttpKernelContract::class, function () use (&$events): HttpKernelContract {
$events[] = 'kernel';
- return Double::for(HttpKernelContract::class);
+ return Double::for(HttpKernelContract::class)->strict();
});
$application->booting(function () use (&$events): void {
$events[] = 'booting';
diff --git a/tests/Foundation/FoundationAuthenticationTest.php b/tests/Foundation/FoundationAuthenticationTest.php
index 2fe9f65577..dd9a5ee325 100644
--- a/tests/Foundation/FoundationAuthenticationTest.php
+++ b/tests/Foundation/FoundationAuthenticationTest.php
@@ -35,13 +35,13 @@ class FoundationAuthenticationTest extends TestCase
*/
protected function mockGuard(): Guard
{
- $guard = Double::for(SessionGuard::class);
+ $guard = Double::for(SessionGuard::class)->strict();
- $auth = Double::for(AuthManager::class);
+ $auth = Double::for(AuthManager::class)->strict();
$auth->expects('guard')
->returns($guard);
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->expects('make')
->with('auth')
->returns($auth);
@@ -167,7 +167,7 @@ protected function setupProvider(array $credentials): void
{
$user = new GenericUser([]);
- $provider = Double::for(UserProvider::class);
+ $provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')
->with($credentials)
diff --git a/tests/Foundation/FoundationCacheBasedMaintenanceModeTest.php b/tests/Foundation/FoundationCacheBasedMaintenanceModeTest.php
index 2c0084c4d2..b9b5139643 100644
--- a/tests/Foundation/FoundationCacheBasedMaintenanceModeTest.php
+++ b/tests/Foundation/FoundationCacheBasedMaintenanceModeTest.php
@@ -18,7 +18,7 @@ class FoundationCacheBasedMaintenanceModeTest extends TestCase
public function testItDeterminesWhetherMaintenanceModeIsActive(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->expects('store')->times(2)->with('store-key')->returns($cache);
$manager = new CacheBasedMaintenanceMode($cache, 'store-key', 'key');
@@ -31,7 +31,7 @@ public function testItDeterminesWhetherMaintenanceModeIsActive(): void
public function testItRetrievesPayloadFromCache(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->expects('store')->with('store-key')->returns($cache);
$manager = new CacheBasedMaintenanceMode($cache, 'store-key', 'key');
@@ -42,7 +42,7 @@ public function testItRetrievesPayloadFromCache(): void
public function testItReturnsEmptyPayloadWhenCacheKeyIsMissing(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->expects('store')->with('store-key')->returns($cache);
$manager = new CacheBasedMaintenanceMode($cache, 'store-key', 'key');
@@ -53,7 +53,7 @@ public function testItReturnsEmptyPayloadWhenCacheKeyIsMissing(): void
public function testItStoresPayloadInCache(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->expects('store')->with('store-key')->returns($cache);
$cache->expects('put')->with('key', ['payload'])->returns(true);
@@ -63,7 +63,7 @@ public function testItStoresPayloadInCache(): void
public function testItRemovesPayloadFromCache(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->expects('store')->with('store-key')->returns($cache);
$cache->expects('forget')->with('key')->returns(true);
@@ -73,7 +73,7 @@ public function testItRemovesPayloadFromCache(): void
public function testItFailsWhenPayloadCannotBeStored(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->expects('store')->with('store-key')->returns($cache);
$cache->expects('put')->with('key', ['payload'])->returns(false);
@@ -85,7 +85,7 @@ public function testItFailsWhenPayloadCannotBeStored(): void
public function testItFailsWhenPayloadCannotBeRemoved(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->expects('store')->with('store-key')->returns($cache);
$cache->expects('forget')->with('key')->returns(false);
diff --git a/tests/Foundation/FoundationExceptionsHandlerTest.php b/tests/Foundation/FoundationExceptionsHandlerTest.php
index 152c9a8b1c..d234c3aaa4 100644
--- a/tests/Foundation/FoundationExceptionsHandlerTest.php
+++ b/tests/Foundation/FoundationExceptionsHandlerTest.php
@@ -94,8 +94,8 @@ protected function setUp(): void
parent::setUp();
$this->config = $this->getConfig();
- $this->viewFactory = Double::for(ViewFactory::class);
- $this->requestDouble = Double::for(Request::class, override: true);
+ $this->viewFactory = Double::for(ViewFactory::class)->strict();
+ $this->requestDouble = Double::for(Request::class, override: true)->strict();
$this->request = $this->requestDouble->instance();
$this->container = new Application;
$this->container->singleton('config', fn (): Repository => $this->config);
@@ -104,7 +104,7 @@ protected function setUp(): void
$this->container->instance(ResponseFactoryContract::class, new ResponseFactory(
$this->viewFactory,
- Double::for(Redirector::class),
+ Double::for(Redirector::class)->strict(),
));
Container::setInstance($this->container);
@@ -140,7 +140,7 @@ public function testHandlerReportsExceptionAsContext(bool $throwingCleanup): voi
public function testHandlerNeverReportsCancellation(): void
{
$cancellation = new CanceledException('canceled');
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->expects('log')->never();
$logger->expects('error')->never();
$this->container->instance(LoggerInterface::class, $logger);
@@ -167,7 +167,7 @@ public function testHandlerPreservesCancellationFromLoggerResolution(Throwable $
#[DataProvider('cancellations')]
public function testHandlerPreservesCancellationFromDefaultContext(Throwable $cancellation): void
{
- $auth = Double::for(Guard::class);
+ $auth = Double::for(Guard::class)->strict();
$auth->expects('id')->throws($cancellation);
$this->container->instance('auth', $auth);
$previousFacadeApplication = Facade::getFacadeApplication();
@@ -208,7 +208,7 @@ public function testHandlerPreservesCancellationDuringRendering(Throwable $cance
public function testHandlerPreservesCancellationFromCustomRenderer(Throwable $cancellation): void
{
$failure = new RuntimeException('failed');
- $renderer = Double::for(ExceptionRenderer::class);
+ $renderer = Double::for(ExceptionRenderer::class)->strict();
$renderer->expects('render')->with(Argument::same($failure))->throws($cancellation);
$this->container->instance(ExceptionRenderer::class, $renderer);
$this->config->set('app.debug', true);
@@ -236,7 +236,7 @@ public function testHandlerPreservesCancellationDuringConsoleRendering(Throwable
public function testReportingStateIsLocalToTheCurrentCoroutine(): void
{
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$exception = new RuntimeException('Exception message');
$parentReporting = false;
@@ -286,7 +286,7 @@ public function testHandlerCallsContextMethodIfPresent(): void
public function testHandlerMergesInlineContextIntoLogContext(): void
{
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('error')->with('Exception message', Argument::satisfies(fn (array $context): bool => ($context['from'] ?? null) === 'user@example.com' && ($context['subject'] ?? null) === 'Hello'));
@@ -298,7 +298,7 @@ public function testHandlerMergesInlineContextIntoLogContext(): void
public function testHandlerInlineContextOverridesExceptionContext(): void
{
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('error')->with('Exception message', Argument::satisfies(fn (array $context): bool => ($context['foo'] ?? null) === 'overridden'));
@@ -331,7 +331,7 @@ public function testReportableCallbackReceivesInlineContext(): void
public function testReportingMarkerIsRestoredAfterNestedReportsAndContextFailures(): void
{
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('error')->with('Inner exception', Argument::satisfies(fn (array $context): bool => array_key_exists('exception', $context)));
@@ -404,7 +404,7 @@ public function testHandlerReportsExceptionWithCustomLogLevel(): void
public function testHandlerReportsExceptionWithInlineLogLevel(): void
{
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('warning')->with(
@@ -423,7 +423,7 @@ public function testHandlerReportsExceptionWithInlineLogLevel(): void
public function testHandlerIgnoresNotReportableExceptions(): void
{
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('log')->never();
$logger->expects('error')->never();
@@ -538,11 +538,11 @@ public function testHandlerInvokesRetryCallbackWhenExceptionMatchesAllIntersecti
public function testHandlerCallsReportMethodWithDependencies(): void
{
- $reporter = Double::for(ReportingService::class);
+ $reporter = Double::for(ReportingService::class)->strict();
$this->container->instance(ReportingService::class, $reporter);
$reporter->expects('send')->with('Exception message');
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('log')->never();
$logger->expects('error')->never();
@@ -552,10 +552,10 @@ public function testHandlerCallsReportMethodWithDependencies(): void
public function testHandlerReportsExceptionUsingCallableClass(): void
{
- $reporter = Double::for(ReportingService::class);
+ $reporter = Double::for(ReportingService::class)->strict();
$reporter->expects('send')->with('Exception message');
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('log')->never();
$logger->expects('error')->never();
@@ -639,7 +639,7 @@ public function testUnauthenticatedRequestWithRedirectReturnsGuestRedirect(): vo
AuthenticationException::redirectUsing(static fn (): string => '/login');
$this->requestDouble->expects('expectsJson')->returns(false);
- $redirector = Double::for(Redirector::class);
+ $redirector = Double::for(Redirector::class)->strict();
$redirector->expects('guest')
->with('/login')
->returns(new RedirectResponse('/login'));
@@ -794,21 +794,15 @@ public function testValidateFileMethod(): void
$argumentExpected = ['input' => 'My input value'];
$argumentActual = null;
- $session = Double::for(Store::class);
+ $session = Double::for(Store::class)->strict();
$session->allows('get')->with('errors', Argument::type(ViewErrorBag::class))->returns(new MessageBag(['error' => 'My custom validation exception']));
$session->expects('flash')->with('errors', Argument::type(ViewErrorBag::class));
- $session->expects('flashInput')->with(Argument::satisfies(
- function (array $argument) use (&$argumentActual): bool {
- $argumentActual = $argument;
-
- return true;
- }
- ))->returns(null);
+ $session->expects('flashInput')->with(Argument::capture($argumentActual));
CoroutineContext::set(Store::CONTEXT_KEY, $session);
$this->container->instance(SessionContract::class, $session);
$this->container->singleton('redirect', function () use ($session): Redirector {
- $redirector = Double::for(Redirector::class);
+ $redirector = Double::for(Redirector::class)->strict();
$redirect = new RedirectResponse('http://localhost/');
$redirect->setSession($session);
@@ -822,7 +816,7 @@ function (array $argument) use (&$argumentActual): bool {
$request = Request::create('/', 'POST', $argumentExpected, [], ['photo' => $file]);
- $validator = Double::for(Validator::class);
+ $validator = Double::for(Validator::class)->strict();
$validator->expects('errors')->times(2)->returns(new MessageBag(['error' => 'My custom validation exception']));
$validationException = new ValidationException($validator);
@@ -836,26 +830,22 @@ function (array $argument) use (&$argumentActual): bool {
public function testInvalidUsesErrorBagWhenStringAndFallsBackWhenNotString(): void
{
$errorBagActual = null;
- CoroutineContext::set(Store::CONTEXT_KEY, Double::for(Store::class));
+ CoroutineContext::set(Store::CONTEXT_KEY, Double::for(Store::class)->strict());
$this->container->singleton('redirect', function () use (&$errorBagActual): Redirector {
- $redirector = Double::for(Redirector::class);
+ $redirector = Double::for(Redirector::class)->strict();
$responder = Double::for(new RedirectResponse('/'))->passthru();
$redirector->expects('to')->times(2)->returns($responder);
$responder->expects('withInput')->times(2)->returns($responder);
$responder->expects('withErrors')->times(2)->with(
Argument::any(),
- Argument::satisfies(function (string $errorBag) use (&$errorBagActual): bool {
- $errorBagActual = $errorBag;
-
- return true;
- })
+ Argument::capture($errorBagActual)
)->returns($responder);
return $redirector;
});
- $validator = Double::for(Validator::class);
+ $validator = Double::for(Validator::class)->strict();
$validator->expects('errors')->times(3)->returns(new MessageBag(['error' => 'My custom validation exception']));
$validationException = new ValidationException($validator);
@@ -881,7 +871,7 @@ public function testSuspiciousOperationReturns400WithoutReporting(): void
$this->assertEquals(400, $response->getStatusCode());
$this->assertStringContainsString('"message": "Bad request."', $response->getContent());
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('log')->never();
$logger->expects('error')->never();
@@ -899,7 +889,7 @@ public function testRecordsNotFoundReturns404WithoutReporting(): void
$this->assertEquals(404, $response->getStatusCode());
$this->assertStringContainsString('"message": "Not found."', $response->getContent());
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('log')->never();
$logger->expects('error')->never();
@@ -983,7 +973,7 @@ private function executeScenarioWhereErrorViewThrowsWhileRenderingAndDebugIs(boo
$this->container->instance(ViewFactory::class, $viewFactory);
$this->container->instance(ResponseFactoryContract::class, new ResponseFactory(
$viewFactory,
- Double::for(Redirector::class),
+ Double::for(Redirector::class)->strict(),
));
$this->config->set('app.debug', $debug);
@@ -1644,7 +1634,7 @@ public function testValidateFailed(): void
$this->requestDouble->allows('input')->with(Argument::none())->returns(['foo' => 'bar']);
$this->requestDouble->allows('input')->with('_error_bag')->returns('default');
- $session = Double::for(Store::class);
+ $session = Double::for(Store::class)->strict();
$session->allows('get')->with('errors', Argument::type(ViewErrorBag::class))->returns(new MessageBag(['error' => 'My custom validation exception']));
$session->expects('flash')->with('errors', Argument::type(ViewErrorBag::class));
$session->expects('flashInput')->with(['foo' => 'bar']);
@@ -1652,7 +1642,7 @@ public function testValidateFailed(): void
$this->container->instance(SessionContract::class, $session);
$redirectTo = 'http://localhost/redirectTo';
- $redirector = Double::for(Redirector::class);
+ $redirector = Double::for(Redirector::class)->strict();
$redirect = new RedirectResponse($redirectTo);
$redirect->setSession($session);
$redirector->expects('to')
@@ -1660,7 +1650,7 @@ public function testValidateFailed(): void
->returns($redirect);
$this->container->instance('redirect', $redirector);
- $validator = Double::for(Validator::class);
+ $validator = Double::for(Validator::class)->strict();
$validator->allows('errors')->returns(new MessageBag(['error' => 'My custom validation exception']));
$validationException = new ValidationException($validator);
@@ -1682,7 +1672,7 @@ public function testModelNotFoundReturns404WithoutReporting(): void
$this->assertEquals(404, $response->getStatusCode());
$this->assertStringContainsString('"message": "No query results for model [foo]."', $response->getContent());
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$this->container->instance(LoggerInterface::class, $logger);
$logger->expects('log')->never();
$logger->expects('error')->never();
diff --git a/tests/Foundation/FoundationFileBasedMaintenanceModeTest.php b/tests/Foundation/FoundationFileBasedMaintenanceModeTest.php
index ba91e9cea9..ba20e6605c 100644
--- a/tests/Foundation/FoundationFileBasedMaintenanceModeTest.php
+++ b/tests/Foundation/FoundationFileBasedMaintenanceModeTest.php
@@ -76,7 +76,7 @@ public function testDataReturnsEmptyPayloadWhenFileDoesNotExist(): void
public function testCachedActivityReturnsFalseWhenFileDisappearsDuringRead(): void
{
$path = storage_path('framework/down');
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->allows('exists')->with($path)->returns(true, false);
$files->expects('get')->with($path)
->throws(new FileNotFoundException('removed'));
@@ -91,7 +91,7 @@ public function testDataRethrowsReadFailureWhenFileStillExists(): void
{
$path = storage_path('framework/down');
$exception = new FileNotFoundException('unreadable');
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with($path)->returns(true);
$files->expects('get')->with($path)->throws($exception);
@@ -209,7 +209,7 @@ public function testActivateRejectsOneLevelOverTheMaximumNestingDepth(): void
public function testDeactivateFailsWhenDeleteReturnsFalseAndFileRemains(): void
{
$path = storage_path('framework/down');
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->times(2)->with($path)->returns(true);
$files->expects('delete')->with($path)->returns(false);
@@ -222,12 +222,10 @@ public function testDeactivateFailsWhenDeleteReturnsFalseAndFileRemains(): void
public function testDeactivateSucceedsWhenAnotherOwnerRemovesTheFile(): void
{
$path = storage_path('framework/down');
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->times(2)->with($path)->returns(true, false);
$files->expects('delete')->with($path)->returns(false);
(new FileBasedMaintenanceMode($files))->deactivate();
-
- $this->assertTrue(true);
}
}
diff --git a/tests/Foundation/FoundationFormRequestTest.php b/tests/Foundation/FoundationFormRequestTest.php
index 9477694d13..77fd3eb9ab 100644
--- a/tests/Foundation/FoundationFormRequestTest.php
+++ b/tests/Foundation/FoundationFormRequestTest.php
@@ -869,7 +869,7 @@ protected function createRequest(array $payload = [], string $class = Foundation
*/
protected function createValidationFactory(Container $container): ValidationFactory
{
- $translator = Double::for(Translator::class);
+ $translator = Double::for(Translator::class)->strict();
$translator->allows('get')->returns('error');
$translator->allows('string')->returns('error');
$translator->allows('choice')->returns('error');
@@ -899,7 +899,7 @@ protected function getRealRedirector(array $routes = []): Redirector
*/
protected function createMockRedirector(FormRequest $request): Redirector
{
- $redirector = $this->mocks['redirector'] = Double::for(Redirector::class);
+ $redirector = $this->mocks['redirector'] = Double::for(Redirector::class)->strict();
$redirector->allows('getUrlGenerator')
->returns($generator = $this->createMockUrlGenerator());
@@ -918,7 +918,7 @@ protected function createMockRedirector(FormRequest $request): Redirector
*/
protected function createMockUrlGenerator(): UrlGenerator
{
- return $this->mocks['generator'] = Double::for(UrlGenerator::class);
+ return $this->mocks['generator'] = Double::for(UrlGenerator::class)->strict();
}
/**
@@ -926,7 +926,7 @@ protected function createMockUrlGenerator(): UrlGenerator
*/
protected function createMockRedirectResponse(): RedirectResponse
{
- return $this->mocks['redirect'] = Double::for(RedirectResponse::class);
+ return $this->mocks['redirect'] = Double::for(RedirectResponse::class)->strict();
}
public function testAttributeConfigurationIsCachedPerClass(): void
diff --git a/tests/Foundation/FoundationHelpersTest.php b/tests/Foundation/FoundationHelpersTest.php
index 45fd7e9e2a..e8ec77a826 100644
--- a/tests/Foundation/FoundationHelpersTest.php
+++ b/tests/Foundation/FoundationHelpersTest.php
@@ -251,7 +251,7 @@ public function testOldReturnsNonStringInput(): void
public function testInfoWritesToTheLogger(): void
{
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->expects('info')->with('User login attempt failed.', ['id' => 1]);
$this->app->instance(LoggerInterface::class, $logger);
@@ -261,7 +261,7 @@ public function testInfoWritesToTheLogger(): void
public function testInfoAddsTheCallerLocationToTheContext(): void
{
$loggedContext = null;
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->expects('info')->with('Cache warmed.', Argument::capture($loggedContext));
$this->app->instance(LoggerInterface::class, $logger);
@@ -273,8 +273,8 @@ public function testInfoAddsTheCallerLocationToTheContext(): void
public function testLogsResolvesAChannelNamedZero(): void
{
- $manager = Double::for(LogManager::class);
- $logger = Double::for(LoggerInterface::class);
+ $manager = Double::for(LogManager::class)->strict();
+ $logger = Double::for(LoggerInterface::class)->strict();
$manager->expects('driver')->with('0')->returns($logger);
$this->app->instance('log', $manager);
diff --git a/tests/Foundation/FoundationInteractsWithDatabaseTest.php b/tests/Foundation/FoundationInteractsWithDatabaseTest.php
index 678db3077b..a7ea2c6191 100644
--- a/tests/Foundation/FoundationInteractsWithDatabaseTest.php
+++ b/tests/Foundation/FoundationInteractsWithDatabaseTest.php
@@ -39,7 +39,7 @@ protected function setUp(): void
{
parent::setUp();
- $this->connection = Double::for(Connection::class);
+ $this->connection = Double::for(Connection::class)->strict();
}
public function testSeeInDatabaseFindsResults(): void
@@ -72,7 +72,7 @@ public function testAssertDatabaseHasConstrainsToModel(): void
public function testAssertDatabaseSupportsArrays(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('where')->ordered()->with(['title' => 'Spark', 'name' => 'Hypervel'])->returns($builder);
$builder->expects('where')->ordered()->with(['title' => 'Forge', 'name' => 'Hypervel'])->returns($builder);
$builder->expects('exists')->times(2)->returns(true);
@@ -118,7 +118,7 @@ public function testSeeInDatabaseFindsManyNotMatchingResults(): void
public function testAssertDatabaseMissingSupportsArrays(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('where')->ordered()->with(['title' => 'Spark', 'name' => 'Hypervel'])->returns($builder);
$builder->expects('where')->ordered()->with(['title' => 'Forge', 'name' => 'Hypervel'])->returns($builder);
$builder->expects('exists')->times(2)->returns(false);
@@ -208,7 +208,7 @@ public function testAssertDatabaseEmpty(): void
public function testAssertDatabaseEmptySupportsArrays(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('count')->times(2)->returns(0);
$this->connection->expects('table')->with($this->table)->returns($builder);
@@ -227,7 +227,7 @@ public function testAssertTableEntriesCountWrong(): void
public function testAssertSoftDeletedSupportsArrays(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('where')->ordered()->with(['title' => 'Spark', 'name' => 'Hypervel'])->returns($builder);
$builder->expects('where')->ordered()->with(['title' => 'Forge', 'name' => 'Hypervel'])->returns($builder);
$builder->expects('whereNotNull')->with('deleted_at')->times(2)->returns($builder);
@@ -243,7 +243,7 @@ public function testAssertSoftDeletedSupportsArrays(): void
public function testAssertSoftDeletedSupportsModelWithArrays(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('where')->ordered()->with(['title' => 'Spark', 'id' => 1])->returns($builder);
$builder->expects('where')->ordered()->with(['name' => 'Hypervel', 'id' => 1])->returns($builder);
$builder->expects('whereNotNull')->with('trashed_at')->times(2)->returns($builder);
@@ -259,7 +259,7 @@ public function testAssertSoftDeletedSupportsModelWithArrays(): void
public function testAssertNotSoftDeletedSupportsArrays(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('where')->ordered()->with(['title' => 'Spark', 'name' => 'Hypervel'])->returns($builder);
$builder->expects('where')->ordered()->with(['title' => 'Forge', 'name' => 'Hypervel'])->returns($builder);
$builder->expects('whereNull')->with('deleted_at')->times(2)->returns($builder);
@@ -275,7 +275,7 @@ public function testAssertNotSoftDeletedSupportsArrays(): void
public function testAssertNotSoftDeletedSupportsModelWithArrays(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('where')->ordered()->with(['title' => 'Spark', 'id' => 1])->returns($builder);
$builder->expects('where')->ordered()->with(['name' => 'Hypervel', 'id' => 1])->returns($builder);
$builder->expects('whereNull')->with('trashed_at')->times(2)->returns($builder);
@@ -291,7 +291,7 @@ public function testAssertNotSoftDeletedSupportsModelWithArrays(): void
public function testAssertSoftDeletedTableSupportsIterablesWithCustomDeletedAtColumn(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('where')->with($this->data)->times(2)->returns($builder);
$builder->expects('whereNotNull')->with('removed_at')->times(2)->returns($builder);
$builder->expects('exists')->times(2)->returns(true);
@@ -304,7 +304,7 @@ public function testAssertSoftDeletedTableSupportsIterablesWithCustomDeletedAtCo
public function testAssertNotSoftDeletedTableSupportsIterablesWithCustomDeletedAtColumn(): void
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$builder->expects('where')->with($this->data)->times(2)->returns($builder);
$builder->expects('whereNull')->with('removed_at')->times(2)->returns($builder);
$builder->expects('exists')->times(2)->returns(true);
@@ -595,7 +595,7 @@ public function testExpectsDatabaseQueryCount(): void
*/
protected function mockCountBuilder(bool $existsResult, string $deletedAtColumn = 'deleted_at', array|int|null $countResult = null): Builder&DoubleInterface
{
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$countResult = Arr::wrap($countResult);
$countResult = ! empty($countResult) ? $countResult : [$existsResult ? 1 : 0];
diff --git a/tests/Foundation/Http/KernelTest.php b/tests/Foundation/Http/KernelTest.php
index 238ddf26d3..e6db02fa7b 100644
--- a/tests/Foundation/Http/KernelTest.php
+++ b/tests/Foundation/Http/KernelTest.php
@@ -20,6 +20,7 @@
use Hypervel\Tests\TestCase;
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;
@@ -420,11 +421,11 @@ public function testHandleReportsAndRendersRouterFailures(): void
$failure = new RuntimeException('stream failed');
$request = Request::create('/');
$replacement = new Response('replacement', 500);
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($failure, []);
- $handler->expects('render')->with($request, $failure)->returns($replacement);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($failure), []);
+ $handler->expects('render')->with(Argument::same($request), Argument::same($failure))->returns($replacement);
$app->instance(ExceptionHandler::class, $handler);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->throws($failure);
$kernel = new Kernel($app, $router);
@@ -439,11 +440,11 @@ public function testHandleRetainsTheRouterFailureWhenExceptionReportingFails():
$app->bootstrapWith([]);
$original = new RuntimeException('router failed');
$reportingFailure = new RuntimeException('reporting failed');
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($original, [])->throws($reportingFailure);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($original), [])->throws($reportingFailure);
$handler->expects('render')->never();
$app->instance(ExceptionHandler::class, $handler);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->throws($original);
$kernel = new Kernel($app, $router);
@@ -467,11 +468,11 @@ public function testHandlePreservesRouterCancellationWithoutReportingOrDispatchi
$events->listen(RequestHandled::class, function () use (&$handled): void {
$handled = true;
});
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->never();
$handler->expects('render')->never();
$app->instance(ExceptionHandler::class, $handler);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->throws($cancellation);
$kernel = new Kernel($app, $router);
@@ -493,11 +494,11 @@ public function testHandlePreservesCancellationFromTheHandledEventWithoutReporti
$app->bootstrapWith([]);
$cancellation = new CanceledException('canceled');
$events->listen(RequestHandled::class, fn () => throw $cancellation);
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->never();
$handler->expects('render')->never();
$app->instance(ExceptionHandler::class, $handler);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->returns(new Response);
$kernel = new Kernel($app, $router);
@@ -517,7 +518,7 @@ public function testTerminationIsExhaustiveAndPreservesTheFirstFailure(): void
$app->instance('events', $events);
$app->instance('config', new Repository(['app' => ['timezone' => 'UTC']]));
$app->bootstrapWith([]);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->returns(new Response);
$kernel = new Kernel($app, $router);
$request = Request::create('/');
@@ -601,7 +602,7 @@ public function testTerminationCancellationStopsLaterStagesAndClearsTheRequestSt
$app->instance('events', $events);
$app->instance('config', new Repository(['app' => ['timezone' => 'UTC']]));
$app->bootstrapWith([]);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->returns(new Response);
$kernel = new Kernel($app, $router);
$request = Request::create('/');
@@ -653,7 +654,7 @@ public function testMiddlewareCancellationSupersedesAnEarlierOrdinaryTermination
$app->instance('events', $events);
$app->instance('config', new Repository(['app' => ['timezone' => 'UTC']]));
$app->bootstrapWith([]);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->returns(new Response);
$kernel = new Kernel($app, $router);
$request = Request::create('/');
@@ -714,7 +715,7 @@ public function testDurationHandlerCancellationSupersedesAnEarlierOrdinaryTermin
$app->instance('events', $events);
$app->instance('config', new Repository(['app' => ['timezone' => 'UTC']]));
$app->bootstrapWith([]);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->returns(new Response);
$kernel = new Kernel($app, $router);
$request = Request::create('/');
@@ -755,7 +756,7 @@ public function testDurationHandlerReceivesConvertedImmutableStartTimeFromContex
$app->instance('config', new Repository(['app' => ['timezone' => 'America/New_York']]));
$app->bootstrapWith([]);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->returns(new Response);
$kernel = new Kernel($app, $router);
@@ -790,7 +791,7 @@ public function testProductionRequestStartTimeIsMaterializedLazily(): void
$app->instance('config', new Repository(['app' => ['timezone' => 'UTC']]));
$app->bootstrapWith([]);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->returns(new Response);
$kernel = new class($app, $router) extends Kernel {
@@ -832,7 +833,7 @@ public function handle(Request $request, Closure $next): Response
}
};
});
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->expects('dispatch')->times(2)->returns(new Response);
$kernel = new class($app, $router) extends Kernel {
public function reusablePipeline(): ?Closure
@@ -855,7 +856,7 @@ public function reusablePipeline(): ?Closure
public function testSetApplicationClearsApplicationSpecificMiddlewareCaches(): void
{
- $kernel = new class(new Application, Double::for(Router::class)) extends Kernel {
+ $kernel = new class(new Application, Double::for(Router::class)->strict()) extends Kernel {
public function primeMiddlewareCaches(): void
{
$this->terminableMiddleware = ['test-middleware' => false];
@@ -888,7 +889,7 @@ public function testRequestStartedAtIsIsolatedBetweenConcurrentCoroutines(): voi
$app->instance('config', new Repository(['app' => ['timezone' => 'UTC']]));
$app->bootstrapWith([]);
- $router = Double::for(Router::class);
+ $router = Double::for(Router::class)->strict();
$router->allows('dispatch')->returns(new Response);
$kernel = new Kernel($app, $router);
@@ -933,7 +934,7 @@ protected function getKernel(): Kernel
{
return new Kernel(
new Application,
- Double::for(Router::class),
+ Double::for(Router::class)->strict(),
);
}
}
diff --git a/tests/Foundation/Http/WebSocketKernelTest.php b/tests/Foundation/Http/WebSocketKernelTest.php
index 82eda38d4f..a7eb1accaf 100644
--- a/tests/Foundation/Http/WebSocketKernelTest.php
+++ b/tests/Foundation/Http/WebSocketKernelTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
@@ -27,10 +28,10 @@ public function testHandleExceptionRetainsTheOriginalExceptionWhenReportingFails
$reportingFailure = new RuntimeException('Reporting failed');
$app = new Application;
- $app->instance(StdoutLoggerInterface::class, Double::for(StdoutLoggerInterface::class));
+ $app->instance(StdoutLoggerInterface::class, Double::for(StdoutLoggerInterface::class)->strict());
- $handler = Double::for(ExceptionHandlerContract::class);
- $handler->expects('report')->with($original)->throws($reportingFailure);
+ $handler = Double::for(ExceptionHandlerContract::class)->strict();
+ $handler->expects('report')->with(Argument::same($original))->throws($reportingFailure);
$handler->expects('render')->never();
$app->instance(ExceptionHandlerContract::class, $handler);
@@ -53,7 +54,7 @@ public function testHandleExceptionRetainsTheOriginalExceptionWhenResolvingTheHa
$resolutionFailure = new RuntimeException('Handler resolution failed');
$app = new Application;
- $app->instance(StdoutLoggerInterface::class, Double::for(StdoutLoggerInterface::class));
+ $app->instance(StdoutLoggerInterface::class, Double::for(StdoutLoggerInterface::class)->strict());
$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 cdbf3c316b..8e1e15f8cc 100644
--- a/tests/Foundation/Listeners/ReloadDotenvAndConfigTest.php
+++ b/tests/Foundation/Listeners/ReloadDotenvAndConfigTest.php
@@ -50,7 +50,7 @@ public function testReloadsUsingApplicationEnvironmentFile(): void
// Switch to .env.testing (simulates LoadEnvironmentVariables having selected it).
$app->loadEnvironmentFrom('.env.testing');
- $event = Double::for(BeforeWorkerStart::class);
+ $event = Double::for(BeforeWorkerStart::class)->strict();
$listener = $app->make(ReloadDotenvAndConfig::class);
$listener->handle($event);
@@ -68,7 +68,7 @@ public function testMissingEnvironmentFileClearsPreviouslyLoadedValues(): void
DotenvManager::load([$app->environmentPath()]);
$this->assertSame('Hypervel', Env::get('APP_NAME'));
- $event = Double::for(BeforeWorkerStart::class);
+ $event = Double::for(BeforeWorkerStart::class)->strict();
$listener = $app->make(ReloadDotenvAndConfig::class);
$listener->handle($event);
@@ -95,14 +95,14 @@ public function testWorkerReloadUsesCurrentCacheFileInsteadOfPreviousBootstrapSt
$filesystem->put($app->getCachedConfigPath(), 'make(ReloadDotenvAndConfig::class);
- $listener->handle(Double::for(BeforeWorkerStart::class));
+ $listener->handle(Double::for(BeforeWorkerStart::class)->strict());
$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(Double::for(BeforeWorkerStart::class));
+ $listener->handle(Double::for(BeforeWorkerStart::class)->strict());
$this->assertSame('from-file', Env::get('DOCTOR_WORKER_VALUE'));
$this->assertSame('from-file', $app->make(Repository::class)->get('worker.value'));
@@ -119,7 +119,7 @@ public function testReloadPreservesRepositoryIdentityAndMutationsMadeBeforeListe
$originalConfig->set('app.name', 'Reloaded Hypervel');
- $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class));
+ $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class)->strict());
$reloadedConfig = $app->make(Repository::class);
@@ -138,7 +138,7 @@ public function testReloadReplaysOverlappingMutationsInTheirOriginalOrder(): voi
$config->set('app.name', 'Second');
$config->set('app', ['name' => 'Last']);
- $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class));
+ $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class)->strict());
$this->assertSame(['name' => 'Last'], $config->get('app'));
}
@@ -151,7 +151,7 @@ public function testReloadPreservesUntouchedSiblingsWhenReplayingAChildMutation(
$config->set('app.name', 'Reloaded Hypervel');
- $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class));
+ $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class)->strict());
$this->assertSame('Reloaded Hypervel', $config->get('app.name'));
$this->assertSame($environment, $config->get('app.env'));
@@ -164,10 +164,10 @@ public function testTrackerSealsAfterReplayAndDoesNotRecordLaterMutations(): voi
$listener = $app->make(ReloadDotenvAndConfig::class);
$config->set('app.name', 'Boot Mutation');
- $listener->handle(Double::for(BeforeWorkerStart::class));
+ $listener->handle(Double::for(BeforeWorkerStart::class)->strict());
$config->set('app.name', 'Post Start Mutation');
- $listener->handle(Double::for(BeforeWorkerStart::class));
+ $listener->handle(Double::for(BeforeWorkerStart::class)->strict());
$this->assertSame('Boot Mutation', $config->get('app.name'));
}
@@ -179,9 +179,9 @@ public function testTrackerSealsWhenThereAreNoBootMutations(): void
$listener = $app->make(ReloadDotenvAndConfig::class);
$originalName = $config->get('app.name');
- $listener->handle(Double::for(BeforeWorkerStart::class));
+ $listener->handle(Double::for(BeforeWorkerStart::class)->strict());
$config->set('app.name', 'Post Start Mutation');
- $listener->handle(Double::for(BeforeWorkerStart::class));
+ $listener->handle(Double::for(BeforeWorkerStart::class)->strict());
$this->assertSame($originalName, $config->get('app.name'));
}
@@ -226,7 +226,7 @@ public function register(): void
$this->assertSame('bar', $config->get('custom.foo'));
$app->loadEnvironmentFrom('.env.testing');
- $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class));
+ $app->make(ReloadDotenvAndConfig::class)->handle(Double::for(BeforeWorkerStart::class)->strict());
$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 e354e6ac92..f1168819e3 100644
--- a/tests/Foundation/PendingChainTest.php
+++ b/tests/Foundation/PendingChainTest.php
@@ -33,7 +33,7 @@ public function testEnumConnectionAndQueueIdentifiersAreNormalized(): void
public function testDispatchPreservesZeroIdentifiersOnTheChainAndFirstJob(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->times(2)->resolves(fn (object $job): object => $job);
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
@@ -56,7 +56,7 @@ public function testDispatchPreservesZeroIdentifiersOnTheChainAndFirstJob(): voi
public function testDispatchUsesChainIdentifiersForEmptyFirstJobIdentifiers(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->resolves(fn (object $job): object => $job);
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
@@ -73,7 +73,7 @@ public function testDispatchUsesChainIdentifiersForEmptyFirstJobIdentifiers(): v
public function testDispatchIgnoresEmptyChainIdentifiers(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->resolves(fn (object $job): object => $job);
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
@@ -94,7 +94,7 @@ public function testDispatchIgnoresEmptyChainIdentifiers(): void
public function testDispatchKeepsFirstJobAttributesOverChainDefaults(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->resolves(fn (object $job): object => $job);
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
@@ -113,7 +113,7 @@ public function testDispatchKeepsFirstJobAttributesOverChainDefaults(): void
public function testDispatchAppliesChainDelayOnlyWithoutAFirstJobDelay(): void
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->expects('dispatch')->times(2)->resolves(fn (object $job): object => $job);
Container::getInstance()->instance(Dispatcher::class, $dispatcher);
diff --git a/tests/Foundation/Testing/Concerns/ExternalServiceOptInTest.php b/tests/Foundation/Testing/Concerns/ExternalServiceOptInTest.php
index cef8e27664..828b6807e9 100644
--- a/tests/Foundation/Testing/Concerns/ExternalServiceOptInTest.php
+++ b/tests/Foundation/Testing/Concerns/ExternalServiceOptInTest.php
@@ -181,7 +181,7 @@ public function testMeilisearchPreservesExplicitPrefixBeforeInitializingClient()
public function testMeilisearchWaitAcceptsSuccessfulTasks(): void
{
- $client = Double::for(MeilisearchClient::class);
+ $client = Double::for(MeilisearchClient::class)->strict();
$client->expects('getTasks')
->returns(new TasksResults([
'results' => [['uid' => 17, 'indexUid' => 'test_users', 'status' => 'enqueued']],
@@ -198,7 +198,7 @@ public function testMeilisearchWaitAcceptsSuccessfulTasks(): void
public function testMeilisearchWaitRejectsFailedTasks(): void
{
- $client = Double::for(MeilisearchClient::class);
+ $client = Double::for(MeilisearchClient::class)->strict();
$client->expects('getTasks')
->returns(new TasksResults([
'results' => [['uid' => 17, 'indexUid' => 'test_users', 'status' => 'processing']],
@@ -224,7 +224,7 @@ public function testMeilisearchWaitRejectsFailedTasks(): void
public function testMeilisearchWaitPropagatesTimeouts(): void
{
$timeout = new TimeOutException;
- $client = Double::for(MeilisearchClient::class);
+ $client = Double::for(MeilisearchClient::class)->strict();
$client->expects('getTasks')
->returns(new TasksResults([
'results' => [['uid' => 17, 'indexUid' => 'test_users', 'status' => 'enqueued']],
@@ -244,7 +244,7 @@ public function testMeilisearchWaitPropagatesTimeouts(): void
public function testMeilisearchWaitIgnoresPendingTasksForOtherPrefixes(): void
{
- $client = Double::for(MeilisearchClient::class);
+ $client = Double::for(MeilisearchClient::class)->strict();
$client->expects('getTasks')
->returns(new TasksResults([
'results' => [['uid' => 17, 'indexUid' => 'other_users', 'status' => 'enqueued']],
@@ -259,10 +259,10 @@ public function testMeilisearchWaitIgnoresPendingTasksForOtherPrefixes(): void
public function testMeilisearchCleanupWaitsForExactDeletionTasks(): void
{
- $index = Double::for(Indexes::class);
+ $index = Double::for(Indexes::class)->strict();
$index->allows('getUid')->returns('test_users');
- $client = Double::for(MeilisearchClient::class);
+ $client = Double::for(MeilisearchClient::class)->strict();
$client->expects('getIndexes')
->returns(new IndexesResults([
'results' => [$index],
@@ -285,10 +285,10 @@ public function testMeilisearchCleanupWaitsForExactDeletionTasks(): void
public function testMeilisearchCleanupPropagatesDeletionTaskFailures(): void
{
- $index = Double::for(Indexes::class);
+ $index = Double::for(Indexes::class)->strict();
$index->allows('getUid')->returns('test_users');
- $client = Double::for(MeilisearchClient::class);
+ $client = Double::for(MeilisearchClient::class)->strict();
$client->expects('getIndexes')
->returns(new IndexesResults([
'results' => [$index],
@@ -408,8 +408,8 @@ public function testAlgoliaAssignsADefaultPrefixAndRestoresTheExactHttpClient():
$expectedPrefix = $testToken === '' ? 'test_' : "test_{$testToken}_";
$originalClient = Algolia::getHttpClient();
- $previousClient = Double::for(HttpClientInterface::class);
- $testClient = Double::for(HttpClientInterface::class);
+ $previousClient = Double::for(HttpClientInterface::class)->strict();
+ $testClient = Double::for(HttpClientInterface::class)->strict();
$testClient->expects('sendRequest')->times(3)->returns(
new Response(200, ['content-type' => 'application/json'], '{"items":[]}')
);
@@ -439,7 +439,7 @@ public function testAlgoliaPreservesAnExplicitPrefix(): void
$this->setExternalServiceEnvironmentValue('ALGOLIA_SECRET', 'secret');
$originalClient = Algolia::getHttpClient();
- $testClient = Double::for(HttpClientInterface::class);
+ $testClient = Double::for(HttpClientInterface::class)->strict();
$testClient->expects('sendRequest')->times(3)->returns(
new Response(200, ['content-type' => 'application/json'], '{"items":[]}')
);
@@ -460,7 +460,7 @@ public function testAlgoliaPreservesAnExplicitPrefix(): void
public function testAlgoliaCleanupWaitsForExactDeletionTasks(): void
{
- $client = Double::for(AlgoliaSearchClient::class);
+ $client = Double::for(AlgoliaSearchClient::class)->strict();
$client->expects('listIndices')
->returns(['items' => [
['name' => 'test_users'],
@@ -482,7 +482,7 @@ public function testAlgoliaCleanupWaitsForExactDeletionTasks(): void
#[DataProvider('incompleteAlgoliaDeletionTasks')]
public function testAlgoliaCleanupRejectsIncompleteDeletionTasks(?array $task): void
{
- $client = Double::for(AlgoliaSearchClient::class);
+ $client = Double::for(AlgoliaSearchClient::class)->strict();
$client->expects('listIndices')
->returns(['items' => [['name' => 'test_users']]]);
$client->expects('deleteIndex')
@@ -517,7 +517,7 @@ public static function incompleteAlgoliaDeletionTasks(): array
public function testAlgoliaCleanupWaitsForRemainingTasksBeforeRejectingAnIncompleteResult(): void
{
- $client = Double::for(AlgoliaSearchClient::class);
+ $client = Double::for(AlgoliaSearchClient::class)->strict();
$client->expects('listIndices')
->returns(['items' => [
['name' => 'test_users'],
@@ -549,7 +549,7 @@ public function testAlgoliaCleanupWaitsForRemainingTasksBeforeRejectingAnIncompl
public function testAlgoliaCleanupPropagatesDeletionTaskFailures(): void
{
$failure = new RuntimeException('Index deletion failed.');
- $client = Double::for(AlgoliaSearchClient::class);
+ $client = Double::for(AlgoliaSearchClient::class)->strict();
$client->expects('listIndices')
->returns(['items' => [
['name' => 'test_users'],
@@ -582,9 +582,9 @@ public function testAlgoliaRestoresTheExactHttpClientWhenSetupFails(): void
$this->setExternalServiceEnvironmentValue('ALGOLIA_SECRET', 'secret');
$originalClient = Algolia::getHttpClient();
- $previousClient = Double::for(HttpClientInterface::class);
+ $previousClient = Double::for(HttpClientInterface::class)->strict();
$failure = new RuntimeException('Algolia probe failed');
- $testClient = Double::for(HttpClientInterface::class);
+ $testClient = Double::for(HttpClientInterface::class)->strict();
$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 2d8adf4160..19e52401ec 100644
--- a/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php
+++ b/tests/Foundation/Testing/Concerns/InteractsWithContainerTest.php
@@ -21,7 +21,7 @@ public function testSwap(): void
$this->assertSame('foo', $this->app->make(InstanceStub::class)->execute());
- $stub = Double::for(InstanceStub::class);
+ $stub = Double::for(InstanceStub::class)->strict();
$stub->expects('execute')->returns('bar');
$this->swap(InstanceStub::class, $stub);
diff --git a/tests/Foundation/Testing/Concerns/InteractsWithDatabaseTest.php b/tests/Foundation/Testing/Concerns/InteractsWithDatabaseTest.php
index 025fe79832..0423d472e9 100644
--- a/tests/Foundation/Testing/Concerns/InteractsWithDatabaseTest.php
+++ b/tests/Foundation/Testing/Concerns/InteractsWithDatabaseTest.php
@@ -74,7 +74,7 @@ public function testDatabaseAssertionsPreserveAnExplicitZeroNamedConnection(): v
public function testCastAsJsonUsesSpecifiedConnection(): void
{
$database = DB::getFacadeRoot();
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammar = new SQLiteGrammar($connection);
$connection->expects('getQueryGrammar')->returns($grammar);
@@ -206,7 +206,7 @@ public function testCastToJsonMariaDb(): void
protected function castAsJsonUsingGrammar(array|object|string $value, string $grammar): string
{
$database = DB::getFacadeRoot();
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$grammarClass = 'Hypervel\Database\Query\Grammars\\' . $grammar . 'Grammar';
$grammar = new $grammarClass($connection);
diff --git a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php
index cbf21aee42..d4346c4acf 100644
--- a/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php
+++ b/tests/Foundation/Testing/Concerns/InteractsWithParallelDatabaseTest.php
@@ -9,6 +9,7 @@
use Hypervel\Database\DatabaseManager;
use Hypervel\Database\QueryException;
use Hypervel\Database\Schema\Builder as SchemaBuilder;
+use Hypervel\Database\Schema\SchemaProxy;
use Hypervel\Foundation\Testing\Concerns\InteractsWithParallelDatabase;
use Hypervel\Support\Facades\DB;
use Hypervel\Testbench\TestCase;
@@ -127,11 +128,11 @@ public function testConfigureParallelDatabaseNameIsNoOpWithoutTestToken(): void
{
$config = $this->app->make('config');
$connection = $config->get('database.default');
- $original = $config->get("database.connections.{$connection}.database");
+ $config->set("database.connections.{$connection}.database", 'testing.sqlite');
- $this->configureParallelDatabaseName($this->app);
+ $this->withParallelEnvironment(null, false, fn () => $this->configureParallelDatabaseName($this->app));
- $this->assertSame($original, $config->get("database.connections.{$connection}.database"));
+ $this->assertSame('testing.sqlite', $config->get("database.connections.{$connection}.database"));
}
public function testConfigureParallelDatabaseNameSkipsInMemorySqlite(): void
@@ -325,10 +326,12 @@ public function testConfigureParallelDatabaseNameSkipsUnconfiguredConnection():
public function testEnsureParallelDatabaseExistsIsNoOpWithoutTestToken(): void
{
- // Without TEST_TOKEN, should be a no-op (no exceptions)
- $this->ensureParallelDatabaseExists();
+ $config = $this->app->make('config');
+ $connection = $config->get('database.default');
+ $config->set("database.connections.{$connection}.database", 'testing.sqlite');
+ $this->expectNoSchemaConnection();
- $this->assertTrue(true);
+ $this->withParallelEnvironment(null, false, fn () => $this->ensureParallelDatabaseExists());
}
public function testEnsureParallelDatabaseExistsSkipsLateConfiguredSqliteMemoryUri(): void
@@ -337,11 +340,9 @@ public function testEnsureParallelDatabaseExistsSkipsLateConfiguredSqliteMemoryU
$connection = $config->get('database.default');
$config->set("database.connections.{$connection}.database", 'file::memory:');
- $this->withParallelEnvironment('7', false, function (): void {
- $this->ensureParallelDatabaseExists();
+ $this->expectNoSchemaConnection();
- $this->assertTrue(true);
- });
+ $this->withParallelEnvironment('7', false, fn () => $this->ensureParallelDatabaseExists());
}
public function testEnsureParallelDatabaseExistsRejectsLateConfiguredSqliteFileUri(): void
@@ -369,11 +370,9 @@ public function testEnsureParallelDatabaseExistsHonorsWithoutDatabasesOption():
$connection = $config->get('database.default');
$config->set("database.connections.{$connection}.database", 'file:/tmp/database.sqlite?mode=rwc');
- $this->withParallelEnvironment('7', true, function (): void {
- $this->ensureParallelDatabaseExists();
+ $this->expectNoSchemaConnection();
- $this->assertTrue(true);
- });
+ $this->withParallelEnvironment('7', true, fn () => $this->ensureParallelDatabaseExists());
}
public function testEnsureParallelDatabaseExistsRecoversFromTheCurrentSuffixedDatabase(): void
@@ -392,19 +391,19 @@ public function testEnsureParallelDatabaseExistsRecoversFromTheCurrentSuffixedDa
[],
new PDOException('Database does not exist.')
);
- $schemaBuilder = Double::for(SchemaBuilder::class);
+ $schemaBuilder = Double::for(SchemaBuilder::class)->strict();
$schemaBuilder->expects('hasTable')
->with('__parallel_check')
->throws($queryException);
$schemaBuilder->expects('createDatabase')
->with('analytics_test_data_test_7')
->returns(true);
- $databaseConnection = Double::for(Connection::class);
+ $databaseConnection = Double::for(Connection::class)->strict();
$databaseConnection->expects('getSchemaBuilder')
->times(2)
->returns($schemaBuilder);
$connectionCalls = 0;
- $databaseManager = Double::for(DatabaseManager::class);
+ $databaseManager = Double::for(DatabaseManager::class)->strict();
$databaseManager->expects('connection')
->times(2)
->with($connection)
@@ -437,11 +436,21 @@ public function testEnsureParallelDatabaseExistsRecoversFromTheCurrentSuffixedDa
);
}
+ /**
+ * Verify that parallel setup never opens a schema connection.
+ */
+ private function expectNoSchemaConnection(): void
+ {
+ $schema = Double::for(SchemaProxy::class)->strict();
+ $schema->expects('connection')->never();
+ $this->app->instance('db.schema', $schema);
+ }
+
/**
* Run a callback with an isolated parallel-testing environment.
*/
private function withParallelEnvironment(
- string $token,
+ ?string $token,
bool $withoutDatabases,
Closure $callback
): void {
@@ -456,9 +465,14 @@ private function withParallelEnvironment(
);
$previousWithoutDatabases = $_SERVER['HYPERVEL_PARALLEL_TESTING_WITHOUT_DATABASES'] ?? null;
- putenv("TEST_TOKEN={$token}");
- $_SERVER['TEST_TOKEN'] = $token;
- $_ENV['TEST_TOKEN'] = $token;
+ if ($token === null) {
+ putenv('TEST_TOKEN');
+ unset($_SERVER['TEST_TOKEN'], $_ENV['TEST_TOKEN']);
+ } else {
+ putenv("TEST_TOKEN={$token}");
+ $_SERVER['TEST_TOKEN'] = $token;
+ $_ENV['TEST_TOKEN'] = $token;
+ }
if ($withoutDatabases) {
$_SERVER['HYPERVEL_PARALLEL_TESTING_WITHOUT_DATABASES'] = 1;
diff --git a/tests/Foundation/Testing/Concerns/InteractsWithRedisParallelTest.php b/tests/Foundation/Testing/Concerns/InteractsWithRedisParallelTest.php
index c1407569ad..82da93ab5d 100644
--- a/tests/Foundation/Testing/Concerns/InteractsWithRedisParallelTest.php
+++ b/tests/Foundation/Testing/Concerns/InteractsWithRedisParallelTest.php
@@ -476,7 +476,7 @@ public function testSetupRejectsUrlConfiguredConnections(): void
public function testTeardownClosesPoolsAndPropagatesAFlushFailure(): void
{
- $pools = Double::for(PoolManager::class);
+ $pools = Double::for(PoolManager::class)->strict();
$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 a647be860b..0980479e1e 100644
--- a/tests/Foundation/Testing/Concerns/InteractsWithTestCaseLifecycleTest.php
+++ b/tests/Foundation/Testing/Concerns/InteractsWithTestCaseLifecycleTest.php
@@ -53,7 +53,7 @@ public function testFoundationTeardownAttemptsEveryPhaseAndPreservesTheEarliestF
$parallelTesting = $this->app->make(ParallelTestingService::class);
try {
- $pooledConnection = Double::for(PoolConnection::class);
+ $pooledConnection = Double::for(PoolConnection::class)->strict();
$pooledConnection->expects('discard')->resolves(
function () use (&$steps, $databaseException): never {
$steps[] = 'database';
@@ -65,7 +65,7 @@ function () use (&$steps, $databaseException): never {
(new ReflectionProperty(DatabaseConnectionResolver::class, 'pooledConnections'))
->setValue(null, ['default' => $pooledConnection]);
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->strict();
$poolManager->expects('purgeAll')->resolves(
function () use (&$steps, $poolException): never {
$steps[] = 'pool';
@@ -74,7 +74,7 @@ function () use (&$steps, $poolException): never {
}
);
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$app->expects('resolved')->with(PoolManager::class)->returns(true);
$app->expects('make')->with(PoolManager::class)->returns($poolManager);
$app->expects('flush')->resolves(
@@ -85,7 +85,7 @@ function () use (&$steps, $applicationException): never {
}
);
- $parallelTestingMock = Double::for(ParallelTestingService::class);
+ $parallelTestingMock = Double::for(ParallelTestingService::class)->strict();
$parallelTestingMock->expects('callTearDownTestCaseCallbacks')->resolves(
function () use (&$steps, $parallelException): never {
$steps[] = 'parallel';
diff --git a/tests/Foundation/Testing/DatabaseConnectionResolverTest.php b/tests/Foundation/Testing/DatabaseConnectionResolverTest.php
index e2839ebae0..296a1daee9 100644
--- a/tests/Foundation/Testing/DatabaseConnectionResolverTest.php
+++ b/tests/Foundation/Testing/DatabaseConnectionResolverTest.php
@@ -135,7 +135,7 @@ public function testPurgeDisconnectsSharedResolverOwnedConnectionOnce(): void
{
$manager = $this->app->make('db');
$connection = $manager->connection('testing::read');
- $transactions = Double::for(DatabaseTransactionsManager::class);
+ $transactions = Double::for(DatabaseTransactionsManager::class)->strict();
$transactions->expects('rollback')->with('testing', 0);
$connection->setTransactionManager($transactions);
@@ -220,16 +220,16 @@ public function testResetCachedConnectionsCompletesEveryDiscardBeforeRethrowing(
{
DatabaseConnectionResolver::flushCachedConnections();
- $firstConnection = Double::for(Connection::class);
+ $firstConnection = Double::for(Connection::class)->strict();
$firstConnection->expects('resetForPool');
$firstConnection->expects('isReusable')->returns(false);
- $secondConnection = Double::for(Connection::class);
+ $secondConnection = Double::for(Connection::class)->strict();
$secondConnection->expects('resetForPool');
$secondConnection->expects('isReusable')->returns(false);
$failure = new RuntimeException('discard failed');
- $firstPooledConnection = Double::for(PooledConnection::class);
+ $firstPooledConnection = Double::for(PooledConnection::class)->strict();
$firstPooledConnection->expects('discard')->throws($failure);
- $secondPooledConnection = Double::for(PooledConnection::class);
+ $secondPooledConnection = Double::for(PooledConnection::class)->strict();
$secondPooledConnection->expects('discard');
(new ReflectionProperty(DatabaseConnectionResolver::class, 'connections'))->setValue([
diff --git a/tests/Foundation/Testing/DatabaseTransactionsManagerTest.php b/tests/Foundation/Testing/DatabaseTransactionsManagerTest.php
index 9d6227dac6..95f0710084 100644
--- a/tests/Foundation/Testing/DatabaseTransactionsManagerTest.php
+++ b/tests/Foundation/Testing/DatabaseTransactionsManagerTest.php
@@ -144,7 +144,7 @@ public function testPooledChildTransactionsDoNotCountAsTheirParentsWrapper(): vo
public function testRoleWrappersExcludeOnlyTheirResolvedOwnersTransaction(): void
{
$manager = new DatabaseTransactionsManager(['foo::write']);
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$writer = new SQLiteConnection(new PDO('sqlite::memory:'), config: ['name' => 'foo']);
$writer->setReadWriteType('write');
$database->expects('connection')->with('foo::write')->returns($writer);
@@ -178,7 +178,7 @@ public function testRoleWrappersExcludeOnlyTheirResolvedOwnersTransaction(): voi
*/
protected function beginWrappingTransactions(DatabaseTransactionsManager $manager, array $names = [null]): void
{
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
foreach ($names as $name) {
$connection = new SQLiteConnection(new PDO('sqlite::memory:'), config: ['name' => $name ?? 'foo']);
diff --git a/tests/Foundation/Testing/DatabaseTransactionsTest.php b/tests/Foundation/Testing/DatabaseTransactionsTest.php
index 33e39571ea..6fc631c580 100644
--- a/tests/Foundation/Testing/DatabaseTransactionsTest.php
+++ b/tests/Foundation/Testing/DatabaseTransactionsTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PDO;
use RuntimeException;
@@ -23,13 +24,13 @@ class DatabaseTransactionsTest extends TestCase
public function testBeginTransactionRestoresTheDispatcherWhenItFails(): void
{
$failure = new RuntimeException('Transaction begin failed.');
- $dispatcher = Double::for(Dispatcher::class);
- $connection = Double::for(Connection::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('setTransactionManager');
$connection->expects('getEventDispatcher')->returns($dispatcher);
$connection->expects('unsetEventDispatcher')->ordered();
$connection->expects('beginTransaction')->throws($failure)->ordered();
- $connection->expects('setEventDispatcher')->with($dispatcher)->ordered();
+ $connection->expects('setEventDispatcher')->with(Argument::same($dispatcher))->ordered();
$testCase = $this->createTestCase($connection);
try {
@@ -59,13 +60,13 @@ public function testTestTransactionIsRolledBackWhenTheTestLeavesATransactionOpen
public function testRollbackRestoresTheDispatcherWhenItFails(): void
{
$failure = new RuntimeException('Transaction rollback failed.');
- $dispatcher = Double::for(Dispatcher::class);
- $connection = Double::for(Connection::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
$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();
+ $connection->expects('setEventDispatcher')->with(Argument::same($dispatcher))->ordered();
$testCase = $this->createTestCase($connection);
try {
@@ -81,7 +82,7 @@ public function testRollbackRestoresTheDispatcherWhenItFails(): void
*/
private function createTestCase(Connection $connection): DatabaseTransactionsTestCase
{
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
$app = new Container;
$app->instance('db', $database);
diff --git a/tests/Foundation/Testing/DatabaseTruncationTest.php b/tests/Foundation/Testing/DatabaseTruncationTest.php
index 5623f7d858..f107d2305f 100644
--- a/tests/Foundation/Testing/DatabaseTruncationTest.php
+++ b/tests/Foundation/Testing/DatabaseTruncationTest.php
@@ -273,14 +273,14 @@ public function testRestoreSkipsDatabaseResolutionWhenNoInMemoryConnectionIsCach
public function testCachesAndRestoresConfiguredInMemoryConnections(): void
{
- $defaultPdo = Double::for(PDO::class);
- $namedPdo = Double::for(PDO::class);
- $sourceDefault = Double::for(PdoConnection::class);
- $sourceNamed = Double::for(PdoConnection::class);
+ $defaultPdo = Double::for(PDO::class)->strict();
+ $namedPdo = Double::for(PDO::class)->strict();
+ $sourceDefault = Double::for(PdoConnection::class)->strict();
+ $sourceNamed = Double::for(PdoConnection::class)->strict();
$sourceDefault->expects('getPdo')->returns($defaultPdo);
$sourceNamed->expects('getPdo')->returns($namedPdo);
- $sourceDatabase = Double::for(DatabaseManager::class);
+ $sourceDatabase = Double::for(DatabaseManager::class)->strict();
$sourceDatabase->expects('connection')->with(null)->returns($sourceDefault);
$sourceDatabase->expects('connection')->with('named')->returns($sourceNamed);
$sourceDatabase->expects('connection')->never()->with('file');
@@ -300,15 +300,15 @@ public function testCachesAndRestoresConfiguredInMemoryConnections(): void
$this->cacheInMemoryDatabases();
- $dispatcher = Double::for(DispatcherContract::class);
- $restoredDefault = Double::for(PdoConnection::class);
- $restoredNamed = Double::for(PdoConnection::class);
+ $dispatcher = Double::for(DispatcherContract::class)->strict();
+ $restoredDefault = Double::for(PdoConnection::class)->strict();
+ $restoredNamed = Double::for(PdoConnection::class)->strict();
$restoredDefault->expects('setPdo')->with(Argument::same($defaultPdo))->returns($restoredDefault);
$restoredDefault->expects('setEventDispatcher')->with(Argument::same($dispatcher))->returns($restoredDefault);
$restoredNamed->expects('setPdo')->with(Argument::same($namedPdo))->returns($restoredNamed);
$restoredNamed->expects('setEventDispatcher')->with(Argument::same($dispatcher))->returns($restoredNamed);
- $restoredDatabase = Double::for(DatabaseManager::class);
+ $restoredDatabase = Double::for(DatabaseManager::class)->strict();
$restoredDatabase->expects('connection')->with(null)->returns($restoredDefault);
$restoredDatabase->expects('connection')->with('named')->returns($restoredNamed);
$restoredDatabase->expects('connection')->never()->with('file');
@@ -342,8 +342,8 @@ public function testCachingInMemoryConnectionRequiresPdoConnection(): void
],
]));
- $database = Double::for(DatabaseManager::class);
- $database->expects('connection')->with(null)->returns(Double::for(Connection::class));
+ $database = Double::for(DatabaseManager::class)->strict();
+ $database->expects('connection')->with(null)->returns(Double::for(Connection::class)->strict());
$this->app->instance('db', $database);
$this->expectException(LogicException::class);
@@ -362,10 +362,10 @@ public function testRestoringInMemoryConnectionRequiresPdoConnection(): void
],
],
]));
- RefreshDatabaseState::$inMemoryConnections = ['default' => Double::for(PDO::class)];
+ RefreshDatabaseState::$inMemoryConnections = ['default' => Double::for(PDO::class)->strict()];
- $database = Double::for(DatabaseManager::class);
- $database->expects('connection')->with(null)->returns(Double::for(Connection::class));
+ $database = Double::for(DatabaseManager::class)->strict();
+ $database->expects('connection')->with(null)->returns(Double::for(Connection::class)->strict());
$this->app->instance('db', $database);
$this->expectException(LogicException::class);
@@ -456,12 +456,12 @@ public function truncate(): void
public function testMigratesWhenRetainedStateHasNoSelectedInMemoryPdo(): void
{
- $pdo = Double::for(PDO::class);
- $connection = Double::for(PdoConnection::class);
+ $pdo = Double::for(PDO::class)->strict();
+ $connection = Double::for(PdoConnection::class)->strict();
$connection->expects('getPdo')->returns($pdo);
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('call')->with('migrate:fresh', [
'--drop-views' => false,
'--drop-types' => false,
@@ -488,11 +488,11 @@ public function testMigratesWhenRetainedStateHasNoSelectedInMemoryPdo(): void
public function testAdoptsAMissingInMemoryPdoBeforeTheTruncationHook(): void
{
- $pdo = Double::for(PDO::class);
- $connection = Double::for(PdoConnection::class);
+ $pdo = Double::for(PDO::class)->strict();
+ $connection = Double::for(PdoConnection::class)->strict();
$connection->expects('getPdo')->returns($pdo);
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
$app = new Container;
@@ -586,7 +586,7 @@ function (array $tables) use (&$actual, &$withoutPrefix, $failure): void {
}
);
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->allows('getTablePrefix')->returns($prefix);
$dispatcher = new Dispatcher;
$connection->expects('getEventDispatcher')->returns($dispatcher);
diff --git a/tests/Foundation/Testing/LazilyRefreshDatabaseTest.php b/tests/Foundation/Testing/LazilyRefreshDatabaseTest.php
index b40076b0f1..ae0b00802f 100644
--- a/tests/Foundation/Testing/LazilyRefreshDatabaseTest.php
+++ b/tests/Foundation/Testing/LazilyRefreshDatabaseTest.php
@@ -70,7 +70,7 @@ public function testDatabaseIsRefreshedOnInteraction(): void
public function testDatabaseIsNotRefreshedWithoutInteraction(): void
{
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$this->app->instance(KernelContract::class, $kernel);
$kernel->expects('call')->never();
diff --git a/tests/Foundation/Testing/RefreshDatabaseTest.php b/tests/Foundation/Testing/RefreshDatabaseTest.php
index 5027489c4b..180de2fe4e 100644
--- a/tests/Foundation/Testing/RefreshDatabaseTest.php
+++ b/tests/Foundation/Testing/RefreshDatabaseTest.php
@@ -221,7 +221,7 @@ public function testRefreshTestDatabaseRestoresMockConsoleOutputAfterMigrationFa
{
$this->mockConsoleOutput = true;
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('call')
->throws(new RuntimeException('Migration failed.'));
@@ -252,15 +252,15 @@ public function testRefreshDatabaseDoesNotPublishMigratedWhenTheAfterHookFails()
$this->runTestsInCoroutine = false;
$this->afterRefreshingDatabaseException = new RuntimeException('After refresh failed.');
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('call')
->with('migrate:fresh', Argument::type('array'))
->returns(0);
$kernel->expects('setArtisan')->with(null);
- $pdo = Double::for(PDO::class);
- $eventDispatcher = Double::for(Dispatcher::class);
- $connection = Double::for(PdoConnection::class);
+ $pdo = Double::for(PDO::class)->strict();
+ $eventDispatcher = Double::for(Dispatcher::class)->strict();
+ $connection = Double::for(PdoConnection::class)->strict();
$connection->expects('getPdo')->returns($pdo);
$connection->expects('getNameWithReadWriteType')->returns('default');
$connection->expects('setTransactionManager');
@@ -272,9 +272,9 @@ public function testRefreshDatabaseDoesNotPublishMigratedWhenTheAfterHookFails()
$connection->expects('inTransaction')->returns(true);
$connection->expects('forgetRecordModificationState');
$connection->expects('rollBack');
- $connection->expects('setEventDispatcher')->times(2)->with($eventDispatcher);
+ $connection->expects('setEventDispatcher')->times(2)->with(Argument::same($eventDispatcher));
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->times(3)->with(null)->returns($connection);
$this->app = new Application;
@@ -307,18 +307,18 @@ public function testRefreshDatabaseCachesPdoBeforeMarkingTheDatabaseAsMigrated()
$this->migrateRefresh = false;
$this->runTestsInCoroutine = true;
- $pdo = Double::for(PDO::class);
- $connection = Double::for(PdoConnection::class);
+ $pdo = Double::for(PDO::class)->strict();
+ $connection = Double::for(PdoConnection::class)->strict();
$connection->expects('getPdo')->resolves(function () use ($pdo): PDO {
$this->assertFalse(RefreshDatabaseState::$migrated);
return $pdo;
});
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('call')
->with('migrate:fresh', Argument::type('array'))
->returns(0);
@@ -347,13 +347,13 @@ public function testRefreshDatabaseCachesPdoBeforeMarkingTheDatabaseAsMigrated()
public function testRestoreInMemoryDatabaseUsesResolvedDefaultConnectionName(): void
{
- $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);
+ $pdo = Double::for(PDO::class)->strict();
+ $eventDispatcher = Double::for(Dispatcher::class)->strict();
+ $connection = Double::for(PdoConnection::class)->strict();
+ $connection->expects('setPdo')->with(Argument::same($pdo));
+ $connection->expects('setEventDispatcher')->with(Argument::same($eventDispatcher));
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
RefreshDatabaseState::$inMemoryConnections = ['default' => $pdo];
@@ -412,15 +412,15 @@ public function testRefreshTestDatabaseCachesOnlyNamedInMemoryConnections(): voi
$this->migrateRefresh = false;
$this->runTestsInCoroutine = true;
- $memoryPdo = Double::for(PDO::class);
- $memoryConnection = Double::for(PdoConnection::class);
+ $memoryPdo = Double::for(PDO::class)->strict();
+ $memoryConnection = Double::for(PdoConnection::class)->strict();
$memoryConnection->expects('getPdo')->returns($memoryPdo);
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->never()->with('file');
$database->expects('connection')->with('memory')->returns($memoryConnection);
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('call')
->with('migrate:fresh', Argument::type('array'))
->returns(0);
@@ -460,12 +460,12 @@ public function testRefreshTestDatabaseRequiresPdoForInMemoryConnection(): void
$this->migrateRefresh = false;
$this->runTestsInCoroutine = true;
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('call')
->with('migrate:fresh', Argument::type('array'))
->returns(0);
@@ -491,9 +491,9 @@ public function testRefreshTestDatabaseRequiresPdoForInMemoryConnection(): void
public function testRestoreInMemoryDatabaseRequiresPdoConnection(): void
{
- $pdo = Double::for(PDO::class);
- $connection = Double::for(Connection::class);
- $database = Double::for(DatabaseManager::class);
+ $pdo = Double::for(PDO::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
RefreshDatabaseState::$inMemoryConnections = ['default' => $pdo];
@@ -521,14 +521,14 @@ public function testRefreshDatabaseRemigratesWhenAnInMemoryPdoCacheIsMissing():
$this->migrateRefresh = false;
$this->runTestsInCoroutine = true;
- $pdo = Double::for(PDO::class);
- $connection = Double::for(PdoConnection::class);
+ $pdo = Double::for(PDO::class)->strict();
+ $connection = Double::for(PdoConnection::class)->strict();
$connection->expects('getPdo')->returns($pdo);
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('call')
->with('migrate:fresh', Argument::type('array'))
->returns(0);
@@ -554,7 +554,7 @@ public function testRefreshDatabaseRemigratesWhenAnInMemoryPdoCacheIsMissing():
public function testRefreshTestDatabaseSkipsMigrationWhenTheSchemaAndPdoCacheAreReady(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
RefreshDatabaseState::$migrated = true;
RefreshDatabaseState::$inMemoryConnections = ['default' => $pdo];
$this->migrateRefresh = false;
@@ -579,20 +579,20 @@ public function testRefreshTestDatabaseSkipsMigrationWhenTheSchemaAndPdoCacheAre
public function testMigrateRefreshReplacesTheCachedInMemoryPdo(): void
{
- $oldPdo = Double::for(PDO::class);
- $freshPdo = Double::for(PDO::class);
+ $oldPdo = Double::for(PDO::class)->strict();
+ $freshPdo = Double::for(PDO::class)->strict();
RefreshDatabaseState::$migrated = true;
RefreshDatabaseState::$inMemoryConnections = ['default' => $oldPdo];
$this->migrateRefresh = true;
$this->runTestsInCoroutine = true;
- $connection = Double::for(PdoConnection::class);
+ $connection = Double::for(PdoConnection::class)->strict();
$connection->expects('getPdo')->returns($freshPdo);
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
- $kernel = Double::for(KernelContract::class);
+ $kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('call')
->with('migrate:fresh', Argument::type('array'))
->returns(0);
@@ -619,15 +619,15 @@ public function testMigrateRefreshReplacesTheCachedInMemoryPdo(): void
public function testBeginTransactionRestoresTheDispatcherWhenItFails(): void
{
$failure = new RuntimeException('Transaction begin failed.');
- $dispatcher = Double::for(Dispatcher::class);
- $connection = Double::for(Connection::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('setTransactionManager');
$connection->expects('getEventDispatcher')->returns($dispatcher);
$connection->expects('unsetEventDispatcher')->ordered();
$connection->expects('beginTransaction')->throws($failure)->ordered();
- $connection->expects('setEventDispatcher')->with($dispatcher)->ordered();
+ $connection->expects('setEventDispatcher')->with(Argument::same($dispatcher))->ordered();
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
$this->app->instance('db', $database);
@@ -643,16 +643,16 @@ public function testRollbackRestoresTheDispatcherAndKeepsMigrationBookkeepingWhe
{
RefreshDatabaseState::$migrated = true;
$failure = new RuntimeException('Transaction rollback failed.');
- $dispatcher = Double::for(Dispatcher::class);
- $connection = Double::for(PdoConnection::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
+ $connection = Double::for(PdoConnection::class)->strict();
$connection->expects('getEventDispatcher')->returns($dispatcher);
$connection->expects('unsetEventDispatcher')->ordered();
$connection->expects('inTransaction')->returns(false)->ordered();
$connection->expects('forgetRecordModificationState')->ordered();
$connection->expects('rollBack')->throws($failure)->ordered();
- $connection->expects('setEventDispatcher')->with($dispatcher)->ordered();
+ $connection->expects('setEventDispatcher')->with(Argument::same($dispatcher))->ordered();
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')->with(null)->returns($connection);
$this->app->instance('db', $database);
@@ -671,9 +671,9 @@ public function testRollbackRestoresTheDispatcherAndKeepsMigrationBookkeepingWhe
*/
protected function getMockedDatabase(): DatabaseManager
{
- $connection = Double::for(Connection::class);
+ $connection = Double::for(Connection::class)->strict();
$connection->expects('getNameWithReadWriteType')->returns('default');
- $eventDispatcher = Double::for(Dispatcher::class);
+ $eventDispatcher = Double::for(Dispatcher::class)->strict();
$connection->expects('getEventDispatcher')
->times(2)
->returns($eventDispatcher);
@@ -686,13 +686,13 @@ protected function getMockedDatabase(): DatabaseManager
$connection->expects('rollback');
$connection->expects('setEventDispatcher')
->times(2)
- ->with($eventDispatcher);
+ ->with(Argument::same($eventDispatcher));
$connection->expects('setTransactionManager');
$connection->expects('inTransaction')
->returns(true);
- $database = Double::for(DatabaseManager::class);
+ $database = Double::for(DatabaseManager::class)->strict();
$database->expects('connection')
->times(2)
->with(null)
diff --git a/tests/Foundation/WorkerCachedMaintenanceModeTest.php b/tests/Foundation/WorkerCachedMaintenanceModeTest.php
index 5367ef928a..d196e459ac 100644
--- a/tests/Foundation/WorkerCachedMaintenanceModeTest.php
+++ b/tests/Foundation/WorkerCachedMaintenanceModeTest.php
@@ -19,7 +19,7 @@ class WorkerCachedMaintenanceModeTest extends TestCase
public function testActiveCallsDriverOnlyOnceAndCachesResult(): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->returns(true);
$driver->expects('data')->returns(['status' => 503]);
@@ -32,7 +32,7 @@ public function testActiveCallsDriverOnlyOnceAndCachesResult(): void
public function testDataReturnsCachedPayloadWithoutRereadingDriver(): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->returns(true);
$driver->expects('data')->returns(['status' => 503, 'retry' => 60]);
@@ -44,7 +44,7 @@ public function testDataReturnsCachedPayloadWithoutRereadingDriver(): void
public function testActiveAndDataAreLoadedAtomically(): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->returns(true);
$driver->expects('data')->returns(['status' => 503]);
@@ -60,7 +60,7 @@ public function testActiveAndDataAreLoadedAtomically(): void
#[TestWith([true])]
public function testEmptyPayloadRechecksActivityBeforeCachingTheSnapshot(bool $remainsActive): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(true, $remainsActive);
$driver->expects('data')->returns([]);
@@ -76,7 +76,7 @@ public function testSnapshotIsReusedWithinRefreshInterval(): void
{
CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00'));
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->returns(false);
$driver->expects('data')->never();
@@ -93,7 +93,7 @@ public function testSnapshotRefreshesAfterInterval(): void
{
CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00'));
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(false, true);
$driver->expects('data')->returns(['status' => 503]);
@@ -110,7 +110,7 @@ public function testSnapshotRefreshesAtExactIntervalBoundary(): void
{
CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00'));
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(false, true);
$driver->expects('data')->returns(['status' => 503]);
@@ -127,7 +127,7 @@ public function testSnapshotDoesNotRefreshBeforeIntervalAcrossFractionalSeconds(
{
CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00.900000'));
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->returns(false);
$cached = new WorkerCachedMaintenanceMode($driver, refreshInterval: 5);
@@ -145,7 +145,7 @@ public function testActivePayloadRefreshesAfterInterval(): void
{
CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00'));
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(true, true);
$driver->expects('data')->times(2)->returns(['status' => 503], ['status' => 418]);
@@ -162,7 +162,7 @@ public function testZeroRefreshIntervalDisablesTimeRefresh(): void
{
CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00'));
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->returns(false);
$driver->expects('data')->never();
@@ -179,7 +179,7 @@ public function testNegativeRefreshIntervalDisablesTimeRefresh(): void
{
CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00'));
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->returns(false);
$driver->expects('data')->never();
@@ -194,7 +194,7 @@ public function testNegativeRefreshIntervalDisablesTimeRefresh(): void
public function testFlushCacheResetsSnapshot(): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(true, false);
$driver->expects('data')->returns(['status' => 503]);
@@ -211,7 +211,7 @@ public function testFlushCacheForcesRefreshWithinInterval(): void
{
CarbonImmutable::setTestNow($now = CarbonImmutable::parse('2026-01-01 00:00:00'));
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(false, true);
$driver->expects('data')->returns(['status' => 503]);
@@ -227,7 +227,7 @@ public function testFlushCacheForcesRefreshWithinInterval(): void
public function testActivateDelegatesToDriverAndFlushesCache(): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(false, true);
$driver->expects('data')->returns(['status' => 503]);
$driver->expects('activate')->with(['status' => 503]);
@@ -243,7 +243,7 @@ public function testActivateDelegatesToDriverAndFlushesCache(): void
public function testDeactivateDelegatesToDriverAndFlushesCache(): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(true, false);
$driver->expects('data')->returns(['status' => 503]);
$driver->expects('deactivate');
@@ -259,7 +259,7 @@ public function testDeactivateDelegatesToDriverAndFlushesCache(): void
public function testWhenNotActiveDataReturnsEmptyArrayWithoutCallingDriverData(): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->returns(false);
$driver->expects('data')->never();
@@ -270,7 +270,7 @@ public function testWhenNotActiveDataReturnsEmptyArrayWithoutCallingDriverData()
public function testAfterFlushAndRereadDecoratorReflectsUpdatedState(): void
{
- $driver = Double::for(MaintenanceModeContract::class);
+ $driver = Double::for(MaintenanceModeContract::class)->strict();
$driver->expects('active')->times(2)->returns(true, false);
$driver->expects('data')->returns(['status' => 503]);
diff --git a/tests/Grpc/ConnectionTest.php b/tests/Grpc/ConnectionTest.php
index 9653ad8d94..fe2d0a4ecb 100644
--- a/tests/Grpc/ConnectionTest.php
+++ b/tests/Grpc/ConnectionTest.php
@@ -31,6 +31,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use LogicException;
use PHPUnit\Framework\Attributes\TestWith;
use ReflectionProperty;
@@ -1197,7 +1198,7 @@ private function expectReported(?Throwable $failure): void
if ($failure === null) {
$handler->expects('report')->never();
} else {
- $handler->expects('report')->with($failure);
+ $handler->expects('report')->with(Argument::same($failure));
}
$container = new Container;
diff --git a/tests/Grpc/DeadlineTest.php b/tests/Grpc/DeadlineTest.php
index 39aa084ace..32f86d21c0 100644
--- a/tests/Grpc/DeadlineTest.php
+++ b/tests/Grpc/DeadlineTest.php
@@ -34,14 +34,18 @@ public function testCreatesALocalAbsoluteMonotonicDeadline(): void
public function testRejectsInvalidAndOverflowingLocalTimeouts(): void
{
- foreach ([0.0, -0.1, INF, NAN, (float) PHP_INT_MAX] as $seconds) {
+ foreach ([0.0, -0.1, INF, NAN] as $seconds) {
try {
Deadline::fromTimeout($seconds);
$this->fail('Expected the local deadline to be rejected.');
- } catch (InvalidArgumentException) {
- $this->addToAssertionCount(1);
+ } catch (InvalidArgumentException $exception) {
+ $this->assertSame('The gRPC timeout must be a positive finite number of seconds.', $exception->getMessage());
}
}
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessageIs('The gRPC timeout exceeds the monotonic clock range.');
+ Deadline::fromTimeout((float) PHP_INT_MAX);
}
public function testSaturatesHugeValidPeerTimeouts(): void
diff --git a/tests/Grpc/ExceptionMapperTest.php b/tests/Grpc/ExceptionMapperTest.php
index c3f670f58a..85724234be 100644
--- a/tests/Grpc/ExceptionMapperTest.php
+++ b/tests/Grpc/ExceptionMapperTest.php
@@ -14,6 +14,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
use Swoole\Coroutine\CanceledException;
@@ -48,7 +49,7 @@ public function testReportsUnexpectedFailuresAndDoesNotExposeTheirMessage(): voi
{
$handler = Double::for(ExceptionHandler::class)->strict();
$failure = new RuntimeException('database credentials leaked');
- $handler->expects('report')->with($failure);
+ $handler->expects('report')->with(Argument::same($failure));
$mapped = (new ExceptionMapper($handler))->map($failure);
@@ -61,7 +62,7 @@ public function testReportsInvalidServiceResponsesAsInternal(): void
{
$handler = Double::for(ExceptionHandler::class)->strict();
$failure = new RuntimeException('The stream yielded a string.');
- $handler->expects('report')->with($failure);
+ $handler->expects('report')->with(Argument::same($failure));
$mapped = (new ExceptionMapper($handler))->invalidResponse($failure);
@@ -85,7 +86,7 @@ public function testPreservesCancellationRaisedByTheReporter(): void
$failure = new RuntimeException('service failed');
$cancellation = new CanceledException;
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($failure)->throws($cancellation);
+ $handler->expects('report')->with(Argument::same($failure))->throws($cancellation);
$this->expectExceptionObject($cancellation);
@@ -104,7 +105,7 @@ public function testReporterFailureFallsBackWithoutChangingTheMappedStatus(): vo
$handler = Double::for(ExceptionHandler::class)->strict();
$failure = new RuntimeException('The original service failure.');
$handler->expects('report')
- ->with($failure)
+ ->with(Argument::same($failure))
->throws(new RuntimeException('The exception reporter failed.'));
$mapped = (new ExceptionMapper($handler))->map($failure);
diff --git a/tests/Grpc/GrpcOperationRunnerTest.php b/tests/Grpc/GrpcOperationRunnerTest.php
index d8aec38b70..65981cc324 100644
--- a/tests/Grpc/GrpcOperationRunnerTest.php
+++ b/tests/Grpc/GrpcOperationRunnerTest.php
@@ -21,6 +21,7 @@
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 Swoole\Coroutine\CanceledException;
@@ -124,7 +125,7 @@ function () use ($startingFailure): never {
throw $startingFailure;
},
));
- $this->bindReportingHandler()->expects('report')->with($completionFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($completionFailure));
try {
$runner->start($this->clientOperation());
@@ -163,7 +164,7 @@ function () use (&$finished, $secondFailure): never {
));
$handle = $runner->start($this->clientOperation());
$result = new GrpcOperationResult(new Status(StatusCode::Ok), null, 2);
- $this->bindReportingHandler()->expects('report')->with($secondFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($secondFailure));
try {
$handle->finish($result);
@@ -196,7 +197,7 @@ function () use (&$finished, $observerFailure): never {
throw $observerFailure;
},
));
- $this->bindReportingHandler()->expects('report')->with($observerFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($observerFailure));
$runner->start($this->clientOperation())->finish($result);
@@ -304,7 +305,7 @@ function () use ($observerFailure): never {
throw $observerFailure;
},
));
- $this->bindReportingHandler()->expects('report')->with($observerFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($observerFailure));
$handle = $runner->start($this->clientOperation());
$handle->finish(new GrpcOperationResult(null, new CanceledException, 1));
diff --git a/tests/Grpc/GrpcRouterTest.php b/tests/Grpc/GrpcRouterTest.php
index 3d079c5ec3..55893e11e9 100644
--- a/tests/Grpc/GrpcRouterTest.php
+++ b/tests/Grpc/GrpcRouterTest.php
@@ -31,6 +31,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\PreserveGlobalState;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use RuntimeException;
@@ -229,7 +230,7 @@ public function testGrpcPipelineMapsTheClosestFailureOnce(): void
$mapper = Double::for(ExceptionMapper::class)->strict();
$failure = new RuntimeException('service failed');
$mapped = new RpcException(StatusCode::Unknown, 'mapped');
- $mapper->expects('map')->with($failure)->returns($mapped);
+ $mapper->expects('map')->with(Argument::same($failure))->returns($mapped);
$container->instance(ExceptionMapper::class, $mapper);
$pipeline = new Pipeline($container);
@@ -252,7 +253,7 @@ public function testResponsePreparationIsIdempotent(): void
$request = Request::create('/testing.Service/Call', 'POST');
$expected = new GrpcHttpResponse('', ['grpc-status' => '0'], [], []);
$value = new GPBEmpty;
- $factory->expects('make')->with($request, $value)->returns($expected);
+ $factory->expects('make')->with(Argument::same($request), Argument::same($value))->returns($expected);
$container->instance(ResponseFactory::class, $factory);
$router = new GrpcRouter(new Dispatcher($container), $container);
diff --git a/tests/Grpc/HandleCallTest.php b/tests/Grpc/HandleCallTest.php
index ac002430b0..9363da06e4 100644
--- a/tests/Grpc/HandleCallTest.php
+++ b/tests/Grpc/HandleCallTest.php
@@ -239,7 +239,7 @@ public function testDeadlineCancellationReportsCleanupFailuresAndKeepsDeadlineSt
{
$cleanupException = new RuntimeException('Service cleanup failed.');
if ($cleanupThrows) {
- $this->exceptions->expects('report')->with($cleanupException);
+ $this->exceptions->expects('report')->with(Argument::same($cleanupException));
} else {
$this->exceptions->expects('report')->never();
}
diff --git a/tests/Grpc/MessageSerializerTest.php b/tests/Grpc/MessageSerializerTest.php
index 5632f9073a..dce434cdb6 100644
--- a/tests/Grpc/MessageSerializerTest.php
+++ b/tests/Grpc/MessageSerializerTest.php
@@ -67,10 +67,12 @@ public function testInvokesOtherCallableDeserializers(): void
public function testValidatesGeneratedAndCallableDeserializersBeforeAResponseArrives(): void
{
+ MessageSerializerCallable::$called = false;
+
MessageSerializer::validate([StringValue::class, 'decode']);
MessageSerializer::validate([MessageSerializerCallable::class, 'deserialize']);
- $this->addToAssertionCount(2);
+ $this->assertFalse(MessageSerializerCallable::$called);
}
public function testRejectsAnInvalidGeneratedDeserializerClass(): void
diff --git a/tests/Grpc/ResponseFactoryTest.php b/tests/Grpc/ResponseFactoryTest.php
index a4cb9e490c..4730888abc 100644
--- a/tests/Grpc/ResponseFactoryTest.php
+++ b/tests/Grpc/ResponseFactoryTest.php
@@ -245,7 +245,7 @@ public function testPreservesCancellationWhileAdvancingAStream(bool $deadlineExp
$cancellation = new CanceledException;
$cleanupException = new RuntimeException('Stream cleanup failed.');
if ($deadlineExpired && $cleanupThrows) {
- $handler->expects('report')->with($cleanupException);
+ $handler->expects('report')->with(Argument::same($cleanupException));
} else {
$handler->expects('report')->never();
}
diff --git a/tests/Grpc/RpcExceptionTest.php b/tests/Grpc/RpcExceptionTest.php
index 00a8063b4c..e19badbcd2 100644
--- a/tests/Grpc/RpcExceptionTest.php
+++ b/tests/Grpc/RpcExceptionTest.php
@@ -132,13 +132,17 @@ public function testFluentTrailerAndRetryMethodsAreImmutable(): void
public function testRejectsInvalidRetryDelay(): void
{
- foreach ([-0.1, INF, NAN, (float) PHP_INT_MAX] as $seconds) {
+ foreach ([-0.1, INF, NAN] as $seconds) {
try {
(new RpcException(StatusCode::Unavailable))->withRetryAfter($seconds);
$this->fail('Expected the retry delay to be rejected.');
- } catch (InvalidArgumentException) {
- $this->addToAssertionCount(1);
+ } catch (InvalidArgumentException $exception) {
+ $this->assertSame('The retry delay must be a non-negative finite number of seconds.', $exception->getMessage());
}
}
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessageIs('The retry delay exceeds the supported millisecond range.');
+ (new RpcException(StatusCode::Unavailable))->withRetryAfter((float) PHP_INT_MAX);
}
}
diff --git a/tests/Grpc/ServiceMethodTest.php b/tests/Grpc/ServiceMethodTest.php
index 8961c51792..54c4733c2f 100644
--- a/tests/Grpc/ServiceMethodTest.php
+++ b/tests/Grpc/ServiceMethodTest.php
@@ -35,8 +35,6 @@ public function testValidatesAServiceNameWithoutInventingAMethod(): void
{
ServiceMethod::validateServiceName('Example.API_Service');
- $this->addToAssertionCount(1);
-
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessageIs('The gRPC service name is invalid.');
diff --git a/tests/Grpc/TimeoutTest.php b/tests/Grpc/TimeoutTest.php
index 5fd642c435..4b7c272ec1 100644
--- a/tests/Grpc/TimeoutTest.php
+++ b/tests/Grpc/TimeoutTest.php
@@ -66,13 +66,17 @@ public function testRejectsMalformedWireTimeouts(): void
public function testRejectsInvalidOrUnrepresentableDurations(): void
{
- foreach ([-0.1, INF, NAN, 100_000_000 * 3600.0] as $seconds) {
+ foreach ([-0.1, INF, NAN] as $seconds) {
try {
Timeout::encode($seconds);
$this->fail('Expected the gRPC timeout to be rejected.');
- } catch (InvalidArgumentException) {
- $this->addToAssertionCount(1);
+ } catch (InvalidArgumentException $exception) {
+ $this->assertSame('The gRPC timeout must be a non-negative finite number of seconds.', $exception->getMessage());
}
}
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessageIs('The gRPC timeout exceeds the eight-digit wire limit.');
+ Timeout::encode(100_000_000 * 3600.0);
}
}
diff --git a/tests/Horizon/Console/WorkCommandTest.php b/tests/Horizon/Console/WorkCommandTest.php
index 94eda71115..02658139fd 100644
--- a/tests/Horizon/Console/WorkCommandTest.php
+++ b/tests/Horizon/Console/WorkCommandTest.php
@@ -32,13 +32,7 @@ public function testOncePassesEveryWorkerOptionAndAcceptsTheWorkersNullResult():
->with('default');
$worker->expects('setCache');
$worker->expects('runNextJob')
- ->with(Argument::all(function (string $connection, string $queue, WorkerOptions $options): bool {
- $this->assertSame('sync', $connection);
- $this->assertSame('default', $queue);
- $this->assertSame(7, $options->stopWhenEmptyFor);
-
- return true;
- }))
+ ->with('sync', 'default', Argument::capture($options))
->returns(null);
$this->app->instance(Worker::class, $worker);
@@ -48,6 +42,8 @@ public function testOncePassesEveryWorkerOptionAndAcceptsTheWorkersNullResult():
'--once' => true,
'--stop-when-empty-for' => 7,
])->assertSuccessful();
+ $this->assertInstanceOf(WorkerOptions::class, $options);
+ $this->assertSame(7, $options->stopWhenEmptyFor);
}
public function testHorizonWorkKeepsTheQueueWorkerOptionSurface(): void
diff --git a/tests/Http/Client/Destinations/CurlCapabilitiesTest.php b/tests/Http/Client/Destinations/CurlCapabilitiesTest.php
index f46536464d..52a8c37502 100644
--- a/tests/Http/Client/Destinations/CurlCapabilitiesTest.php
+++ b/tests/Http/Client/Destinations/CurlCapabilitiesTest.php
@@ -12,9 +12,9 @@ class CurlCapabilitiesTest extends TestCase
{
public function testAcceptsTheInstalledCurlTransport(): void
{
- CurlCapabilities::ensurePinningSupported();
+ $this->expectNotToPerformAssertions();
- $this->addToAssertionCount(1);
+ CurlCapabilities::ensurePinningSupported();
}
public function testRejectsAnUnusableCurlVersionResult(): void
@@ -31,14 +31,14 @@ public function testRejectsAnUnusableCurlVersionResult(): void
public function testAcceptsTheNonPermanentResolveFloor(): void
{
+ $this->expectNotToPerformAssertions();
+
FakeCurlCapabilities::useVersionInfo([
'version' => '7.75.0',
'features' => CURL_VERSION_SSL,
]);
CurlCapabilities::ensurePinningSupported();
-
- $this->addToAssertionCount(1);
}
public function testRejectsCurlBeforeTheNonPermanentResolveFloor(): void
@@ -73,12 +73,12 @@ public function testRejectsCurlWithoutSslSupport(): void
public function testCachesASuccessfulPinningCheck(): void
{
+ $this->expectNotToPerformAssertions();
+
CurlCapabilities::ensurePinningSupported();
FakeCurlCapabilities::useVersionInfo(false);
CurlCapabilities::ensurePinningSupported();
-
- $this->addToAssertionCount(1);
}
public function testRejectsAnHttpsProxyBeforeTheSupportedFloor(): void
diff --git a/tests/Http/Client/Guzzle/CoroutineStateTest.php b/tests/Http/Client/Guzzle/CoroutineStateTest.php
index 810d7f47da..88108a2090 100644
--- a/tests/Http/Client/Guzzle/CoroutineStateTest.php
+++ b/tests/Http/Client/Guzzle/CoroutineStateTest.php
@@ -22,6 +22,7 @@
use Hypervel\Tests\Http\Client\Guzzle\Fixtures\HttpServer;
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;
@@ -152,7 +153,7 @@ public function testThrowingExitTaskReportsAndCancelsTransfersWithoutSkippingEar
$url = $this->startServer();
$failure = new RuntimeException('exit callback failed');
$reporter = Double::for(ExceptionHandler::class)->strict();
- $reporter->expects('report')->with($failure);
+ $reporter->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandler::class, $reporter);
$transfer = null;
$earlierDeferRan = false;
diff --git a/tests/Http/HttpClientTest.php b/tests/Http/HttpClientTest.php
index fa10e3446c..24f6931ed6 100644
--- a/tests/Http/HttpClientTest.php
+++ b/tests/Http/HttpClientTest.php
@@ -3151,8 +3151,8 @@ public function testResponseSubclassesMaySelectTheirRequestException(): void
try {
$throw();
$this->fail('The custom request exception was not thrown.');
- } catch (CustomRequestException) {
- $this->addToAssertionCount(1);
+ } catch (CustomRequestException $exception) {
+ $this->assertSame($response, $exception->response);
}
}
}
@@ -6664,8 +6664,8 @@ public function testThrowIfStatusWorksWithNonErrorStatusCodes(): void
try {
$this->factory->get('http://foo.com/api')->throwIfStatus(201);
$this->fail('The request exception was not thrown.');
- } catch (RequestException) {
- $this->addToAssertionCount(1);
+ } catch (RequestException $exception) {
+ $this->assertSame(201, $exception->response->status());
}
$this->expectException(RequestException::class);
diff --git a/tests/Http/HttpRedirectResponseTest.php b/tests/Http/HttpRedirectResponseTest.php
index a03770bd14..22c2bb8701 100755
--- a/tests/Http/HttpRedirectResponseTest.php
+++ b/tests/Http/HttpRedirectResponseTest.php
@@ -44,7 +44,7 @@ public function testWithOnRedirect(): void
{
$response = new RedirectResponse('foo.bar');
$response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
- $session = Double::for(Store::class);
+ $session = Double::for(Store::class)->strict();
$response->setSession($session);
$session->expects('flash')->with('0', 'name');
$session->expects('flash')->with('1', 'age');
@@ -54,7 +54,7 @@ public function testWithOnRedirect(): void
public function testWithAssociativeArrayOnRedirect(): void
{
$response = new RedirectResponse('foo.bar');
- $session = Double::for(Store::class);
+ $session = Double::for(Store::class)->strict();
$session->expects('flash')->with('name', 'Taylor');
$response->setSession($session);
$response->with(['name' => 'Taylor']);
@@ -139,7 +139,7 @@ public function testFlashingErrorsOnRedirect(): void
$response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
$session = new Store('test', new NullSessionHandler);
$response->setSession($session);
- $provider = Double::for(MessageProvider::class);
+ $provider = Double::for(MessageProvider::class)->strict();
$provider->expects('getMessageBag')->returns(new MessageBag(['name' => ['required']]));
$response->withErrors($provider);
diff --git a/tests/Http/HttpResponseTest.php b/tests/Http/HttpResponseTest.php
index e85a6de833..004256d9d5 100644
--- a/tests/Http/HttpResponseTest.php
+++ b/tests/Http/HttpResponseTest.php
@@ -299,7 +299,7 @@ public function testFlashingErrorsOnRedirect(): void
$response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
$session = new Store('test', new NullSessionHandler);
$response->setSession($session);
- $provider = Double::for(MessageProvider::class);
+ $provider = Double::for(MessageProvider::class)->strict();
$provider->expects('getMessageBag')->returns(new MessageBag(['name' => ['required']]));
$response->withErrors($provider);
diff --git a/tests/Http/IterableStreamedResponseTest.php b/tests/Http/IterableStreamedResponseTest.php
index 2d6873345a..136677e9a3 100644
--- a/tests/Http/IterableStreamedResponseTest.php
+++ b/tests/Http/IterableStreamedResponseTest.php
@@ -10,6 +10,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
class IterableStreamedResponseTest extends TestCase
@@ -94,7 +95,7 @@ public function testStreamToPreservesWriterFailureWhenReleasingChunksAlsoFails()
unset($chunks);
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($releaseFailure);
+ $handler->expects('report')->with(Argument::same($releaseFailure));
Container::getInstance()->instance(ExceptionHandler::class, $handler);
try {
@@ -125,7 +126,7 @@ public function testSendContentPreservesOutputFailureWhenReleasingChunksAlsoFail
unset($chunks);
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($releaseFailure);
+ $handler->expects('report')->with(Argument::same($releaseFailure));
Container::getInstance()->instance(ExceptionHandler::class, $handler);
$level = ob_get_level();
diff --git a/tests/HttpServer/ServerTest.php b/tests/HttpServer/ServerTest.php
index 11098c9fea..251707133c 100644
--- a/tests/HttpServer/ServerTest.php
+++ b/tests/HttpServer/ServerTest.php
@@ -291,9 +291,9 @@ public function testOnRequestPreservesOperationFailureAcrossExhaustiveFinalizati
$terminateFailure = new RuntimeException('terminate failed');
$handler = $this->bindReportingHandler();
- $handler->expects('report')->with($handledFailure)->ordered();
- $handler->expects('report')->with($sendFailure)->ordered();
- $handler->expects('report')->with($terminateFailure)->ordered();
+ $handler->expects('report')->with(Argument::same($handledFailure))->ordered();
+ $handler->expects('report')->with(Argument::same($sendFailure))->ordered();
+ $handler->expects('report')->with(Argument::same($terminateFailure))->ordered();
$kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('handle')->never();
@@ -344,8 +344,8 @@ public function testOnRequestFinalizationIsExhaustiveAndPreservesTheFirstFailure
$sendFailure = new RuntimeException('send failed');
$terminateFailure = new RuntimeException('terminate failed');
$handler = $this->bindReportingHandler();
- $handler->expects('report')->with($sendFailure)->ordered();
- $handler->expects('report')->with($terminateFailure)->ordered();
+ $handler->expects('report')->with(Argument::same($sendFailure))->ordered();
+ $handler->expects('report')->with(Argument::same($terminateFailure))->ordered();
$kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('handle')->returns(new Response('OK'));
$kernel->expects('terminate')->throws($terminateFailure);
@@ -386,7 +386,7 @@ public function testRequestTerminatedObservesSendFailureBeforeLaterTerminationFa
CoordinatorManager::until(Constants::WORKER_START)->resume();
$sendFailure = new RuntimeException('send failed');
$terminateFailure = new RuntimeException('terminate failed');
- $this->bindReportingHandler()->expects('report')->with($terminateFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($terminateFailure));
$kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('handle')->returns(new Response('OK'));
@@ -758,8 +758,8 @@ public function testCancellationReportsTheHeldFailureAndCanceledListenerFailures
$listenerFailure = new RuntimeException('Canceled listener failed.');
$cancellation = new CanceledException;
$handler = $this->bindReportingHandler();
- $handler->expects('report')->with($listenerFailure)->ordered();
- $handler->expects('report')->with($heldFailure)->ordered();
+ $handler->expects('report')->with(Argument::same($listenerFailure))->ordered();
+ $handler->expects('report')->with(Argument::same($heldFailure))->ordered();
$kernel = Double::for(KernelContract::class)->strict();
$kernel->expects('handle')->returns(new Response('OK'));
diff --git a/tests/Image/Drivers/GdDriverTest.php b/tests/Image/Drivers/GdDriverTest.php
index 9a4938db32..c71a955df5 100644
--- a/tests/Image/Drivers/GdDriverTest.php
+++ b/tests/Image/Drivers/GdDriverTest.php
@@ -473,11 +473,11 @@ public function testQualityAffectsFileSize(): void
public function testEnsureRequirementsPasses(): void
{
+ $this->expectNotToPerformAssertions();
+
$driver = new GdDriver;
$driver->ensureRequirementsAreMet();
-
- $this->assertTrue(true);
}
public function testDimensionsReturnsTheDecodedSize(): void
diff --git a/tests/Image/Drivers/ImagickDriverTest.php b/tests/Image/Drivers/ImagickDriverTest.php
index 2f3598e28c..61a2365952 100644
--- a/tests/Image/Drivers/ImagickDriverTest.php
+++ b/tests/Image/Drivers/ImagickDriverTest.php
@@ -597,11 +597,11 @@ public function testQualityAffectsFileSize(): void
public function testEnsureRequirementsPasses(): void
{
+ $this->expectNotToPerformAssertions();
+
$driver = new ImagickDriver;
$driver->ensureRequirementsAreMet();
-
- $this->assertTrue(true);
}
protected function fakeImageContents(int $width = 100, int $height = 100): string
diff --git a/tests/Image/ImageManagerTest.php b/tests/Image/ImageManagerTest.php
index a44a729438..cbd366f281 100644
--- a/tests/Image/ImageManagerTest.php
+++ b/tests/Image/ImageManagerTest.php
@@ -236,7 +236,7 @@ public function testFromPathReturnsImageFromFilePath(): void
public function testFromPathIsLazy(): void
{
$app = $this->makeApp([]);
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('get')->never();
$app->bind(Filesystem::class, fn (): Filesystem => $filesystem);
@@ -251,12 +251,12 @@ public function testFromStorageReturnsImageFromStorageDiskPath(): void
{
$contents = $this->fakeImageContents();
- $disk = Double::for(FilesystemContract::class);
+ $disk = Double::for(FilesystemContract::class)->strict();
$disk->expects('get')
->with('images/avatar.jpg')
->returns($contents);
- $filesystem = Double::for(FilesystemFactory::class);
+ $filesystem = Double::for(FilesystemFactory::class)->strict();
$filesystem->expects('disk')
->with('public')
->returns($disk);
@@ -275,12 +275,12 @@ public function testFromStorageAcceptsBackedEnumDisk(): void
{
$contents = $this->fakeImageContents();
- $disk = Double::for(FilesystemContract::class);
+ $disk = Double::for(FilesystemContract::class)->strict();
$disk->expects('get')
->with('images/avatar.jpg')
->returns($contents);
- $filesystem = Double::for(FilesystemFactory::class);
+ $filesystem = Double::for(FilesystemFactory::class)->strict();
$filesystem->expects('disk')
->with(ImageDiskStub::Public)
->returns($disk);
@@ -299,12 +299,12 @@ public function testFromStorageAcceptsUnitEnumDisk(): void
{
$contents = $this->fakeImageContents();
- $disk = Double::for(FilesystemContract::class);
+ $disk = Double::for(FilesystemContract::class)->strict();
$disk->expects('get')
->with('images/avatar.jpg')
->returns($contents);
- $filesystem = Double::for(FilesystemFactory::class);
+ $filesystem = Double::for(FilesystemFactory::class)->strict();
$filesystem->expects('disk')
->with(ImageUnitDiskStub::public)
->returns($disk);
@@ -321,10 +321,10 @@ public function testFromStorageAcceptsUnitEnumDisk(): void
public function testFromStorageReportsAMissingPath(): void
{
- $disk = Double::for(FilesystemContract::class);
+ $disk = Double::for(FilesystemContract::class)->strict();
$disk->expects('get')->with('images/missing.jpg')->returns(null);
- $filesystem = Double::for(FilesystemFactory::class);
+ $filesystem = Double::for(FilesystemFactory::class)->strict();
$filesystem->expects('disk')->with('public')->returns($disk);
$app = $this->makeApp([]);
@@ -342,7 +342,7 @@ public function testFromStorageReportsAMissingPath(): void
public function testFromStorageIsLazy(): void
{
$app = $this->makeApp([]);
- $filesystem = Double::for(FilesystemFactory::class);
+ $filesystem = Double::for(FilesystemFactory::class)->strict();
$filesystem->expects('disk')->never();
$app->bind(FilesystemFactory::class, fn (): FilesystemFactory => $filesystem);
@@ -675,7 +675,7 @@ public function testCustomBackendProcessesWithoutInterventionInheritance(): void
{
$container = new Container;
$container->instance('config', new Repository(['images.default' => 'custom']));
- $driver = Double::for(Driver::class);
+ $driver = Double::for(Driver::class)->strict();
$driver->expects('process')
->with(
'source image',
diff --git a/tests/Integration/Auth/EloquentUserProviderCacheTest.php b/tests/Integration/Auth/EloquentUserProviderCacheTest.php
index a937c266b1..c774d7ea6a 100644
--- a/tests/Integration/Auth/EloquentUserProviderCacheTest.php
+++ b/tests/Integration/Auth/EloquentUserProviderCacheTest.php
@@ -590,7 +590,7 @@ public function testRetrieveByIdCachesResultWithEagerLoadedRelations(): void
$this->cacheCoordinator->expects('fill')
->times(2)
->with(
- $repo,
+ Argument::same($repo),
Argument::type(Closure::class),
$expectedKey,
300,
diff --git a/tests/Integration/Broadcasting/BroadcastManagerTest.php b/tests/Integration/Broadcasting/BroadcastManagerTest.php
index d4d7588bbe..e51a1574fa 100644
--- a/tests/Integration/Broadcasting/BroadcastManagerTest.php
+++ b/tests/Integration/Broadcasting/BroadcastManagerTest.php
@@ -371,7 +371,7 @@ public function testUniqueBroadcastPreparationHonorsRescue(string $phase, bool $
$this->app->instance(ExceptionHandler::class, $handler);
if ($rescued && ! $cancellation) {
- $handler->expects('report')->with($failure, []);
+ $handler->expects('report')->with(Argument::same($failure), []);
} else {
$handler->expects('report')->never();
}
@@ -460,7 +460,11 @@ public function testDeferredQueueFailuresHonorBroadcastRescueAndReleaseLocks(str
config(['cache.default' => 'array', 'broadcasting.default' => 'log']);
$failure = $mode === 'cancellation' ? new CanceledException : new RuntimeException('Queue unavailable.');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($failure, [])->times($mode === 'cancellation' ? 0 : 1);
+ if ($mode === 'cancellation') {
+ $handler->expects('report')->never();
+ } else {
+ $handler->expects('report')->with(Argument::same($failure), []);
+ }
$this->app->instance(ExceptionHandler::class, $handler);
if ($mode === 'rollback') {
@@ -1236,7 +1240,7 @@ public function testDeferredMercureRescuesPublicationAndLockCleanupFailures(stri
{
$failure = new RuntimeException('Broadcast operation failed.');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($failure, []);
+ $handler->expects('report')->with(Argument::same($failure), []);
$this->app->instance(ExceptionHandler::class, $handler);
$published = 0;
$manager = $this->synchronousMercureManager(function () use (&$published, $phase, $failure): void {
diff --git a/tests/Integration/Cache/MemoizedTaggedCacheTest.php b/tests/Integration/Cache/MemoizedTaggedCacheTest.php
index 88767c7aae..6fe43cab22 100644
--- a/tests/Integration/Cache/MemoizedTaggedCacheTest.php
+++ b/tests/Integration/Cache/MemoizedTaggedCacheTest.php
@@ -384,6 +384,7 @@ public function testStoreFlushClearsExistingTaggedMemoizedCacheInstancesWithoutD
Cache::memo()->flush();
$this->assertNull($cache->get('name'));
+ // Unlike Laravel, Hypervel's flush() dispatches the same store-wide events as clear().
$this->assertSame([CacheFlushing::class, CacheFlushed::class], array_map(get_class(...), $events));
$this->assertSame([[], []], array_map(static fn (CacheFlushing|CacheFlushed $event): array => $event->tags, $events));
}
diff --git a/tests/Integration/Cache/Redis/FlushOperationsIntegrationTest.php b/tests/Integration/Cache/Redis/FlushOperationsIntegrationTest.php
index f723b470d1..ecff3a8c23 100644
--- a/tests/Integration/Cache/Redis/FlushOperationsIntegrationTest.php
+++ b/tests/Integration/Cache/Redis/FlushOperationsIntegrationTest.php
@@ -8,7 +8,6 @@
use Hypervel\Support\Facades\Cache;
use Hypervel\Testbench\Attributes\WithConfig;
use Redis;
-use Throwable;
/**
* Integration tests for tag flush operations.
@@ -220,15 +219,8 @@ public function testFlushNonExistentTagGracefullyInAllMode(): void
Cache::tags(['real-tag'])->put('item', 'value', 60);
- // Flushing non-existent tag should not throw errors
- try {
- Cache::tags(['non-existent'])->flush();
- $this->assertTrue(true);
- } catch (Throwable $e) {
- $this->fail('Flushing non-existent tag should not throw: ' . $e->getMessage());
- }
+ Cache::tags(['non-existent'])->flush();
- // Real item should still exist
$this->assertSame('value', Cache::tags(['real-tag'])->get('item'));
}
@@ -238,15 +230,8 @@ public function testFlushNonExistentTagGracefullyInAnyMode(): void
Cache::tags(['real-tag'])->put('item', 'value', 60);
- // Flushing non-existent tag should not throw errors
- try {
- Cache::tags(['non-existent'])->flush();
- $this->assertTrue(true);
- } catch (Throwable $e) {
- $this->fail('Flushing non-existent tag should not throw: ' . $e->getMessage());
- }
+ Cache::tags(['non-existent'])->flush();
- // Real item should still exist
$this->assertSame('value', Cache::get('item'));
}
diff --git a/tests/Integration/Cache/Redis/RedisStoreTest.php b/tests/Integration/Cache/Redis/RedisStoreTest.php
index 29ca355aec..7204a36484 100644
--- a/tests/Integration/Cache/Redis/RedisStoreTest.php
+++ b/tests/Integration/Cache/Redis/RedisStoreTest.php
@@ -501,7 +501,7 @@ public function testFlushingTagsWhileASharedKeyIsRewrittenLeavesNoLiveValueUnind
$context = $store->getStore()->getContext();
$scanner = new GetEntries($context);
$requests = 0;
- $entries = Double::for(GetEntries::class);
+ $entries = Double::for(GetEntries::class)->strict();
$entries->expects('execute')
->times(2)
->resolves(function (array $tagIds) use ($scanner, $store, &$requests): LazyCollection {
diff --git a/tests/Integration/Console/CommandDurationThresholdTest.php b/tests/Integration/Console/CommandDurationThresholdTest.php
index c4d1adb4a3..8ab359431c 100644
--- a/tests/Integration/Console/CommandDurationThresholdTest.php
+++ b/tests/Integration/Console/CommandDurationThresholdTest.php
@@ -206,9 +206,8 @@ public function testUsesTheConfiguredDateTimezone(): void
public function testItHandlesCallingTerminateWithoutHandle(): void
{
- $this->app->make(Kernel::class)->terminate(new StringInput('foo'), 21);
+ $this->expectNotToPerformAssertions();
- // This is a placeholder just to show that the above did not throw an exception.
- $this->assertTrue(true);
+ $this->app->make(Kernel::class)->terminate(new StringInput('foo'), 21);
}
}
diff --git a/tests/Integration/Database/DatabaseLockTest.php b/tests/Integration/Database/DatabaseLockTest.php
index 952a79ad57..042d18f46b 100644
--- a/tests/Integration/Database/DatabaseLockTest.php
+++ b/tests/Integration/Database/DatabaseLockTest.php
@@ -277,10 +277,10 @@ public function testExpiredLockCannotBeRefreshedByPreviousOwner(): void
#[TestWith(['Table does not exist', 1146, false])]
public function testIgnoresConcurrencyException(string $message, int $code, bool $hasConcurrencyError): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
- $insertBuilder = Double::for(Builder::class);
- $deleteBuilder = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $insertBuilder = Double::for(Builder::class)->strict();
+ $deleteBuilder = Double::for(Builder::class)->strict();
$insertBuilder->expects('insert')->returns(true);
@@ -313,9 +313,9 @@ public function testAcquireThrowsConcurrencyExceptionInsideTransaction(): void
{
// REMOVED: upstream's case where a deadlock outside a transaction falls back to a takeover. Insert failures other
// than an existing lock always propagate; see CacheDatabaseLockTest::testInsertFailureOtherThanAnExistingLockPropagatesWithoutTakingOver().
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
- $insertBuilder = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $insertBuilder = Double::for(Builder::class)->strict();
$insertBuilder->expects('insert')->throws(
new QueryException(
@@ -342,9 +342,9 @@ public function testAcquireThrowsConcurrencyExceptionInsideTransaction(): void
#[TestWith(['Table does not exist', 1146, false])]
public function testReleaseIgnoresConcurrencyException(string $message, int $code, bool $hasConcurrencyError): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
- $deleteBuilder = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $deleteBuilder = Double::for(Builder::class)->strict();
$owner = 'owner-123';
@@ -376,9 +376,9 @@ public function testReleaseIgnoresConcurrencyException(string $message, int $cod
public function testPruneThrowsConcurrencyExceptionInsideTransaction(): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
- $deleteBuilder = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $deleteBuilder = Double::for(Builder::class)->strict();
$deleteBuilder->expects('where')->with('expiration', '<=', Argument::any())->returns($deleteBuilder);
$deleteBuilder->expects('delete')->throws(
@@ -403,9 +403,9 @@ public function testPruneThrowsConcurrencyExceptionInsideTransaction(): void
public function testReleaseThrowsConcurrencyExceptionInsideTransaction(): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
- $deleteBuilder = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $deleteBuilder = Double::for(Builder::class)->strict();
$owner = 'owner-123';
diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php
index aed463ac8d..3c0e0de27b 100644
--- a/tests/Integration/Database/EloquentBelongsToManyTest.php
+++ b/tests/Integration/Database/EloquentBelongsToManyTest.php
@@ -487,7 +487,7 @@ public function testFindMethodStringyKey(): void
$post->tags()->attach(TagStringPrimaryKey::all());
- $this->assertEquals($tag2->name, $post->tags()->find($tag2->id)->name);
+ $this->assertSame($tag2->id, $post->tags()->find($tag2->id)->id);
$this->assertCount(0, $post->tags()->findMany([]));
$this->assertCount(2, $post->tags()->findMany([$tag->id, $tag2->id]));
$this->assertCount(0, $post->tags()->findMany(new Collection));
@@ -509,12 +509,8 @@ public function testFindSoleMethod(): void
// Test with no records
$post->tags()->detach($tag);
- try {
- $post->tags()->findSole($tag);
- $this->fail('Expected RecordsNotFoundException was not thrown.');
- } catch (RecordsNotFoundException) {
- $this->assertTrue(true);
- }
+ $this->expectException(RecordsNotFoundException::class);
+ $post->tags()->findSole($tag);
}
#[TestWith([false])]
diff --git a/tests/Integration/Database/PooledConnectionTest.php b/tests/Integration/Database/PooledConnectionTest.php
index 8fee1a3a88..02f3225e0f 100644
--- a/tests/Integration/Database/PooledConnectionTest.php
+++ b/tests/Integration/Database/PooledConnectionTest.php
@@ -32,6 +32,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PDO;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
@@ -1447,7 +1448,7 @@ public function testPingCancellationDuringStartupReportingStopsThePublishedHeart
$childCoroutineId = null;
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, $cleanupStarted, $releaseCleanup, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
diff --git a/tests/Integration/Database/Sqlite/DatabaseSchemaBlueprintTest.php b/tests/Integration/Database/Sqlite/DatabaseSchemaBlueprintTest.php
index 2bd7bcbedb..db278746e3 100644
--- a/tests/Integration/Database/Sqlite/DatabaseSchemaBlueprintTest.php
+++ b/tests/Integration/Database/Sqlite/DatabaseSchemaBlueprintTest.php
@@ -5,7 +5,6 @@
namespace Hypervel\Tests\Integration\Database\Sqlite;
use Closure;
-use Exception;
use Hypervel\Contracts\Database\Query\Expression;
use Hypervel\Contracts\Foundation\Application as ApplicationContract;
use Hypervel\Database\Grammar;
@@ -1526,19 +1525,11 @@ public function testItDoesNotSetPrecisionHigherThanSupportedWhenRenamingTimestam
$table->timestamp('created_at');
});
- try {
- // this would only fail in mysql, postgres and sql server
- Schema::table('users', function (Blueprint $table) {
- $table->renameColumn('created_at', 'new_created_at');
- });
+ Schema::table('users', function (Blueprint $table) {
+ $table->renameColumn('created_at', 'new_created_at');
+ });
- $this->addToAssertionCount(1); // it did not throw
- } catch (Exception $e) {
- // Expecting something similar to:
- // QueryException
- // SQLSTATE[42000]: Syntax error or access violation: 1426 Too big precision 10 specified for 'my_timestamp'. Maximum is 6....
- $this->fail('test_it_does_not_set_precision_higher_than_supported_when_renaming_timestamps has failed. Error: ' . $e->getMessage());
- }
+ $this->assertSame(['new_created_at'], Schema::getColumnListing('users'));
}
public function testItEnsuresDroppingForeignKeyIsAvailable(): void
diff --git a/tests/Integration/Foundation/MaintenanceModeTest.php b/tests/Integration/Foundation/MaintenanceModeTest.php
index 71b315d194..0079901918 100644
--- a/tests/Integration/Foundation/MaintenanceModeTest.php
+++ b/tests/Integration/Foundation/MaintenanceModeTest.php
@@ -83,7 +83,7 @@ public function testBasicMaintenanceModeResponse(): void
public function testCacheMaintenanceModeAllowsRequestWhenDeactivatedWhileReadingPayload(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->allows('store')->with('maintenance')->returns($cache);
$cache->allows('has')->with('framework:down')->returns(true, false);
$cache->expects('get')->with('framework:down')->returns(null);
@@ -103,7 +103,7 @@ public function testCacheMaintenanceModeAllowsRequestWhenDeactivatedWhileReading
public function testActiveCacheMaintenanceModeWithAnEmptyPayloadBlocksRequests(): void
{
- $cache = Double::for(Factory::class, Repository::class);
+ $cache = Double::for(Factory::class, Repository::class)->strict();
$cache->allows('store')->with('maintenance')->returns($cache);
$cache->allows('has')->with('framework:down')->returns(true);
$cache->expects('get')->with('framework:down')->returns([]);
@@ -122,7 +122,7 @@ public function testActiveCacheMaintenanceModeWithAnEmptyPayloadBlocksRequests()
public function testConcurrentMaintenanceFileRemovalAllowsTheRequestToProceed(): void
{
$path = storage_path('framework/down');
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->allows('exists')->with($path)->returns(true, false);
$files->expects('get')->with($path)
->throws(new FileNotFoundException('removed'));
@@ -142,7 +142,7 @@ public function testUnreadableMaintenanceFileDoesNotAllowTheRequestToProceed():
$path = storage_path('framework/down');
$exception = new FileNotFoundException('unreadable');
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->allows('exists')->with($path)->returns(true);
$files->expects('get')->with($path)->throws($exception);
$this->app->instance(MaintenanceModeContract::class, new FileBasedMaintenanceMode($files));
@@ -428,7 +428,7 @@ public function testDownAttemptsReloadAfterEventFailureAndPreservesTheEventFailu
static fn (): never => throw $eventException,
);
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->with(Argument::same($eventException), [])->throws($reportException);
$this->app->instance(ExceptionHandler::class, $handler);
@@ -480,7 +480,7 @@ public function testUpAttemptsReloadAfterEventFailureAndPreservesTheEventFailure
public function testDownReportsDriverFailureBeforeMaintenanceStateIsCommitted(): void
{
- $mode = Double::for(MaintenanceModeContract::class);
+ $mode = Double::for(MaintenanceModeContract::class)->strict();
$mode->expects('active')->returns(false);
$mode->expects('activate')->throws(new RuntimeException('activation failed'));
$this->app->instance(MaintenanceModeContract::class, $mode);
@@ -498,12 +498,12 @@ public function testUpReportsDriverFailureBeforeMaintenanceStateIsCommitted(): v
file_put_contents(storage_path('framework/down'), json_encode(['status' => 503]));
$exception = new RuntimeException('deactivation failed');
- $mode = Double::for(MaintenanceModeContract::class);
+ $mode = Double::for(MaintenanceModeContract::class)->strict();
$mode->expects('active')->returns(true);
$mode->expects('deactivate')->throws($exception);
$this->app->instance(MaintenanceModeContract::class, $mode);
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->with(Argument::same($exception), []);
$this->app->instance(ExceptionHandler::class, $handler);
diff --git a/tests/Integration/Horizon/Feature/Listeners/MarkJobAsCompleteTest.php b/tests/Integration/Horizon/Feature/Listeners/MarkJobAsCompleteTest.php
index ac6fe312df..97e8e22d7a 100644
--- a/tests/Integration/Horizon/Feature/Listeners/MarkJobAsCompleteTest.php
+++ b/tests/Integration/Horizon/Feature/Listeners/MarkJobAsCompleteTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\Integration\Horizon\IntegrationTestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
class MarkJobAsCompleteTest extends IntegrationTestCase
{
@@ -31,7 +32,7 @@ public function testHandle(): void
$event->payload = $payload;
$jobs = Double::for(JobRepository::class)->strict();
- $jobs->expects('completed')->with($payload, false, false);
+ $jobs->expects('completed')->with(Argument::same($payload), false, false);
$tags = Double::for(TagRepository::class)->strict();
$tags->expects('monitored')->with([])->returns([]);
@@ -56,8 +57,8 @@ public function testHandleWithTag(): void
$event->queue = 'default';
$jobs = Double::for(JobRepository::class)->strict();
- $jobs->expects('completed')->with($payload, false, false);
- $jobs->expects('remember')->with('redis', 'default', $payload);
+ $jobs->expects('completed')->with(Argument::same($payload), false, false);
+ $jobs->expects('remember')->with('redis', 'default', Argument::same($payload));
$tags = Double::for(TagRepository::class)->strict();
$tags->expects('monitored')->with(['tag'])->returns(['tag']);
diff --git a/tests/Integration/Horizon/Feature/SupervisorTest.php b/tests/Integration/Horizon/Feature/SupervisorTest.php
index 8c8cf4574a..e6d28d0dcb 100644
--- a/tests/Integration/Horizon/Feature/SupervisorTest.php
+++ b/tests/Integration/Horizon/Feature/SupervisorTest.php
@@ -30,6 +30,7 @@
use Hypervel\Tests\Integration\Horizon\IntegrationTestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use Throwable;
@@ -486,7 +487,7 @@ public function testAutoScalerIsCalledOnLoopWhenAutoScaling(): void
// Mock the scaler...
$autoScaler = Double::for(AutoScaler::class)->strict();
- $autoScaler->expects('scale')->with($supervisor);
+ $autoScaler->expects('scale')->with(Argument::same($supervisor));
$this->app->singleton(AutoScaler::class, fn () => $autoScaler);
// Start the supervisor...
diff --git a/tests/Integration/Http/RequestDurationThresholdTest.php b/tests/Integration/Http/RequestDurationThresholdTest.php
index affa924ea4..61065f893c 100644
--- a/tests/Integration/Http/RequestDurationThresholdTest.php
+++ b/tests/Integration/Http/RequestDurationThresholdTest.php
@@ -192,9 +192,8 @@ public function testItClearsStartTimeAfterHandlingRequest(): void
public function testItHandlesCallingTerminateWithoutHandle(): void
{
- $this->app->make(Kernel::class)->terminate(Request::create('http://localhost/test-route'), new Response);
+ $this->expectNotToPerformAssertions();
- // this is a placeholder just to show that the above did not throw an exception.
- $this->assertTrue(true);
+ $this->app->make(Kernel::class)->terminate(Request::create('http://localhost/test-route'), new Response);
}
}
diff --git a/tests/Integration/Queue/CallQueuedHandlerTest.php b/tests/Integration/Queue/CallQueuedHandlerTest.php
index c88f6e82e6..c21f47a54b 100644
--- a/tests/Integration/Queue/CallQueuedHandlerTest.php
+++ b/tests/Integration/Queue/CallQueuedHandlerTest.php
@@ -129,7 +129,7 @@ public function testJobIsDeletedIfHasDeleteProperty(): void
$instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->expects('payload')->returns(['deleteWhenMissingModels' => true]);
$job->expects('resolveQueuedJobClass')->returns(CallQueuedHandlerExceptionThrower::class);
$job->expects('markAsFailed')->never();
@@ -149,7 +149,7 @@ public function testJobIsDeletedIfHasDeleteAttribute(): void
$instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->expects('payload')->returns(['deleteWhenMissingModels' => true]);
$job->expects('resolveQueuedJobClass')->returns(CallQueuedHandlerAttributeExceptionThrower::class);
$job->expects('markAsFailed')->never();
@@ -169,16 +169,16 @@ public function testBatchJobIsRecordedWhenDeletedDueToMissingModel(): void
$instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
- $batch = Double::for(Batch::class);
+ $batch = Double::for(Batch::class)->strict();
$batch->expects('recordSuccessfulJob')->with('job-uuid');
- $repository = Double::for(BatchRepository::class);
+ $repository = Double::for(BatchRepository::class)->strict();
$repository->expects('find')->with('test-batch-id')->returns($batch);
$this->app->instance(BatchRepository::class, $repository);
$serialized = serialize((new CallQueuedHandlerBatchableExceptionThrower)->withBatchId('test-batch-id'));
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->expects('resolveQueuedJobClass')->returns(CallQueuedHandlerBatchableExceptionThrower::class);
$job->expects('markAsFailed')->never();
$job->expects('delete');
@@ -205,10 +205,10 @@ public function testBatchJobIsRecordedAsFailedWhenModelIsMissing(): void
$exception = new ModelNotFoundException('Foo');
- $batch = Double::for(Batch::class);
+ $batch = Double::for(Batch::class)->strict();
$batch->expects('recordFailedJob')->with('job-uuid', Argument::same($exception));
- $repository = Double::for(BatchRepository::class);
+ $repository = Double::for(BatchRepository::class)->strict();
$repository->expects('find')->with('test-batch-id')->returns($batch);
$this->app->instance(BatchRepository::class, $repository);
@@ -222,19 +222,19 @@ public function testBatchJobIsRecordedAsFailedWhenModelIsMissing(): void
public function testUniqueJobLockIsReleasedFromPayloadWhenDeletedForMissingModel(): void
{
- $lock = Double::for(Lock::class);
+ $lock = Double::for(Lock::class)->strict();
$lock->expects('forceRelease');
- $cache = Double::for(Cache::class, LockProvider::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
$cache->allows('lock')->with('laravel_unique_job:TestJob:42')->returns($lock);
- $cacheFactory = Double::for(CacheFactory::class);
+ $cacheFactory = Double::for(CacheFactory::class)->strict();
$cacheFactory->allows('store')->with('array')->returns($cache);
$this->app->instance(CacheFactory::class, $cacheFactory);
$instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->allows('payload')->returns([
'deleteWhenMissingModels' => true,
'illuminate:log:context' => ['hidden' => $this->uniqueLockMetadata()],
@@ -250,23 +250,23 @@ public function testUniqueJobLockIsReleasedFromPayloadWhenDeletedForMissingModel
public function testUniqueJobLockOwnerIsRestoredFromPayloadWhenDeletedForMissingModel(): void
{
- $lock = Double::for(Lock::class);
+ $lock = Double::for(Lock::class)->strict();
$lock->expects('release');
- $cache = Double::for(Cache::class, LockProvider::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
$cache->expects('getStore')->returns(new WorkerArrayStore);
$cache->expects('restoreLock')
->with('laravel_unique_job:TestJob:42', 'owner-token')
->returns($lock);
$cache->expects('lock')->never();
- $cacheFactory = Double::for(CacheFactory::class);
+ $cacheFactory = Double::for(CacheFactory::class)->strict();
$cacheFactory->allows('store')->with('array')->returns($cache);
$this->app->instance(CacheFactory::class, $cacheFactory);
$instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->allows('payload')->returns([
'deleteWhenMissingModels' => true,
'illuminate:log:context' => ['hidden' => $this->uniqueLockMetadata('owner-token')],
@@ -352,13 +352,13 @@ public function testOwnerlessRegularUniqueListenerLockIsReleasedWhenFailingWithM
#[TestWith([2, 0])]
public function testMissingModelFailureReleasesAnOwnerlessUniqueUntilProcessingLockOnceBeforeProcessing(int $attempts, int $releases): void
{
- $lock = Double::for(Lock::class);
+ $lock = Double::for(Lock::class)->strict();
$lock->expects('forceRelease')->times($releases);
- $cache = Double::for(Cache::class, LockProvider::class);
+ $cache = Double::for(Cache::class, LockProvider::class)->strict();
$cache->allows('lock')->with('laravel_unique_job:TestJob:42')->returns($lock);
- $cacheFactory = Double::for(CacheFactory::class);
+ $cacheFactory = Double::for(CacheFactory::class)->strict();
$cacheFactory->allows('store')->with('array')->returns($cache);
$this->app->instance(CacheFactory::class, $cacheFactory);
@@ -404,12 +404,12 @@ public function testUniqueJobLockIsReleasedFromContextWhenFailingWithMissingMode
public function testDebouncedJobEventIsSkippedWithoutListeners(): void
{
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->expects('hasListeners')->with(JobDebounced::class)->returns(false);
$events->expects('dispatch')->never();
$this->app->instance('events', $events);
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->expects('getConnectionName')->never();
$job->expects('delete');
@@ -431,7 +431,7 @@ public function debounceId(): string
}
};
- $cache = Double::for(Cache::class);
+ $cache = Double::for(Cache::class)->strict();
$cache->expects('get')->with(DebounceLock::getKey($command))->returns('new-owner');
$this->app->instance(Cache::class, $cache);
@@ -444,7 +444,7 @@ public function testDebouncedJobEventRemainsVisibleToEventFake(): void
{
Event::fake([JobDebounced::class]);
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->expects('getConnectionName')->returns('database');
$job->expects('delete');
diff --git a/tests/Integration/Queue/Fixtures/OutboxClaimTestCase.php b/tests/Integration/Queue/Fixtures/OutboxClaimTestCase.php
index 8d12522c69..06c045569a 100644
--- a/tests/Integration/Queue/Fixtures/OutboxClaimTestCase.php
+++ b/tests/Integration/Queue/Fixtures/OutboxClaimTestCase.php
@@ -29,8 +29,8 @@
#[ResetRefreshDatabaseState]
abstract class OutboxClaimTestCase extends TestCase
{
- use VerifiesDoubles;
use DatabaseTruncation;
+ use VerifiesDoubles;
/**
* Enable independent database sessions for competing relay coroutines.
diff --git a/tests/Integration/Queue/ModelSerializationTest.php b/tests/Integration/Queue/ModelSerializationTest.php
index 79c8503cf7..cec2c54f76 100644
--- a/tests/Integration/Queue/ModelSerializationTest.php
+++ b/tests/Integration/Queue/ModelSerializationTest.php
@@ -510,9 +510,10 @@ public function testSerializationTypesEmptyCustomEloquentCollection(): void
$serialized = serialize($class);
- unserialize($serialized);
+ $restored = unserialize($serialized);
- $this->assertTrue(true);
+ $this->assertInstanceOf(ModelSerializationTestCustomUserCollection::class, $restored->collection);
+ $this->assertCount(0, $restored->collection);
}
#[WithConfig('database.default', 'testing')]
diff --git a/tests/Integration/Queue/QueueConnectionTest.php b/tests/Integration/Queue/QueueConnectionTest.php
index 611bfd6c53..dcd2f26007 100644
--- a/tests/Integration/Queue/QueueConnectionTest.php
+++ b/tests/Integration/Queue/QueueConnectionTest.php
@@ -61,7 +61,7 @@ protected function tearDown(): void
public function testJobWontGetDispatchedInsideATransaction(): void
{
$this->app->singleton('db.transactions', function (): DatabaseTransactionsManager {
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('callbackApplicableTransactions')
->returns(new Collection([new DatabaseTransactionRecord('sqlite', 1)]));
@@ -79,7 +79,7 @@ public function testJobWontGetDispatchedInsideATransaction(): void
public function testJobWillGetDispatchedInsideATransactionWhenExplicitlyIndicated(): void
{
$this->app->singleton('db.transactions', function (): DatabaseTransactionsManager {
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('addCallback')->never();
$transactionManager->expects('addCallbackForRollback')->never();
@@ -96,7 +96,7 @@ public function testJobWontGetDispatchedInsideATransactionWhenExplicitlyIndicate
$this->app->make('config')->set('queue.connections.sqs.after_commit', false);
$this->app->singleton('db.transactions', function (): DatabaseTransactionsManager {
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('callbackApplicableTransactions')
->returns(new Collection([new DatabaseTransactionRecord('sqlite', 1)]));
@@ -114,7 +114,7 @@ public function testJobWontGetDispatchedInsideATransactionWhenExplicitlyIndicate
public function testUniqueJobWontGetDispatchedInsideATransaction(): void
{
$this->app->singleton('db.transactions', function (): DatabaseTransactionsManager {
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('callbackApplicableTransactions')
->returns(new Collection([new DatabaseTransactionRecord('sqlite', 1)]));
@@ -132,7 +132,7 @@ public function testUniqueJobWontGetDispatchedInsideATransaction(): void
public function testUniqueJobWillGetDispatchedInsideATransactionWhenExplicitlyIndicated(): void
{
$this->app->singleton('db.transactions', function (): DatabaseTransactionsManager {
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('addCallback')->never();
$transactionManager->expects('addCallbackForRollback')->never();
@@ -149,7 +149,7 @@ public function testUniqueJobWontGetDispatchedInsideATransactionWhenExplicitlyIn
$this->app->make('config')->set('queue.connections.sqs.after_commit', false);
$this->app->singleton('db.transactions', function (): DatabaseTransactionsManager {
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('callbackApplicableTransactions')
->returns(new Collection([new DatabaseTransactionRecord('sqlite', 1)]));
diff --git a/tests/Integration/Queue/Redis/RateLimitedRedisStoreTest.php b/tests/Integration/Queue/Redis/RateLimitedRedisStoreTest.php
index c42cbdc7dc..cbdb5dfff3 100644
--- a/tests/Integration/Queue/Redis/RateLimitedRedisStoreTest.php
+++ b/tests/Integration/Queue/Redis/RateLimitedRedisStoreTest.php
@@ -25,8 +25,8 @@
// REMOVED: RateLimitedWithRedis is replaced by RateLimited::store('redis').
class RateLimitedRedisStoreTest extends TestCase
{
- use VerifiesDoubles;
use InteractsWithRedis;
+ use VerifiesDoubles;
public function testUnlimitedJobsAreExecuted(): void
{
diff --git a/tests/Integration/Queue/Redis/RedisQueueTest.php b/tests/Integration/Queue/Redis/RedisQueueTest.php
index 2e13fa948c..d271c77876 100644
--- a/tests/Integration/Queue/Redis/RedisQueueTest.php
+++ b/tests/Integration/Queue/Redis/RedisQueueTest.php
@@ -526,14 +526,14 @@ public function testPushJobQueueingAndJobQueuedEvents(): void
public function testBulkJobQueuedEvent(): void
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(JobPayloadFinalizing::class)->returns(false)->times(3);
$events->expects('hasListeners')->with(JobQueueing::class)->returns(true)->times(3);
$events->expects('hasListeners')->with(JobQueued::class)->returns(true)->times(3);
$events->expects('dispatch')->with(Argument::type(JobQueueing::class))->returns(null)->times(3);
$events->expects('dispatch')->with(Argument::type(JobQueued::class))->returns(null)->times(3);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->allows('bound')->with('queue.routes')->returns(false);
$container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes);
$container->expects('has')->with('db.transactions')->returns(false);
diff --git a/tests/Integration/Queue/SkipIfBatchCancelledTest.php b/tests/Integration/Queue/SkipIfBatchCancelledTest.php
index acc0eab451..fcfbd89116 100644
--- a/tests/Integration/Queue/SkipIfBatchCancelledTest.php
+++ b/tests/Integration/Queue/SkipIfBatchCancelledTest.php
@@ -55,7 +55,7 @@ protected function assertJobHandled(SkipCancelledBatchableTestJob $class, bool $
$class::$handled = false;
$instance = new CallQueuedHandler(new Dispatcher($this->app), $this->app);
- $job = Double::for(Job::class);
+ $job = Double::for(Job::class)->strict();
$job->expects('uuid')->returns('simple-test-uuid');
$job->expects('hasFailed')->returns(false);
diff --git a/tests/Integration/Queue/WorkCommandTest.php b/tests/Integration/Queue/WorkCommandTest.php
index 95760a020c..3d9fb1ebe2 100644
--- a/tests/Integration/Queue/WorkCommandTest.php
+++ b/tests/Integration/Queue/WorkCommandTest.php
@@ -302,7 +302,7 @@ public function testDisableLastRestartCheck(): void
Worker::$restartable = false;
- $cache = Double::for(Repository::class);
+ $cache = Double::for(Repository::class)->strict();
$cache->expects('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->never();
$cache->expects('get')->with('illuminate:queues:paused', false)->returns(false);
$cache->expects('get')
@@ -332,7 +332,7 @@ public function testDisablePauseQueueCheck(): void
Worker::$pausable = false;
- $cache = Double::for(Repository::class);
+ $cache = Double::for(Repository::class)->strict();
$cache->expects('get')->times(2)->with(Worker::RESTART_SIGNAL_CACHE_KEY)->returns(null);
diff --git a/tests/Integration/Reverb/RedisSharedStateTest.php b/tests/Integration/Reverb/RedisSharedStateTest.php
index 1d254d6428..ed9c68d8cd 100644
--- a/tests/Integration/Reverb/RedisSharedStateTest.php
+++ b/tests/Integration/Reverb/RedisSharedStateTest.php
@@ -137,8 +137,8 @@ public function testReleaseConnectionSlotIsSafeWhenNoSlotAcquired(): void
{
$this->state->releaseConnectionSlot('app1');
- // No exception — just a no-op
- $this->assertTrue(true);
+ $this->assertTrue($this->state->acquireConnectionSlot('app1', 1));
+ $this->assertFalse($this->state->acquireConnectionSlot('app1', 1));
}
// ── Key cleanup ────────────────────────────────────────────────────
diff --git a/tests/Integration/Support/ExceptionsFacadeTest.php b/tests/Integration/Support/ExceptionsFacadeTest.php
index 73f8c4ad19..45f941c37f 100644
--- a/tests/Integration/Support/ExceptionsFacadeTest.php
+++ b/tests/Integration/Support/ExceptionsFacadeTest.php
@@ -236,9 +236,9 @@ public function testFakeMethodReturnsExceptionHandlerFake(): void
public function testReportedExceptionsAreNotThrownByDefault(): void
{
- report(new Exception('Test exception'));
+ $this->expectNotToPerformAssertions();
- $this->assertTrue(true);
+ report(new Exception('Test exception'));
}
public function testReportedExceptionsAreNotThrownByDefaultWithExceptionHandling(): void
diff --git a/tests/Jwt/Http/ParserTest.php b/tests/Jwt/Http/ParserTest.php
index 0ce6d394c9..cddba93fb9 100644
--- a/tests/Jwt/Http/ParserTest.php
+++ b/tests/Jwt/Http/ParserTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
class ParserTest extends TestCase
@@ -218,13 +219,13 @@ public function testUsesTheFirstExtractorInTheChainThatFindsAToken(): void
$request = Request::create('/');
$missing = Double::for(TokenExtractor::class)->strict();
- $missing->expects('parseToken')->with($request)->returns(null);
+ $missing->expects('parseToken')->with(Argument::same($request))->returns(null);
$empty = Double::for(TokenExtractor::class)->strict();
- $empty->expects('parseToken')->with($request)->returns('');
+ $empty->expects('parseToken')->with(Argument::same($request))->returns('');
$found = Double::for(TokenExtractor::class)->strict();
- $found->expects('parseToken')->with($request)->returns('custom-token');
+ $found->expects('parseToken')->with(Argument::same($request))->returns('custom-token');
$unused = Double::for(TokenExtractor::class)->strict();
$unused->expects('parseToken')->never();
diff --git a/tests/Jwt/JwtGuardEventTest.php b/tests/Jwt/JwtGuardEventTest.php
index d1612dd92f..c259434518 100644
--- a/tests/Jwt/JwtGuardEventTest.php
+++ b/tests/Jwt/JwtGuardEventTest.php
@@ -342,7 +342,7 @@ public function testAttemptingRegistersListener(): void
$listener = static fn (): null => null;
$events = Double::for(Dispatcher::class)->strict();
- $events->expects('listen')->with(Attempting::class, $listener);
+ $events->expects('listen')->with(Attempting::class, Argument::same($listener));
$guard = $this->createGuard();
$guard->setDispatcher($events);
diff --git a/tests/Jwt/JwtGuardTest.php b/tests/Jwt/JwtGuardTest.php
index c1b9d640fb..9e76a2444e 100644
--- a/tests/Jwt/JwtGuardTest.php
+++ b/tests/Jwt/JwtGuardTest.php
@@ -31,6 +31,7 @@
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;
@@ -233,8 +234,8 @@ public function testAttemptReturnsTokenOnValidCredentials(): void
$provider = Double::for(UserProvider::class)->strict();
$provider->allows('retrieveByCredentials')->with($credentials)->returns($user);
- $provider->allows('validateCredentials')->with($user, $credentials)->returns(true);
- $provider->expects('rehashPasswordIfRequired')->with($user, $credentials);
+ $provider->allows('validateCredentials')->with(Argument::same($user), $credentials)->returns(true);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), $credentials);
$jwtManager = Double::for(ManagerContract::class)->strict();
$jwtManager->expects('encode')->returns('new-token');
@@ -1092,7 +1093,7 @@ public function testOnceDoesNotMintTokenAndSetsUser(): void
$provider = Double::for(UserProvider::class)->strict();
$provider->expects('retrieveByCredentials')->returns($user);
$provider->expects('validateCredentials')->returns(true);
- $provider->expects('rehashPasswordIfRequired')->with($user, $credentials);
+ $provider->expects('rehashPasswordIfRequired')->with(Argument::same($user), $credentials);
$jwtManager = Double::for(ManagerContract::class)->strict();
$jwtManager->expects('encode')->never();
diff --git a/tests/Mail/MailMailableTest.php b/tests/Mail/MailMailableTest.php
index 7fe110081d..6e3889b755 100644
--- a/tests/Mail/MailMailableTest.php
+++ b/tests/Mail/MailMailableTest.php
@@ -629,7 +629,7 @@ public function testMailerMayBeSet(): void
public function testMailablePriorityGetsSent(): void
{
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$mailer = new Mailer('array', $view, new ArrayTransport);
@@ -648,7 +648,7 @@ public function testMailablePriorityGetsSent(): void
public function testMailableIsReleasedWithoutGarbageCollectionAfterSettingPriority(): void
{
- $mailer = new Mailer('array', Double::for(ViewFactory::class), new ArrayTransport);
+ $mailer = new Mailer('array', Double::for(ViewFactory::class)->strict(), new ArrayTransport);
$garbageCollectionEnabled = gc_enabled();
gc_disable();
@@ -674,7 +674,7 @@ public function testMailableIsReleasedWithoutGarbageCollectionAfterSettingPriori
public function testEnvelopeCallbackCanInspectAndReplaceRenderedContent(): void
{
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$mailer = new Mailer('array', $view, new ArrayTransport);
$renderedContent = null;
@@ -737,7 +737,7 @@ public function testMailableMergeMetadata(): void
$this->assertTrue($mailable->hasMetadata('total', 1670));
$this->stubMailer();
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$mailer = new Mailer('array', $view, new ArrayTransport);
$sentMessage = $mailer->send($mailable);
@@ -754,7 +754,7 @@ public function testMailableMetadataGetsSent(): void
{
$this->stubMailer();
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$mailer = new Mailer('array', $view, new ArrayTransport);
@@ -799,7 +799,7 @@ public function testMailableTagGetsSent(): void
{
$this->stubMailer();
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$mailer = new Mailer('array', $view, new ArrayTransport);
@@ -1061,13 +1061,13 @@ public function envelope(): Envelope
public function testHasAttachmentWithDeclaredStorageAttachmentsAndNoEnvelope(): void
{
- $storage = Double::for(FilesystemAdapter::class);
+ $storage = Double::for(FilesystemAdapter::class)->strict();
$storage->allows('mimeType')->with('report.txt')->returns('text/plain');
$storage->allows('mimeType')->with('other.txt')->returns('text/plain');
$storage->allows('get')->with('report.txt')->returns('report content');
$storage->allows('get')->with('other.txt')->returns('other content');
- $factory = Double::for(FilesystemFactory::class);
+ $factory = Double::for(FilesystemFactory::class)->strict();
$factory->allows('disk')->with('documents')->returns($storage);
$this->app->instance(FilesystemFactory::class, $factory);
@@ -1248,11 +1248,11 @@ public function testItCanCheckForStorageBasedAttachments(): void
public function testStorageAttachmentOmitsFailedMimeDetection(): void
{
- $storage = Double::for(FilesystemAdapter::class);
+ $storage = Double::for(FilesystemAdapter::class)->strict();
$storage->expects('mimeType')->with('report.txt')->returns(false);
$storage->expects('get')->with('report.txt')->returns('file content');
- $factory = Double::for(FilesystemFactory::class);
+ $factory = Double::for(FilesystemFactory::class)->strict();
$factory->expects('disk')->with('documents')->returns($storage);
$this->app->instance(FilesystemFactory::class, $factory);
@@ -1269,11 +1269,11 @@ public function testStorageAttachmentOmitsFailedMimeDetection(): void
public function testExplicitStorageAttachmentMimeSkipsDetection(): void
{
- $storage = Double::for(FilesystemAdapter::class);
+ $storage = Double::for(FilesystemAdapter::class)->strict();
$storage->expects('mimeType')->never();
$storage->expects('get')->with('report.txt')->returns('file content');
- $factory = Double::for(FilesystemFactory::class);
+ $factory = Double::for(FilesystemFactory::class)->strict();
$factory->expects('disk')->with('documents')->returns($storage);
$this->app->instance(FilesystemFactory::class, $factory);
@@ -1433,7 +1433,7 @@ public function testSubjectAssertionMatchesTheDeliveredDefaultSubject(): void
{
$this->stubMailer();
- $mailer = new Mailer('array', Double::for(ViewFactory::class), new ArrayTransport);
+ $mailer = new Mailer('array', Double::for(ViewFactory::class)->strict(), new ArrayTransport);
foreach ([new WelcomeMailableStub, (new WelcomeMailableStub)->subject('0')] as $mailable) {
$mailable->from('sender@example.com')->to('recipient@example.com')->html('test content');
@@ -1466,7 +1466,7 @@ public function envelope(): Envelope
public function testMailableHeadersGetSent(): void
{
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$mailer = new Mailer('array', $view, new ArrayTransport);
@@ -1490,7 +1490,7 @@ public function testMailableHeadersGetSent(): void
public function testMailableIsReleasedWithoutGarbageCollectionAfterSendingWithHeaders(): void
{
- $mailer = new Mailer('array', Double::for(ViewFactory::class), new ArrayTransport);
+ $mailer = new Mailer('array', Double::for(ViewFactory::class)->strict(), new ArrayTransport);
$garbageCollectionEnabled = gc_enabled();
gc_disable();
@@ -1562,7 +1562,7 @@ public function testMailablesCanBeTapped(): void
*/
protected function stubMailer(): void
{
- $mailer = Double::for(Mailer::class);
+ $mailer = Double::for(Mailer::class)->strict();
$mailer->allows('render')
->returns('');
diff --git a/tests/Mail/MailMailerTest.php b/tests/Mail/MailMailerTest.php
index bb3991788b..1fdad671d8 100644
--- a/tests/Mail/MailMailerTest.php
+++ b/tests/Mail/MailMailerTest.php
@@ -87,7 +87,7 @@ public function testMailerSendSendsMessageWithCcAndBccRecipients(): void
public function testMailerSendSendsMessageWithProperViewContentUsingHtmlStrings(): void
{
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$view->expects('make')->never();
$mailer = new Mailer('array', $view, new ArrayTransport);
@@ -107,7 +107,7 @@ function (Message $message): void {
public function testMailerSendSendsMessageWithProperViewContentUsingStringCallbacks(): void
{
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$view->expects('make')->never();
$mailer = new Mailer('array', $view, new ArrayTransport);
@@ -138,7 +138,7 @@ function (Message $message): void {
public function testMailerSendSendsMessageWithProperViewContentUsingHtmlMethod(): void
{
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$view->expects('make')->never();
$mailer = new Mailer('array', $view, new ArrayTransport);
@@ -350,7 +350,7 @@ public function testEventsAreSkippedWhenNoListenersAreRegistered(): void
{
$view = $this->viewFactory('rendered.view');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(MessageSending::class)->returns(false);
$events->expects('hasListeners')->with(MessageSent::class)->returns(false);
$events->expects('until')->never();
@@ -369,7 +369,7 @@ public function testMacroable(): void
return 'bar';
});
- $mailer = new Mailer('array', Double::for(ViewFactory::class), new ArrayTransport);
+ $mailer = new Mailer('array', Double::for(ViewFactory::class)->strict(), new ArrayTransport);
$this->assertSame(
'bar',
@@ -379,7 +379,7 @@ public function testMacroable(): void
public function testSendQueuedMailableReturnsNull(): void
{
- $view = Double::for(ViewFactory::class);
+ $view = Double::for(ViewFactory::class)->strict();
$view->expects('make')->never();
$queueFake = new QueueFake($this->app);
@@ -400,11 +400,11 @@ public function testSendQueuedMailableReturnsNull(): void
*/
protected function viewFactory(string ...$rendered): ViewFactory
{
- $factory = Double::for(ViewFactory::class);
+ $factory = Double::for(ViewFactory::class)->strict();
$views = [];
foreach ($rendered as $contents) {
- $view = Double::for(ViewContract::class);
+ $view = Double::for(ViewContract::class)->strict();
$view->expects('render')->returns($contents);
$views[] = $view;
}
diff --git a/tests/Mail/MailResendTransportTest.php b/tests/Mail/MailResendTransportTest.php
index 987ead21ad..ed86e8e036 100644
--- a/tests/Mail/MailResendTransportTest.php
+++ b/tests/Mail/MailResendTransportTest.php
@@ -48,7 +48,7 @@ public function testSend(): void
$message->bcc('bcc@example.com');
$message->replyTo(new Address('reply@example.com', 'Reply'));
- $emails = Double::for(EmailService::class);
+ $emails = Double::for(EmailService::class)->strict();
$emails->expects('send')
->with(Argument::satisfies(function (array $arg): bool {
return $arg['from'] === 'sender@example.com'
@@ -88,7 +88,7 @@ public function testSendError(): void
$message->sender('sender@example.com');
$message->to('recipient@example.com');
- $emails = Double::for(EmailService::class);
+ $emails = Double::for(EmailService::class)->strict();
$emails->expects('send')
->throws(new Exception('API key is invalid'));
diff --git a/tests/Mail/MailableQueuedTest.php b/tests/Mail/MailableQueuedTest.php
index 9561895ba3..fd4c6f9c28 100644
--- a/tests/Mail/MailableQueuedTest.php
+++ b/tests/Mail/MailableQueuedTest.php
@@ -366,7 +366,7 @@ public function testQueueMethodsPreserveStringAndEnumQueueNames(): void
*/
protected function getMocks(): array
{
- return ['smtp', Double::for(Factory::class), Double::for(TransportInterface::class)];
+ return ['smtp', Double::for(Factory::class)->strict(), Double::for(TransportInterface::class)->strict()];
}
/**
diff --git a/tests/Notifications/NotificationBroadcastChannelTest.php b/tests/Notifications/NotificationBroadcastChannelTest.php
index c5ee234b95..8e8e01b555 100644
--- a/tests/Notifications/NotificationBroadcastChannelTest.php
+++ b/tests/Notifications/NotificationBroadcastChannelTest.php
@@ -28,7 +28,7 @@ public function testDatabaseChannelCreatesDatabaseRecordWithProperData(): void
$notification->id = '1';
$notifiable = new stdClass;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('dispatch')->with(Argument::type(BroadcastNotificationCreated::class));
$channel = new BroadcastChannel($events);
$channel->send($notifiable, $notification);
@@ -138,7 +138,7 @@ public function testNotificationIsBroadcastedNow(): void
$notification->id = '1';
$notifiable = new stdClass;
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('dispatch')->with(Argument::satisfies(function (BroadcastNotificationCreated $event): bool {
return $event->connection === 'sync';
}));
diff --git a/tests/Notifications/NotificationChannelManagerTest.php b/tests/Notifications/NotificationChannelManagerTest.php
index c8c270b57f..e765f83b1c 100644
--- a/tests/Notifications/NotificationChannelManagerTest.php
+++ b/tests/Notifications/NotificationChannelManagerTest.php
@@ -40,7 +40,6 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
-use JMac\Testing\Matching\Argument;
use Laravel\SerializableClosure\SerializableClosure;
use stdClass;
@@ -51,7 +50,7 @@ class NotificationChannelManagerTest extends TestCase
public function testGetDefaultChannel(): void
{
$container = $this->getContainer();
- $container->instance(MailChannel::class, Double::for(MailChannel::class));
+ $container->instance(MailChannel::class, Double::for(MailChannel::class)->strict());
$manager = new ChannelManager($container);
@@ -61,7 +60,7 @@ public function testGetDefaultChannel(): void
public function testGetCustomChannelResolvesDirectly(): void
{
$container = $this->getContainer();
- $container->instance(MailChannel::class, Double::for(MailChannel::class));
+ $container->instance(MailChannel::class, Double::for(MailChannel::class)->strict());
$manager = new ChannelManager($container);
$channel = new NotificationChannelManagerTestCustomChannel;
@@ -436,23 +435,25 @@ public function testQueuedNotificationForwardsArrayCallableDeduplicatorToQueueJo
$deduplicator = [NotificationChannelManagerTestDeduplicator::class, 'resolve'];
$container = $this->getContainer();
- $container->instance('queue.routes', $queueRoutes = Double::for(QueueRoutes::class));
+ $container->instance('queue.routes', $queueRoutes = Double::for(QueueRoutes::class)->strict());
$queueRoutes->expects('getQueue')->times(2)->returns(null);
$queueRoutes->expects('getConnection')->times(2)->returns(null);
+ $jobs = [];
$container->make(BusDispatcherContract::class)
- ->expects('dispatch')->times(2)->with(Argument::satisfies(function (SendQueuedNotifications $job) use ($deduplicator): bool {
- $this->assertSame($deduplicator, $job->deduplicator);
-
- $restored = unserialize(serialize($job));
- $this->assertSame('queue:payload', ($restored->deduplicator)('payload', 'queue'));
-
- return true;
- }));
+ ->expects('dispatch')->times(2)->resolves(static function (SendQueuedNotifications $job) use (&$jobs): void {
+ $jobs[] = $job;
+ });
$manager = new ChannelManager($container);
$notification = (new NotificationChannelManagerTestQueuedNotificationWithTwoChannels)->withDeduplicator($deduplicator);
$manager->send([new NotificationChannelManagerTestNotifiable], $notification);
+
+ foreach ($jobs as $job) {
+ $this->assertSame($deduplicator, $job->deduplicator);
+ $restored = unserialize(serialize($job));
+ $this->assertSame('queue:payload', ($restored->deduplicator)('payload', 'queue'));
+ }
}
public function testQueuedNotificationForwardsDeduplicatorSetToQueueJob(): void
@@ -558,7 +559,7 @@ protected function getContainer(): Container
$container = new Container;
$container->instance(ContainerContract::class, $container);
$container->instance('config', new ConfigRepository([]));
- $container->instance(BusDispatcherContract::class, Double::for(BusDispatcherContract::class));
+ $container->instance(BusDispatcherContract::class, Double::for(BusDispatcherContract::class)->strict());
$container->instance(Dispatcher::class, $this->mockEventDispatcher());
Container::setInstance($container);
@@ -571,7 +572,7 @@ protected function getContainer(): Container
*/
protected function mockEventDispatcher(): Dispatcher
{
- $dispatcher = Double::for(Dispatcher::class);
+ $dispatcher = Double::for(Dispatcher::class)->strict();
$dispatcher->allows('hasListeners')->returns(true);
return $dispatcher;
diff --git a/tests/Notifications/NotificationDatabaseChannelTest.php b/tests/Notifications/NotificationDatabaseChannelTest.php
index bc6a93bef9..8732531501 100644
--- a/tests/Notifications/NotificationDatabaseChannelTest.php
+++ b/tests/Notifications/NotificationDatabaseChannelTest.php
@@ -23,15 +23,15 @@ public function testDatabaseChannelCreatesDatabaseRecordWithProperData(): void
{
$notification = new NotificationDatabaseChannelTestNotification;
$notification->id = '1';
- $notifiable = Double::for(AnonymousNotifiable::class);
+ $notifiable = Double::for(AnonymousNotifiable::class)->strict();
- $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class));
+ $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class)->strict());
$relation->expects('create')->with([
'id' => '1',
'type' => get_class($notification),
'data' => ['invoice_id' => '1'],
'read_at' => null,
- ])->returns(Double::for(Model::class));
+ ])->returns(Double::for(Model::class)->strict());
$channel = new DatabaseChannel;
$channel->send($notifiable, $notification);
@@ -41,16 +41,16 @@ public function testCorrectPayloadIsSentToDatabase(): void
{
$notification = new NotificationDatabaseChannelTestNotification;
$notification->id = '1';
- $notifiable = Double::for(AnonymousNotifiable::class);
+ $notifiable = Double::for(AnonymousNotifiable::class)->strict();
- $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class));
+ $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class)->strict());
$relation->expects('create')->with([
'id' => '1',
'type' => get_class($notification),
'data' => ['invoice_id' => '1'],
'read_at' => null,
'something' => 'else',
- ])->returns(Double::for(Model::class));
+ ])->returns(Double::for(Model::class)->strict());
$channel = new ExtendedDatabaseChannel;
$channel->send($notifiable, $notification);
@@ -62,16 +62,16 @@ public function testCustomizeTypeIsSentToDatabase(): void
$notification = new NotificationDatabaseChannelCustomizeTypeTestNotification;
$notification->id = '1';
- $notifiable = Double::for(AnonymousNotifiable::class);
+ $notifiable = Double::for(AnonymousNotifiable::class)->strict();
- $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class));
+ $notifiable->expects('routeNotificationFor')->returns($relation = Double::for(HasMany::class)->strict());
$relation->expects('create')->with([
'id' => '1',
'type' => 'MONTHLY',
'data' => ['invoice_id' => '1'],
'read_at' => CarbonImmutable::now(),
'something' => 'else',
- ])->returns(Double::for(Model::class));
+ ])->returns(Double::for(Model::class)->strict());
$channel = new ExtendedDatabaseChannel;
$channel->send($notifiable, $notification);
diff --git a/tests/Notifications/NotificationRoutesNotificationsTest.php b/tests/Notifications/NotificationRoutesNotificationsTest.php
index 74a18b8348..b5c61a5811 100644
--- a/tests/Notifications/NotificationRoutesNotificationsTest.php
+++ b/tests/Notifications/NotificationRoutesNotificationsTest.php
@@ -12,6 +12,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use stdClass;
class NotificationRoutesNotificationsTest extends TestCase
@@ -21,11 +22,11 @@ class NotificationRoutesNotificationsTest extends TestCase
public function testNotificationCanBeDispatched(): void
{
$container = $this->getContainer();
- $factory = Double::for(Dispatcher::class);
+ $factory = Double::for(Dispatcher::class)->strict();
$container->instance(Dispatcher::class, $factory);
$notifiable = new RoutesNotificationsTestInstance;
$instance = new stdClass;
- $factory->expects('send')->with($notifiable, $instance);
+ $factory->expects('send')->with(Argument::same($notifiable), Argument::same($instance));
$notifiable->notify($instance);
}
@@ -33,11 +34,11 @@ public function testNotificationCanBeDispatched(): void
public function testNotificationCanBeSentNow(): void
{
$container = $this->getContainer();
- $factory = Double::for(Dispatcher::class);
+ $factory = Double::for(Dispatcher::class)->strict();
$container->instance(Dispatcher::class, $factory);
$notifiable = new RoutesNotificationsTestInstance;
$instance = new stdClass;
- $factory->expects('sendNow')->with($notifiable, $instance, null);
+ $factory->expects('sendNow')->with(Argument::same($notifiable), Argument::same($instance), null);
$notifiable->notifyNow($instance);
}
diff --git a/tests/Notifications/NotificationSendQueuedNotificationTest.php b/tests/Notifications/NotificationSendQueuedNotificationTest.php
index fe2fb66887..208140feb0 100644
--- a/tests/Notifications/NotificationSendQueuedNotificationTest.php
+++ b/tests/Notifications/NotificationSendQueuedNotificationTest.php
@@ -47,7 +47,7 @@ public function testNotificationsCanBeSent(): void
{
$notification = new TestNotification;
$job = new SendQueuedNotifications('notifiables', $notification);
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->expects('sendNow')->with(Argument::all(function (mixed $notifiables, mixed $notification, ?array $channels): bool {
return $notifiables instanceof Collection && $notifiables->toArray() === ['notifiables']
&& $notification instanceof TestNotification
diff --git a/tests/Notifications/NotificationSenderTest.php b/tests/Notifications/NotificationSenderTest.php
index 991abd80e5..ed55dd6902 100644
--- a/tests/Notifications/NotificationSenderTest.php
+++ b/tests/Notifications/NotificationSenderTest.php
@@ -53,11 +53,11 @@ class NotificationSenderTest extends TestCase
public function testItCanSendNotificationsWithAStringVia(): void
{
$notifiable = new DummyNotifiable;
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->expects('driver')
- ->returns($driver = Double::for(ChannelSpy::class));
+ ->returns($driver = Double::for(ChannelSpy::class)->strict());
$driver->expects('send');
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
$bus->expects('dispatch')->never();
$events = $this->mockEventDispatcher();
$events->allows('until')->with(Argument::type(NotificationSending::class))->returns(true);
@@ -79,8 +79,8 @@ static function () use (&$order): void {
$order[] = 'after-sending';
}
);
- $manager = Double::for(ChannelManager::class);
- $manager->expects('driver')->with('mail')->returns($driver = Double::for(ChannelSpy::class));
+ $manager = Double::for(ChannelManager::class)->strict();
+ $manager->expects('driver')->with('mail')->returns($driver = Double::for(ChannelSpy::class)->strict());
$driver->expects('send')->resolves(function () use (&$order, $response): object {
$order[] = 'channel';
@@ -113,7 +113,7 @@ function (object $event) use (&$order, $notifiable, $response): void {
(new NotificationSender(
$manager,
- Double::for(BusDispatcherContract::class),
+ Double::for(BusDispatcherContract::class)->strict(),
$events,
))->sendNow($notifiable, $notification, ['mail']);
@@ -132,7 +132,7 @@ public function shouldSend(mixed $notifiable, string $channel): bool
return false;
}
};
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->expects('driver')->never();
$events = $this->mockEventDispatcher();
$events->expects('until')->never();
@@ -144,14 +144,14 @@ public function shouldSend(mixed $notifiable, string $channel): bool
(new NotificationSender(
$manager,
- Double::for(BusDispatcherContract::class),
+ Double::for(BusDispatcherContract::class)->strict(),
$events,
))->sendNow($notifiable, $notification, ['mail']);
}
public function testSendingVetoDispatchesSkippedWithoutResolvingTheChannel(): void
{
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->expects('driver')->never();
$events = $this->mockEventDispatcher();
$events->expects('until')->with(Argument::type(NotificationSending::class))->returns(false);
@@ -159,7 +159,7 @@ public function testSendingVetoDispatchesSkippedWithoutResolvingTheChannel(): vo
(new NotificationSender(
$manager,
- Double::for(BusDispatcherContract::class),
+ Double::for(BusDispatcherContract::class)->strict(),
$events,
))->sendNow(new AnonymousNotifiable, new Notification, ['mail']);
}
@@ -167,7 +167,7 @@ public function testSendingVetoDispatchesSkippedWithoutResolvingTheChannel(): vo
public function testThrowingSendingListenerDispatchesFailedAndRethrows(): void
{
$exception = new RuntimeException('sending listener failed');
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->expects('driver')->never();
$events = $this->mockEventDispatcher();
$events->expects('until')->with(Argument::type(NotificationSending::class))->throws($exception);
@@ -175,7 +175,7 @@ public function testThrowingSendingListenerDispatchesFailedAndRethrows(): void
fn (object $event): bool => $event instanceof NotificationFailed
&& $event->data['exception'] === $exception
));
- $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class), $events);
+ $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class)->strict(), $events);
try {
$sender->sendNow(new AnonymousNotifiable, new Notification, ['mail']);
@@ -191,15 +191,15 @@ public function testThrowingFailureObserverDoesNotAllowRetryAfterCancellation():
$observerFailure = new RuntimeException('Failure storage unavailable.');
$events = new EventDispatcher(Container::getInstance());
$events->listen(NotificationFailed::class, static fn () => throw $observerFailure);
- $manager = Double::for(ChannelManager::class);
- $driver = Double::for(ChannelSpy::class);
+ $manager = Double::for(ChannelManager::class)->strict();
+ $driver = Double::for(ChannelSpy::class)->strict();
$manager->allows('driver')->returns($driver);
$attempts = 0;
$driver->allows('send')->resolves(static function () use ($cancellation, &$attempts): never {
++$attempts;
throw $cancellation;
});
- $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class), $events);
+ $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class)->strict(), $events);
$caught = null;
try {
@@ -216,15 +216,15 @@ public function testThrowingFailureObserverDoesNotAllowRetryAfterCancellation():
public function testThrowingDeliveredListenerIsNotRelabeledAsDeliveryFailure(): void
{
$exception = new RuntimeException('delivered listener failed');
- $manager = Double::for(ChannelManager::class);
- $manager->expects('driver')->returns($driver = Double::for(ChannelSpy::class));
+ $manager = Double::for(ChannelManager::class)->strict();
+ $manager->expects('driver')->returns($driver = Double::for(ChannelSpy::class)->strict());
$driver->expects('send')->returns('response');
$events = $this->mockEventDispatcher();
$events->expects('until')->with(Argument::type(NotificationSending::class))->returns(true);
$events->expects('dispatch')->with(Argument::type(NotificationDelivered::class))->throws($exception);
$events->expects('dispatch')->never()->with(Argument::type(NotificationFailed::class));
$events->expects('dispatch')->never()->with(Argument::type(NotificationSent::class));
- $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class), $events);
+ $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class)->strict(), $events);
try {
$sender->sendNow(new AnonymousNotifiable, new Notification, ['mail']);
@@ -240,15 +240,15 @@ public function testThrowingAfterSendingCallbackIsNotRelabeledAsDeliveryFailure(
$notification = new DummyNotificationWithAfterSendingCallback(static function () use ($exception): never {
throw $exception;
});
- $manager = Double::for(ChannelManager::class);
- $manager->expects('driver')->returns($driver = Double::for(ChannelSpy::class));
+ $manager = Double::for(ChannelManager::class)->strict();
+ $manager->expects('driver')->returns($driver = Double::for(ChannelSpy::class)->strict());
$driver->expects('send')->returns('response');
$events = $this->mockEventDispatcher();
$events->expects('until')->with(Argument::type(NotificationSending::class))->returns(true);
$events->expects('dispatch')->with(Argument::type(NotificationDelivered::class));
$events->expects('dispatch')->never()->with(Argument::type(NotificationFailed::class));
$events->expects('dispatch')->never()->with(Argument::type(NotificationSent::class));
- $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class), $events);
+ $sender = new NotificationSender($manager, Double::for(BusDispatcherContract::class)->strict(), $events);
try {
$sender->sendNow(new AnonymousNotifiable, $notification, ['mail']);
@@ -296,9 +296,9 @@ public function testItCanSendQueuedNotificationsWithAnArrayVia(): void
public function testItCanSendNotificationsWithAnEmptyStringVia(): void
{
$notifiable = new AnonymousNotifiable;
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$bus = new BusFake(new BusDispatcher(new Container));
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('dispatch')->never();
$sender = new NotificationSender($manager, $bus, $events);
@@ -311,9 +311,9 @@ public function testItCanSendNotificationsWithAnEmptyStringVia(): void
public function testItCannotSendNotificationsViaDatabaseForAnonymousNotifiables(): void
{
$notifiable = new AnonymousNotifiable;
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$bus = new BusFake(new BusDispatcher(new Container));
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('dispatch')->never();
$sender = new NotificationSender($manager, $bus, $events);
@@ -446,7 +446,7 @@ public function viaConnections(): array
}
};
$notification->onConnection($connection);
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
$bus->expects('dispatch')->with(Argument::satisfies(
fn (SendQueuedNotifications $job): bool => $job->channels === ['mail']
&& $job->queue === 'admin_notifications'
@@ -458,7 +458,7 @@ public function viaConnections(): array
&& $job->connection === 'database-connection'
));
- (new NotificationSender(new ChannelManager($container), $bus, Double::for(Dispatcher::class)))
+ (new NotificationSender(new ChannelManager($container), $bus, Double::for(Dispatcher::class)->strict()))
->send(new AnonymousNotifiable, $notification);
}
@@ -477,12 +477,12 @@ public function via(mixed $notifiable): string
};
$notifiable = new DummyNotifiable;
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->allows('getContainer')->returns(app());
$manager->allows('resolveQueueFromQueueRoute')->returns(null);
$manager->allows('resolveConnectionFromQueueRoute')->returns(null);
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
$bus->expects('dispatch')
->with(Argument::satisfies(function (SendQueuedNotifications $job): bool {
return $job->delay === 30;
@@ -518,12 +518,12 @@ public function withDelay(mixed $notifiable, string $channel): int
};
$notifiable = new DummyNotifiable;
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->allows('getContainer')->returns(app());
$manager->allows('resolveQueueFromQueueRoute')->returns(null);
$manager->allows('resolveConnectionFromQueueRoute')->returns(null);
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
$bus->expects('dispatch')
->with(Argument::satisfies(function (SendQueuedNotifications $job): bool {
return $job->delay === 60;
@@ -539,12 +539,12 @@ public function withDelay(mixed $notifiable, string $channel): int
public function testItCanSendQueuedNotificationsWithDelayProperty(): void
{
$notifiable = new DummyNotifiable;
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->allows('getContainer')->returns(app());
$manager->allows('resolveQueueFromQueueRoute')->returns(null);
$manager->allows('resolveConnectionFromQueueRoute')->returns(null);
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
$bus->expects('dispatch')
->with(Argument::satisfies(function (SendQueuedNotifications $job): bool {
return $job->delay === 45;
@@ -564,10 +564,10 @@ public function testNotificationFailedSentWithoutHttpTransportException(): void
$container->instance('config', new Config(['app' => ['name' => 'Name', 'logo' => 'Logo']]));
$manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container));
$driver = new ChannelSpy;
- $response = Double::for(ResponseInterface::class);
+ $response = Double::for(ResponseInterface::class)->strict();
$driver->exception = $exception = new HttpTransportException('Transport error', $response);
$manager->expects('driver')->returns($driver);
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
$events = new EventDispatcher;
$failed = null;
@@ -652,7 +652,7 @@ public function testItPreservesNotificationStateMutatedInViaMethod(): void
$manager = Double::for(ChannelManager::class)->passthru(new ChannelManager($container));
$driver = new ChannelSpy;
$manager->expects('driver')->returns($driver);
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
$events = new EventFake(new EventDispatcher);
@@ -766,13 +766,13 @@ public function via(mixed $notifiable): string
public function testNotificationEventsAreSkippedWhenNoListenersAreRegistered(): void
{
$notifiable = new DummyNotifiable;
- $manager = Double::for(ChannelManager::class);
+ $manager = Double::for(ChannelManager::class)->strict();
$manager->expects('driver')
- ->returns($driver = Double::for(ChannelSpy::class));
+ ->returns($driver = Double::for(ChannelSpy::class)->strict());
$driver->expects('send');
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
$bus->expects('dispatch')->never();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(NotificationSending::class)->returns(false);
$events->expects('hasListeners')->with(NotificationDelivered::class)->returns(false);
$events->expects('hasListeners')->with(NotificationSent::class)->returns(false);
@@ -787,14 +787,14 @@ public function testNotificationEventsAreSkippedWhenNoListenersAreRegistered():
public function testNotificationFailedIsSkippedWithoutListeners(): void
{
$notifiable = new AnonymousNotifiable;
- $manager = Double::for(ChannelManager::class);
- $manager->allows('driver')->returns($driver = Double::for(ChannelSpy::class));
- $response = Double::for(ResponseInterface::class);
+ $manager = Double::for(ChannelManager::class)->strict();
+ $manager->allows('driver')->returns($driver = Double::for(ChannelSpy::class)->strict());
+ $response = Double::for(ResponseInterface::class)->strict();
$exception = new HttpTransportException('Transport error', $response);
$driver->expects('send')->throws($exception);
- $bus = Double::for(BusDispatcherContract::class);
+ $bus = Double::for(BusDispatcherContract::class)->strict();
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(NotificationSending::class)->returns(false);
$events->expects('hasListeners')->with(NotificationFailed::class)->returns(false);
$events->expects('until')->never();
@@ -841,7 +841,7 @@ protected function getManager(array $queueRoutes = []): ChannelManager
*/
private function mockEventDispatcher(): Dispatcher
{
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(true);
return $events;
diff --git a/tests/ObjectPool/LeaseTest.php b/tests/ObjectPool/LeaseTest.php
index 072d587772..e50d835c55 100644
--- a/tests/ObjectPool/LeaseTest.php
+++ b/tests/ObjectPool/LeaseTest.php
@@ -14,6 +14,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use stdClass;
@@ -113,7 +114,7 @@ public function testDiscardFailureDoesNotMaskAReleaseCallbackFailure(): void
$callbackFailure = new RuntimeException('reset failed');
$discardFailure = new RuntimeException('discard failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($discardFailure);
+ $handler->expects('report')->with(Argument::same($discardFailure));
$container->instance(ExceptionHandler::class, $handler);
$pool = new ContractOnlyObjectPool;
@@ -156,7 +157,7 @@ public function testReleaseCallbackPreservesCancellationPrecedence(
$discardCancellation = new RuntimeException('discard cleanup failed', previous: $discardCancellation);
}
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($discardCancellation)
+ $handler->expects('report')->with(Argument::same($discardCancellation))
->times($expectCallbackFailure && $discardCleanupThrows ? 1 : 0);
$this->container()->instance(ExceptionHandler::class, $handler);
@@ -226,7 +227,7 @@ public function testDestructorReportsAndSwallowsFinalizationFailures(): void
$container = $this->container();
$expected = new RuntimeException('reset failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($expected);
+ $handler->expects('report')->with(Argument::same($expected));
$container->instance(ExceptionHandler::class, $handler);
$pool = $this->pool();
@@ -276,7 +277,7 @@ public function testFailureFinalizersPreserveCancellationPrecedence(
$cleanup = new RuntimeException('finalizer cleanup failed', previous: $cleanup);
}
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($cleanup)
+ $handler->expects('report')->with(Argument::same($cleanup))
->times($expectPrimary && ! $cleanup instanceof CanceledException ? 1 : 0);
$container->instance(ExceptionHandler::class, $handler);
diff --git a/tests/ObjectPool/ObjectPoolServiceProviderTest.php b/tests/ObjectPool/ObjectPoolServiceProviderTest.php
index e51081f651..fb1205c763 100644
--- a/tests/ObjectPool/ObjectPoolServiceProviderTest.php
+++ b/tests/ObjectPool/ObjectPoolServiceProviderTest.php
@@ -18,6 +18,7 @@
use Hypervel\Testbench\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use stdClass;
use Swoole\Server;
@@ -89,7 +90,7 @@ public function testLifecyclePurgesResolvedMasterPoolsBeforeForkAndStartsTheWork
$recycler = Double::for(StartRecycler::class)->strict();
$server = Double::for(Server::class)->strict();
$afterWorkerStart = new AfterWorkerStart($server, 0);
- $recycler->expects('handle')->with($afterWorkerStart);
+ $recycler->expects('handle')->with(Argument::same($afterWorkerStart));
$application = Double::for(Application::class, override: true)->strict();
$application->expects('make')->with('events')->returns($events);
$application->expects('resolved')->with(PoolManager::class)->returns(true);
diff --git a/tests/ObjectPool/ObjectPoolTest.php b/tests/ObjectPool/ObjectPoolTest.php
index d1b0af6683..2ca7a34218 100644
--- a/tests/ObjectPool/ObjectPoolTest.php
+++ b/tests/ObjectPool/ObjectPoolTest.php
@@ -18,6 +18,7 @@
use Hypervel\Tests\TestCase;
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;
@@ -70,7 +71,7 @@ public function testCloseDrainsEveryIdleObjectBeforeRethrowingTheFirstCancellati
$secondCancellation = new RuntimeException('Second cleanup failed.', previous: $secondCancellation);
}
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($secondCancellation)->times($secondCleanupThrows ? 1 : 0);
+ $handler->expects('report')->with(Argument::same($secondCancellation))->times($secondCleanupThrows ? 1 : 0);
$this->container()->instance(ExceptionHandler::class, $handler);
$destroyed = [];
$pool = $this->pool(
@@ -749,7 +750,7 @@ public function testDestroyCallbackFailuresAreReportedWithoutLeavingManagedGhost
$container = $this->container();
$failure = new RuntimeException('destroy failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->times(2)->with($failure);
+ $handler->expects('report')->times(2)->with(Argument::same($failure));
$container->instance(ExceptionHandler::class, $handler);
$pool = new InspectableObjectPool(
PoolOptions::fromArray(['max_objects' => 2]),
diff --git a/tests/ObjectPool/PoolErrorReporterTest.php b/tests/ObjectPool/PoolErrorReporterTest.php
index c9b5b376cf..84e715fe42 100644
--- a/tests/ObjectPool/PoolErrorReporterTest.php
+++ b/tests/ObjectPool/PoolErrorReporterTest.php
@@ -10,6 +10,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
class PoolErrorReporterTest extends TestCase
@@ -24,7 +25,7 @@ public function testReportsThroughTheSupportFailureReporter(): void
Container::setInstance($container);
$exception = new RuntimeException('reported through handler');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception);
+ $handler->expects('report')->with(Argument::same($exception));
$container->instance(ExceptionHandler::class, $handler);
PoolErrorReporter::report($exception);
diff --git a/tests/ObjectPool/PoolProxyTest.php b/tests/ObjectPool/PoolProxyTest.php
index e29887c4e6..a75c401135 100644
--- a/tests/ObjectPool/PoolProxyTest.php
+++ b/tests/ObjectPool/PoolProxyTest.php
@@ -18,6 +18,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
class PoolProxyTest extends TestCase
@@ -126,12 +127,12 @@ public function testDiscardFailureDoesNotMaskAConfigureFailure(): void
$configureFailure = new RuntimeException('configuration failed');
$discardFailure = new RuntimeException('discard failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($discardFailure);
+ $handler->expects('report')->with(Argument::same($discardFailure));
$this->container->instance(ExceptionHandler::class, $handler);
$pool = Double::for(ObjectPoolContract::class)->strict();
$pool->expects('borrow')->returns($object);
- $pool->expects('discard')->with($object)->throws($discardFailure);
+ $pool->expects('discard')->with(Argument::same($object))->throws($discardFailure);
$factory = Double::for(Factory::class)->strict();
$factory->expects('getOrCreate')->returns($pool);
$proxy = new InspectablePoolProxy(
@@ -156,7 +157,7 @@ public function testOperationFailureRemainsPrimaryWhenFinalizationAlsoFails(): v
$operationFailure = new RuntimeException('operation failed');
$finalizationFailure = new RuntimeException('release failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($finalizationFailure);
+ $handler->expects('report')->with(Argument::same($finalizationFailure));
$this->container->instance(ExceptionHandler::class, $handler);
$proxy = $this->proxy(
static fn (): object => new PoolProxyObject($operationFailure),
diff --git a/tests/ObjectPool/PoolRecyclerTest.php b/tests/ObjectPool/PoolRecyclerTest.php
index 6f0215b564..1a8b5d0412 100644
--- a/tests/ObjectPool/PoolRecyclerTest.php
+++ b/tests/ObjectPool/PoolRecyclerTest.php
@@ -44,7 +44,7 @@ public function testIdlePoolIsEvictedByIdentityAndExactInstance(): void
$pool->expects('isIdleExpired')->returns(true);
$manager = Double::for(Factory::class)->strict();
$manager->expects('getPools')->returns(['idle' => $pool]);
- $manager->expects('purge')->with('idle', $pool)->returns(true);
+ $manager->expects('purge')->with('idle', Argument::same($pool))->returns(true);
(new InspectablePoolRecycler($manager))->maintain();
}
@@ -59,7 +59,7 @@ public function testReplacementPoolSurvivesAStaleEvictionSnapshot(): void
$snapshotManager = Double::for(Factory::class)->strict();
$snapshotManager->expects('getPools')->returns(['shared' => $stale]);
$snapshotManager->expects('purge')
- ->with('shared', $stale)
+ ->with('shared', Argument::same($stale))
->resolves(fn (): bool => $manager->purge('shared', $stale));
(new InspectablePoolRecycler($snapshotManager))->maintain();
@@ -214,7 +214,7 @@ public function testCancellationStopsMaintenanceWithoutReporting(bool $scheduled
]);
if ($operation === 'purge') {
- $manager->expects('purge')->with('canceled', $pool)->throws($cancellation);
+ $manager->expects('purge')->with('canceled', Argument::same($pool))->throws($cancellation);
} else {
$pool->expects('sweepExpired')->throws($cancellation);
$pool->expects('trimIdle')->never();
@@ -264,7 +264,7 @@ public function testTimerReportsMaintenanceFailures(): void
{
$failure = new RuntimeException('maintenance failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($failure);
+ $handler->expects('report')->with(Argument::same($failure));
$container = new Container;
$container->instance(ExceptionHandler::class, $handler);
Container::setInstance($container);
diff --git a/tests/OpenTelemetry/Deferred/DeferredLogsTest.php b/tests/OpenTelemetry/Deferred/DeferredLogsTest.php
index 29488583fd..b894fecdbc 100644
--- a/tests/OpenTelemetry/Deferred/DeferredLogsTest.php
+++ b/tests/OpenTelemetry/Deferred/DeferredLogsTest.php
@@ -9,6 +9,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use OpenTelemetry\API\Logs\LoggerInterface;
use OpenTelemetry\API\Logs\LoggerProviderInterface;
use OpenTelemetry\API\Logs\LogRecord;
@@ -37,10 +38,10 @@ public function testPreBindLoggerDropsRecordsAndReplaysItsScopeAcrossBindings():
$workerBuilder = Double::for(LogRecordBuilderInterface::class)->strict();
$workerLogger = Double::for(LoggerInterface::class)->strict();
$workerLogger->expects('isEnabled')
- ->with(Context::getRoot(), 17, 'exception')
+ ->with(Argument::same(Context::getRoot()), 17, 'exception')
->returns(true);
$workerLogger->expects('logRecordBuilder')->returns($workerBuilder);
- $workerLogger->expects('emit')->with($record);
+ $workerLogger->expects('emit')->with(Argument::same($record));
$workerProvider = Double::for(LoggerProviderInterface::class)->strict();
$workerProvider->expects('getLogger')
->with('billing', '1.0', 'https://schema.test', ['scope.kind' => 'test'])
diff --git a/tests/OpenTelemetry/Deferred/DeferredMetricsTest.php b/tests/OpenTelemetry/Deferred/DeferredMetricsTest.php
index e5ef213ea9..420ecf8a29 100644
--- a/tests/OpenTelemetry/Deferred/DeferredMetricsTest.php
+++ b/tests/OpenTelemetry/Deferred/DeferredMetricsTest.php
@@ -239,7 +239,7 @@ public function testBatchObservationMapsOwnedInstrumentsAndLeavesForeignInstrume
->with('runtime.count', null, null, [])
->returns($counterDelegate);
$workerMeter->expects('batchObserve')
- ->with($callback, $counterDelegate, $foreignGauge)
+ ->with(Argument::same($callback), Argument::same($counterDelegate), Argument::same($foreignGauge))
->returns($delegateToken);
$workerProvider = Double::for(MeterProviderInterface::class)->strict();
$workerProvider->expects('getMeter')
@@ -288,23 +288,23 @@ private function observableProvider(
$batchToken = Double::for(ObservableCallbackInterface::class)->strict();
$counter = Double::for(ObservableCounterInterface::class)->strict();
$counter->allows('isEnabled')->returns(true);
- $counter->expects('observe')->with($counterCallback)->returns($counterToken);
+ $counter->expects('observe')->with(Argument::same($counterCallback))->returns($counterToken);
$gauge = Double::for(ObservableGaugeInterface::class)->strict();
$gauge->allows('isEnabled')->returns(true);
$upDownCounter = Double::for(ObservableUpDownCounterInterface::class)->strict();
$upDownCounter->allows('isEnabled')->returns(true);
$meter = Double::for(MeterInterface::class)->strict();
$meter->expects('createObservableCounter')
- ->with('runtime.count', null, null, [], $counterCreation)
+ ->with('runtime.count', null, null, [], Argument::same($counterCreation))
->returns($counter);
$meter->expects('createObservableGauge')
- ->with('runtime.gauge', null, null, [], $gaugeCreation)
+ ->with('runtime.gauge', null, null, [], Argument::same($gaugeCreation))
->returns($gauge);
$meter->expects('createObservableUpDownCounter')
->with('runtime.active', null, null, [])
->returns($upDownCounter);
$meter->expects('batchObserve')
- ->with($batchCallback, $counter, $gauge)
+ ->with(Argument::same($batchCallback), Argument::same($counter), Argument::same($gauge))
->returns($batchToken);
$provider = Double::for(MeterProviderInterface::class)->strict();
$provider->expects('getMeter')
diff --git a/tests/OpenTelemetry/Instrumentation/ExceptionInstrumentationTest.php b/tests/OpenTelemetry/Instrumentation/ExceptionInstrumentationTest.php
index bfdac82518..485442ac81 100644
--- a/tests/OpenTelemetry/Instrumentation/ExceptionInstrumentationTest.php
+++ b/tests/OpenTelemetry/Instrumentation/ExceptionInstrumentationTest.php
@@ -24,6 +24,7 @@
use JMac\Testing\Double;
use JMac\Testing\DoubleInterface;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use OpenTelemetry\API\Common\Time\ClockInterface;
use OpenTelemetry\API\Logs\LogRecordBuilderInterface;
use OpenTelemetry\API\Logs\Severity;
@@ -203,7 +204,7 @@ public function testRequestOnlyStateSuppliesLazyUserContextToExceptionLogs(): vo
);
RequestTelemetryState::set($state);
$this->userContexts->expects('resolve')
- ->with($state)
+ ->with(Argument::same($state))
->returns(['user.id' => '42']);
$this->handler->report(new RuntimeException('Request failed.'));
diff --git a/tests/OpenTelemetry/Logging/OpenTelemetryHandlerTest.php b/tests/OpenTelemetry/Logging/OpenTelemetryHandlerTest.php
index ccafa6b533..e0de458b2b 100644
--- a/tests/OpenTelemetry/Logging/OpenTelemetryHandlerTest.php
+++ b/tests/OpenTelemetry/Logging/OpenTelemetryHandlerTest.php
@@ -17,6 +17,7 @@
use JMac\Testing\Double;
use JMac\Testing\DoubleInterface;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use JMac\Testing\OverriddenDouble;
use Monolog\Level;
use Monolog\LogRecord;
@@ -169,8 +170,8 @@ public function testItSuppressesOnlyTheExactExceptionBeingDirectlyReported(): vo
$reported = new RuntimeException('Reported.');
$other = new RuntimeException('Other.');
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('isReporting')->with($reported)->returns(true);
- $exceptionHandler->expects('isReporting')->with($other)->returns(false);
+ $exceptionHandler->expects('isReporting')->with(Argument::same($reported))->returns(true);
+ $exceptionHandler->expects('isReporting')->with(Argument::same($other))->returns(false);
$this->container->expects('make')
->with(ExceptionHandlerContract::class)
->returns($exceptionHandler);
diff --git a/tests/OpenTelemetry/OpenTelemetryManagerTest.php b/tests/OpenTelemetry/OpenTelemetryManagerTest.php
index 270a38f869..d7241820cf 100644
--- a/tests/OpenTelemetry/OpenTelemetryManagerTest.php
+++ b/tests/OpenTelemetry/OpenTelemetryManagerTest.php
@@ -25,6 +25,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use JMac\Testing\OverriddenDouble;
use LogicException;
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
@@ -136,7 +137,7 @@ public function testBindResolvesAndRegistersConfiguredInstrumentationAfterProvid
$manager->bind($identity);
- $container->received('instance')->with(ProcessIdentity::class, $identity)->times(1);
+ $container->received('instance')->with(ProcessIdentity::class, Argument::same($identity))->times(1);
$this->assertSame(['metrics' => true, 'custom' => 'value'], $instrumentation->options);
$manager->shutdown();
}
@@ -162,7 +163,7 @@ public function testBindRegistersIdentityWithoutInstrumentationsAndRetainsItAfte
$exceptionContexts->enable();
$manager->bind($identity);
- $container->received('instance')->with(ProcessIdentity::class, $identity)->times(1);
+ $container->received('instance')->with(ProcessIdentity::class, Argument::same($identity))->times(1);
$manager->shutdown();
$expected = new RuntimeException('failure');
@@ -341,7 +342,7 @@ public function testInstrumentationRegistrationFailureKeepsTheGraphBoundAndOneSh
$this->assertTrue($manager->isBound());
$manager->bind($identity);
- $container->received('instance')->with(ProcessIdentity::class, $identity)->times(1);
+ $container->received('instance')->with(ProcessIdentity::class, Argument::same($identity))->times(1);
$this->assertSame(1, $instrumentation->registrations);
$this->assertSame(1, $failingInstrumentation->registrations);
$this->assertTrue($manager->shutdown());
diff --git a/tests/Pagination/CursorPaginatorLoadMorphCountTest.php b/tests/Pagination/CursorPaginatorLoadMorphCountTest.php
index 8f9cf0c32b..958005d092 100644
--- a/tests/Pagination/CursorPaginatorLoadMorphCountTest.php
+++ b/tests/Pagination/CursorPaginatorLoadMorphCountTest.php
@@ -23,7 +23,7 @@ public function testCollectionLoadMorphCountCanChainOnThePaginator(): void
'App\Company' => ['employees', 'calendars'],
];
- $items = Double::for(Collection::class);
+ $items = Double::for(Collection::class)->strict();
$items->expects('loadMorphCount')->with('parentable', $relations);
$p = (new class extends AbstractCursorPaginator {
diff --git a/tests/Pagination/CursorPaginatorLoadMorphTest.php b/tests/Pagination/CursorPaginatorLoadMorphTest.php
index 3954c4514f..a2e1cedba3 100644
--- a/tests/Pagination/CursorPaginatorLoadMorphTest.php
+++ b/tests/Pagination/CursorPaginatorLoadMorphTest.php
@@ -23,7 +23,7 @@ public function testCollectionLoadMorphCanChainOnThePaginator(): void
'App\Company' => ['employees', 'calendars'],
];
- $items = Double::for(Collection::class);
+ $items = Double::for(Collection::class)->strict();
$items->expects('loadMorph')->with('parentable', $relations);
$p = (new class extends AbstractCursorPaginator {
diff --git a/tests/Pagination/PaginatorLoadMorphCountTest.php b/tests/Pagination/PaginatorLoadMorphCountTest.php
index 0213813f39..1a4de53a1f 100644
--- a/tests/Pagination/PaginatorLoadMorphCountTest.php
+++ b/tests/Pagination/PaginatorLoadMorphCountTest.php
@@ -23,7 +23,7 @@ public function testCollectionLoadMorphCountCanChainOnThePaginator(): void
'App\Company' => ['employees', 'calendars'],
];
- $items = Double::for(Collection::class);
+ $items = Double::for(Collection::class)->strict();
$items->expects('loadMorphCount')->with('parentable', $relations);
$p = (new class extends AbstractPaginator {
diff --git a/tests/Pagination/PaginatorLoadMorphTest.php b/tests/Pagination/PaginatorLoadMorphTest.php
index 6421fd6526..d2194f0aff 100644
--- a/tests/Pagination/PaginatorLoadMorphTest.php
+++ b/tests/Pagination/PaginatorLoadMorphTest.php
@@ -23,7 +23,7 @@ public function testCollectionLoadMorphCanChainOnThePaginator(): void
'App\Company' => ['employees', 'calendars'],
];
- $items = Double::for(Collection::class);
+ $items = Double::for(Collection::class)->strict();
$items->expects('loadMorph')->with('parentable', $relations);
$p = (new class extends AbstractPaginator {
diff --git a/tests/Passkeys/Feature/Actions/DeletePasskeyTest.php b/tests/Passkeys/Feature/Actions/DeletePasskeyTest.php
index f9eb9e1b53..9ef27b5a4c 100644
--- a/tests/Passkeys/Feature/Actions/DeletePasskeyTest.php
+++ b/tests/Passkeys/Feature/Actions/DeletePasskeyTest.php
@@ -93,7 +93,7 @@ public function testItDoesNotDispatchPasskeyDeletedEventWithoutListeners(): void
]);
$passkey = $this->createPasskeyForUser($user, 'credential-quiet-delete');
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(false);
$this->instance('events', $events);
diff --git a/tests/Passkeys/Feature/Actions/VerifyPasskeyTest.php b/tests/Passkeys/Feature/Actions/VerifyPasskeyTest.php
index f3eb6f60da..3c4c526c5c 100644
--- a/tests/Passkeys/Feature/Actions/VerifyPasskeyTest.php
+++ b/tests/Passkeys/Feature/Actions/VerifyPasskeyTest.php
@@ -345,7 +345,7 @@ public function testItUsesTheConfiguredPasskeyModelConnectionForVerificationTran
'credential' => ['id' => 'credential-connection'],
]);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->returns(false);
$this->instance('events', $events);
diff --git a/tests/Passport/PassportCacheTest.php b/tests/Passport/PassportCacheTest.php
index d89e69ebaa..b75c8cb7c7 100644
--- a/tests/Passport/PassportCacheTest.php
+++ b/tests/Passport/PassportCacheTest.php
@@ -28,6 +28,7 @@
use Hypervel\Tests\Passport\Fixtures\User;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PDO;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
@@ -397,9 +398,9 @@ public function testBatchInvalidationContinuesAfterAFailureFollowingCommit(): vo
$realCoordinator = new ModelCacheCoordinator($this->app);
$coordinator = Double::for($realCoordinator)->passthru();
$coordinator->expects('invalidate')
- ->with($cache, 'passport:tokens:token')->throws($failure);
+ ->with(Argument::same($cache), 'passport:tokens:token')->throws($failure);
$coordinator->expects('invalidate')
- ->with($cache, 'passport:tokens:token-second')->resolves($realCoordinator->invalidate(...));
+ ->with(Argument::same($cache), 'passport:tokens:token-second')->resolves($realCoordinator->invalidate(...));
$this->app->instance(ModelCacheCoordinator::class, $coordinator);
$first = $this->createToken();
@@ -438,11 +439,11 @@ public function testBatchInvalidationStopsOnCancellationAfterAnOrdinaryFailure(b
$cache = $this->app->make('cache')->store('passport-file');
$coordinator = Double::for(new ModelCacheCoordinator($this->app))->passthru();
$coordinator->expects('invalidate')
- ->with($cache, 'passport:tokens:token')->throws(new LockTimeoutException);
+ ->with(Argument::same($cache), 'passport:tokens:token')->throws(new LockTimeoutException);
$coordinator->expects('invalidate')
- ->with($cache, 'passport:tokens:token-second')->throws($failure);
+ ->with(Argument::same($cache), 'passport:tokens:token-second')->throws($failure);
$coordinator->expects('invalidate')->never()
- ->with($cache, 'passport:tokens:token-third');
+ ->with(Argument::same($cache), 'passport:tokens:token-third');
$this->app->instance(ModelCacheCoordinator::class, $coordinator);
$first = $this->createToken();
diff --git a/tests/Passport/Unit/SimpleViewResponseTest.php b/tests/Passport/Unit/SimpleViewResponseTest.php
index e1ef131e92..d9aab0722f 100644
--- a/tests/Passport/Unit/SimpleViewResponseTest.php
+++ b/tests/Passport/Unit/SimpleViewResponseTest.php
@@ -16,6 +16,7 @@
use Hypervel\Testbench\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\TestWith;
class SimpleViewResponseTest extends TestCase
@@ -60,7 +61,7 @@ public function testCallbacksCanReturnResponsableObjects(): void
$request = Request::create('/oauth/authorize');
$expected = new Response('Consent', 202, ['X-Consent' => 'pending']);
$responsable = Double::for(Responsable::class)->strict();
- $responsable->expects('toResponse')->with($request)->returns($expected);
+ $responsable->expects('toResponse')->with(Argument::same($request))->returns($expected);
$response = new SimpleViewResponse(function (array $parameters) use ($responsable): Responsable {
$this->assertSame(['client' => 'example'], $parameters);
diff --git a/tests/Permission/Events/EventTest.php b/tests/Permission/Events/EventTest.php
index b56cfe0a75..3dfe97423c 100644
--- a/tests/Permission/Events/EventTest.php
+++ b/tests/Permission/Events/EventTest.php
@@ -38,7 +38,7 @@ public function testRoleAttachedEventChecksListenersBeforeDispatching(): void
$events = Double::for(Dispatcher::class)->strict();
$events->allows('hasListeners')->with(Argument::not(RoleAttachedEvent::class))->returns(false);
$events->expects('hasListeners')->with(RoleAttachedEvent::class)->returns(false);
- $events->expects('dispatch')->with(Argument::type(RoleAttachedEvent::class), Argument::any(), Argument::any())->never();
+ $events->expects('dispatch')->with(Argument::type(RoleAttachedEvent::class))->never();
$this->app->instance('events', $events);
$this->app->instance(Dispatcher::class, $events);
diff --git a/tests/Permission/SchemaConfigTest.php b/tests/Permission/SchemaConfigTest.php
index 02bd8378d0..db1b671aef 100644
--- a/tests/Permission/SchemaConfigTest.php
+++ b/tests/Permission/SchemaConfigTest.php
@@ -70,7 +70,7 @@ public function testTeamMigrationAcceptsOmittedOptionalColumnNamesWhenTeamsAreDi
try {
$migration->up();
- $this->addToAssertionCount(1);
+ $this->assertFalse(Schema::hasColumn('roles', 'team_id'));
} finally {
config()->set('permission', $original);
}
diff --git a/tests/Permission/Traits/HasPermissionsTest.php b/tests/Permission/Traits/HasPermissionsTest.php
index fe15299926..41820fd202 100644
--- a/tests/Permission/Traits/HasPermissionsTest.php
+++ b/tests/Permission/Traits/HasPermissionsTest.php
@@ -188,19 +188,22 @@ public function testItCanScopeUsersUsingAString(): void
$this->assertCount(2, User::withoutPermission('edit-news')->get());
}
- public function testItCanScopeUsersUsingAInt(): void
+ public function testItCanScopeUsersUsingPermissionIds(): void
{
+ // The inherited test covers both upstream's integer IDs and the custom permission model's UUIDs.
+ $articles = $this->testUserPermission->getKey();
+ $news = $this->testUserPermission::findByName('edit-news')->getKey();
User::all()->each(fn ($item) => $item->delete());
$user1 = User::create(['email' => 'user1@test.com']);
$user2 = User::create(['email' => 'user2@test.com']);
User::create(['email' => 'user3@test.com']);
- $user1->givePermissionTo([1, 2]);
- $this->testUserRole->givePermissionTo(1);
+ $user1->givePermissionTo([$articles, $news]);
+ $this->testUserRole->givePermissionTo($articles);
$user2->assignRole('testRole');
- $this->assertCount(2, User::permission(1)->get());
- $this->assertCount(1, User::permission([2])->get());
- $this->assertCount(2, User::withoutPermission([2])->get());
+ $this->assertCount(2, User::permission($articles)->get());
+ $this->assertCount(1, User::permission([$news])->get());
+ $this->assertCount(2, User::withoutPermission([$news])->get());
}
public function testItCanScopeUsersUsingAnArray(): void
diff --git a/tests/Permission/Traits/HasPermissionsWithCustomModelsTest.php b/tests/Permission/Traits/HasPermissionsWithCustomModelsTest.php
index 9479d54a82..2e8e569164 100644
--- a/tests/Permission/Traits/HasPermissionsWithCustomModelsTest.php
+++ b/tests/Permission/Traits/HasPermissionsWithCustomModelsTest.php
@@ -10,7 +10,6 @@
use Hypervel\Support\Facades\DB;
use Hypervel\Tests\Permission\Fixtures\Models\Admin;
use Hypervel\Tests\Permission\Fixtures\Models\Permission;
-use Hypervel\Tests\Permission\Fixtures\Models\User;
class HasPermissionsWithCustomModelsTest extends HasPermissionsTest
{
@@ -69,28 +68,6 @@ public function testBasePermissionRequestsReuseTheConfiguredCustomCatalogAndPrim
$this->assertSame([], DB::getQueryLog());
}
- public function testItCanScopeUsersUsingAInt(): void
- {
- // Skipped because custom model uses uuid,
- // replacement "testItCanScopeUsersUsingAUuid"
- $this->assertTrue(true);
- }
-
- public function testItCanScopeUsersUsingAUuid(): void
- {
- $uuid1 = $this->testUserPermission->getKey();
- $uuid2 = app(Permission::class)::where('name', 'edit-news')->first()->getKey();
-
- $user1 = User::create(['email' => 'user1@test.com']);
- $user2 = User::create(['email' => 'user2@test.com']);
- $user1->givePermissionTo([$uuid1, $uuid2]);
- $this->testUserRole->givePermissionTo($uuid1);
- $user2->assignRole('testRole');
-
- $this->assertCount(2, User::permission($uuid1)->get());
- $this->assertCount(1, User::permission([$uuid2])->get());
- }
-
public function testItDoesntDetachRolesWhenSoftDeleting(): void
{
$this->testUserRole->givePermissionTo($this->testUserPermission);
diff --git a/tests/Process/ProcessTest.php b/tests/Process/ProcessTest.php
index 080ce12cb2..4aac6c8f33 100644
--- a/tests/Process/ProcessTest.php
+++ b/tests/Process/ProcessTest.php
@@ -1186,9 +1186,7 @@ public function testFakeProcessesDontThrowIfFalse(): void
$factory->fake(fn () => $factory->result(exitCode: 1));
$result = $factory->path(__DIR__)->run($this->ls());
- $result->throwIf(false);
-
- $this->assertTrue(true);
+ $this->assertSame($result, $result->throwIf(false));
}
#[RequiresOperatingSystem('Linux|Darwin')]
@@ -1539,9 +1537,7 @@ public function testRealProcessesDoesntThrowIfFalse(): void
$factory = new Factory;
$result = $factory->path(__DIR__)->run('echo "Hello World" >&2; exit 1;');
- $result->throwIf(false);
-
- $this->assertTrue(true);
+ $this->assertSame($result, $result->throwIf(false));
}
#[RequiresOperatingSystem('Linux|Darwin')]
diff --git a/tests/Prompts/PromptAnimationTest.php b/tests/Prompts/PromptAnimationTest.php
index 23a7306e99..6a28d1b581 100644
--- a/tests/Prompts/PromptAnimationTest.php
+++ b/tests/Prompts/PromptAnimationTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\TestCase;
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;
@@ -35,7 +36,7 @@ public function testOwnerCancellationDuringCreationLeavesAnimationStoppable(): v
$childCoroutineId = null;
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
$exceptionHandler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
diff --git a/tests/Queue/FailoverQueueTest.php b/tests/Queue/FailoverQueueTest.php
index 1bedc35ec5..5bc689a211 100644
--- a/tests/Queue/FailoverQueueTest.php
+++ b/tests/Queue/FailoverQueueTest.php
@@ -59,11 +59,11 @@ public function testConnectionScopedForwardsApplyBeforeDelegating(string $method
$routes = new QueueRoutes;
$routes->forward(['default' => 'processing', 'reports' => 'processing', '0' => 'processing', 'processing' => 'archive'], connection: 'failover');
Container::getInstance()->instance('queue.routes', $routes);
- $manager = Double::for(QueueManager::class);
- $redis = Double::for(RedisQueue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $redis = Double::for(RedisQueue::class)->strict();
$manager->expects('connection')->with('redis')->returns($redis);
$redis->expects($method)->with(...$expectedArguments)->returns($result);
- $queue = new FailoverQueue($manager, Double::for(DispatcherContract::class), ['redis']);
+ $queue = new FailoverQueue($manager, Double::for(DispatcherContract::class)->strict(), ['redis']);
$queue->setConnectionName('failover');
$this->assertSame($result, $queue->{$method}(...$arguments));
@@ -96,7 +96,7 @@ public static function forwardedQueueOperations(): array
#[DataProvider('failedConnectionNames')]
public function testPushFailsOverOnException(UnitEnum|string|null $connection, ?string $expectedName): void
{
- $queue = Double::for(QueueManager::class);
+ $queue = Double::for(QueueManager::class)->strict();
$events = new EventDispatcher;
$failedOver = [];
$events->listen(QueueFailedOver::class, function (QueueFailedOver $event) use (&$failedOver): void {
@@ -107,10 +107,10 @@ public function testPushFailsOverOnException(UnitEnum|string|null $connection, ?
'sync',
]);
- $redis = Double::for(RedisQueue::class);
+ $redis = Double::for(RedisQueue::class)->strict();
$queue->expects('connection')->with($connection)->returns($redis);
- $sync = Double::for(SyncQueue::class);
+ $sync = Double::for(SyncQueue::class)->strict();
$queue->expects('connection')->with('sync')->returns($sync);
$redis->expects('push')->resolves(
@@ -141,10 +141,10 @@ public static function failedConnectionNames(): array
public function testReplacementQueueReportsItsOwnFirstFailure(): void
{
- $manager = Double::for(QueueManager::class);
- $events = Double::for(DispatcherContract::class);
- $primary = Double::for(Queue::class);
- $secondary = Double::for(Queue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $events = Double::for(DispatcherContract::class)->strict();
+ $primary = Double::for(Queue::class)->strict();
+ $secondary = Double::for(Queue::class)->strict();
$primary->allows('push')->throws(new RuntimeException('Primary unavailable.'));
$secondary->allows('push')->returns('job-id');
$manager->allows('connection')->with('primary')->returns($primary);
@@ -164,9 +164,9 @@ public function testReplacementQueueReportsItsOwnFirstFailure(): void
#[TestWith([true])]
public function testCancellationDoesNotFailOverOrEmitAnEvent(bool $cleanupThrows): void
{
- $manager = Double::for(QueueManager::class);
- $events = Double::for(DispatcherContract::class);
- $primary = Double::for(Queue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $events = Double::for(DispatcherContract::class)->strict();
+ $primary = Double::for(Queue::class)->strict();
$cancellation = new CanceledException;
if ($cleanupThrows) {
$cancellation = new RuntimeException('Queue cleanup failed.', previous: $cancellation);
@@ -192,9 +192,9 @@ public function testCancellationDoesNotFailOverOrEmitAnEvent(bool $cleanupThrows
public function testCancellationAfterAnOrdinaryFailureRetainsFailureSuppressionState(bool $cleanupThrows): void
{
$events = new FailoverQueueFakeDispatcher;
- $manager = Double::for(QueueManager::class);
- $primary = Double::for(Queue::class);
- $secondary = Double::for(Queue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $primary = Double::for(Queue::class)->strict();
+ $secondary = Double::for(Queue::class)->strict();
$cancellation = new CanceledException;
if ($cleanupThrows) {
$cancellation = new RuntimeException('Queue cleanup failed.', previous: $cancellation);
@@ -230,9 +230,9 @@ static function () use (&$secondaryAttempts, $cancellation): string {
public function testCancellationFromAFailoverListenerStopsFallback(): void
{
- $manager = Double::for(QueueManager::class);
- $events = Double::for(DispatcherContract::class);
- $primary = Double::for(Queue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $events = Double::for(DispatcherContract::class)->strict();
+ $primary = Double::for(Queue::class)->strict();
$cancellation = new CanceledException;
$failover = new FailoverQueue($manager, $events, ['primary', 'secondary']);
@@ -254,9 +254,9 @@ public function testCancellationFromAFailoverListenerStopsFallback(): void
public function testBulkRespectsJobDelays(): void
{
- $manager = Double::for(QueueManager::class);
- $failover = new FailoverQueue($manager, Double::for(DispatcherContract::class), ['sync']);
- $sync = Double::for(SyncQueue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $failover = new FailoverQueue($manager, Double::for(DispatcherContract::class)->strict(), ['sync']);
+ $sync = Double::for(SyncQueue::class)->strict();
$manager->expects('connection')->times(3)->with('sync')->returns($sync);
$sync->expects('later')->with(15, Argument::type(FailoverJobWithDelayAttribute::class), '', null);
@@ -361,11 +361,11 @@ protected function executePayload(string $payload, ?string $queue = null): int
}
};
$first->setContainer($container)->setConnectionName('first');
- $second = Double::for(Queue::class);
+ $second = Double::for(Queue::class)->strict();
$job = new FailoverQueueUniqueDebouncedJob;
$lock = new UniqueLock(new CacheRepository(new ArrayStore));
$this->assertTrue($lock->acquireForDispatch($job));
- $second->expects('push')->with($job)->resolves(function ($job) use ($lock): string {
+ $second->expects('push')->with(Argument::same($job))->resolves(function ($job) use ($lock): string {
$this->assertTrue(DispatchLockContext::has($job));
$this->assertFalse($lock->acquire($job));
DispatchLockContext::accept($job);
@@ -519,8 +519,8 @@ public function testRollbackAttemptsEveryJobLockReleaseWhenOneFails(): void
true,
);
$transactions = new DatabaseTransactionsManager;
- $cache = Double::for(CacheContract::class, LockProvider::class);
- $lock = Double::for(LockContract::class);
+ $cache = Double::for(CacheContract::class, LockProvider::class)->strict();
+ $lock = Double::for(LockContract::class)->strict();
$container = new Container;
$container->instance('db.transactions', $transactions);
$container->instance(CacheContract::class, $cache);
@@ -683,9 +683,9 @@ public function testFailingQueueStateIsIsolatedBetweenCoroutines(): void
public function testInspectionDelegatesToTheFirstConnection(): void
{
- $manager = Double::for(QueueManager::class);
- $events = Double::for(DispatcherContract::class);
- $redis = Double::for(RedisQueue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $events = Double::for(DispatcherContract::class)->strict();
+ $redis = Double::for(RedisQueue::class)->strict();
$queue = new FailoverQueue($manager, $events, ['redis', 'sync']);
$manager->expects('connection')->times(10)->with('redis')->returns($redis);
@@ -714,9 +714,9 @@ public function testInspectionDelegatesToTheFirstConnection(): void
public function testPopForwardsTheQueueIndexToTheFirstConnection(): void
{
- $manager = Double::for(QueueManager::class);
- $events = Double::for(DispatcherContract::class);
- $redis = Double::for(RedisQueue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $events = Double::for(DispatcherContract::class)->strict();
+ $redis = Double::for(RedisQueue::class)->strict();
$queue = new FailoverQueue($manager, $events, ['redis', 'sync']);
$manager->expects('connection')->with('redis')->returns($redis);
@@ -727,9 +727,9 @@ public function testPopForwardsTheQueueIndexToTheFirstConnection(): void
public function testPopDoesNotForwardTheQueueIndexToAnOrdinaryConnection(): void
{
- $manager = Double::for(QueueManager::class);
- $events = Double::for(DispatcherContract::class);
- $sync = Double::for(SyncQueue::class);
+ $manager = Double::for(QueueManager::class)->strict();
+ $events = Double::for(DispatcherContract::class)->strict();
+ $sync = Double::for(SyncQueue::class)->strict();
$queue = new FailoverQueue($manager, $events, ['sync']);
$manager->expects('connection')->with('sync')->returns($sync);
diff --git a/tests/Queue/InteractsWithQueueTest.php b/tests/Queue/InteractsWithQueueTest.php
index 7daa9a0e3a..815efcfb6b 100644
--- a/tests/Queue/InteractsWithQueueTest.php
+++ b/tests/Queue/InteractsWithQueueTest.php
@@ -20,12 +20,8 @@ class InteractsWithQueueTest extends TestCase
public function testCreatesAnExceptionFromString(): void
{
- $queueJob = Double::for(Job::class);
- $queueJob->expects('fail')->with(Argument::satisfies(function (Exception $exception): bool {
- $this->assertSame('Whoops!', $exception->getMessage());
-
- return true;
- }));
+ $queueJob = Double::for(Job::class)->strict();
+ $queueJob->expects('fail')->with(Argument::capture($exception));
$job = new class {
use InteractsWithQueue;
@@ -35,13 +31,16 @@ public function testCreatesAnExceptionFromString(): void
$job->job = $queueJob;
$job->fail('Whoops!');
+
+ $this->assertInstanceOf(Exception::class, $exception);
+ $this->assertSame('Whoops!', $exception->getMessage());
}
public function testReleasesUsingDateInterval(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::now());
- $queueJob = Double::for(Job::class);
+ $queueJob = Double::for(Job::class)->strict();
$queueJob->expects('release')->with(60);
$job = new class {
diff --git a/tests/Queue/ListFailedCommandTest.php b/tests/Queue/ListFailedCommandTest.php
index e6bebf4f67..c40e92e19a 100644
--- a/tests/Queue/ListFailedCommandTest.php
+++ b/tests/Queue/ListFailedCommandTest.php
@@ -119,7 +119,7 @@ public function testItFiltersFailedJobsByQueue(string $queue): void
protected function runCommandWithFailedJobs(array $failedJobs, array $arguments = [], bool $decorated = false): string
{
$container = new Application;
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$container->instance(FailedJobProviderInterface::class, $failer);
$failer->expects('all')->returns($failedJobs);
diff --git a/tests/Queue/Outbox/OutboxDispatchTest.php b/tests/Queue/Outbox/OutboxDispatchTest.php
index 5b1040d68a..6ac5044146 100644
--- a/tests/Queue/Outbox/OutboxDispatchTest.php
+++ b/tests/Queue/Outbox/OutboxDispatchTest.php
@@ -32,6 +32,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use Pheanstalk\Contract\PheanstalkManagerInterface;
use Pheanstalk\Contract\PheanstalkPublisherInterface;
use Pheanstalk\Contract\PheanstalkSubscriberInterface;
@@ -162,7 +163,7 @@ public function testBaseBulkStagesOneInsertAndKeepsTheDirectPartition(bool $bean
: Double::for(OutboxDispatchBaseQueue::class)->passthru();
$queue->setContainer($this->app)->setConnectionName($beanstalk ? 'beanstalkd' : 'custom');
$direct = (new OutboxDispatchJob)->withoutOutbox();
- $queue->expects('push')->with($direct, '', 'orders')->returns('direct');
+ $queue->expects('push')->with(Argument::same($direct), '', 'orders')->returns('direct');
$jobs = array_map(static fn (): OutboxDispatchJob => (new OutboxDispatchJob)->viaOutbox(), range(1, 100));
$connection = DB::connection();
$connection->enableQueryLog();
@@ -262,7 +263,7 @@ public function testBulkFailureIsNotReplacedByAFailingFailureListener(): void
});
$this->app->make('events')->listen(JobQueueingFailed::class, static fn () => throw $listener);
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($listener);
+ $handler->expects('report')->with(Argument::same($listener));
$this->app->instance(ExceptionHandler::class, $handler);
$jobs = [(new OutboxDispatchJob)->viaOutbox(), (new OutboxDispatchJob)->viaOutbox()];
diff --git a/tests/Queue/Outbox/OutboxRelayTest.php b/tests/Queue/Outbox/OutboxRelayTest.php
index c462d37d7b..9a9038e8fc 100644
--- a/tests/Queue/Outbox/OutboxRelayTest.php
+++ b/tests/Queue/Outbox/OutboxRelayTest.php
@@ -111,13 +111,11 @@ public function testPartialResultsSettleBeforeAnotherConnectionAndReportingCanno
$this->assertSame(1, $event->failed);
$this->assertSame($failure, $event->exception);
});
- $exceptions->expects('report')->with($failure, Argument::satisfies(function (array $context) use (&$settled): bool {
+ $exceptions->expects('report')->with(Argument::same($failure), Argument::type('array'))->resolves(function (RuntimeException $failure, array $context) use (&$settled): void {
$this->assertSame([[1], [3]], $settled);
$this->assertSame([1, 2], $context['outbox_ids']);
$this->assertSame(['SendInvoice', 'SendInvoice'], $context['jobs']);
-
- return true;
- }));
+ });
$this->assertFalse((new OutboxRelay($repository, $queues, $events, $exceptions))->deliver('primary', $messages));
}
@@ -131,16 +129,14 @@ public function testInvalidResultsReleaseEveryInputAsFailure(OutboxBatchResult $
$exceptions = Double::for(ExceptionHandler::class)->strict();
$queues->expects('connection')->returns($queue);
$queue->expects('publishOutboxMessages')->returns($invalid);
- $repository->expects('settle')->with('primary', Argument::type('array'), Argument::satisfies(function (OutboxBatchResult $result): bool {
- $this->assertSame([], $result->accepted);
- $this->assertSame([], $result->deferred);
- $this->assertInstanceOf(LogicException::class, $result->failure);
-
- return true;
- }))->returns(2);
+ $repository->expects('settle')->with('primary', Argument::type('array'), Argument::capture($result))->returns(2);
$exceptions->expects('report')->with(Argument::type(LogicException::class), Argument::type('array'));
$this->assertFalse((new OutboxRelay($repository, $queues, new Dispatcher, $exceptions))->deliver('primary', [$this->message(1), $this->message(2)]));
+ $this->assertInstanceOf(OutboxBatchResult::class, $result);
+ $this->assertSame([], $result->accepted);
+ $this->assertSame([], $result->deferred);
+ $this->assertInstanceOf(LogicException::class, $result->failure);
}
/**
@@ -185,8 +181,8 @@ public function testPublicationAndSettlementErrorsAreBothReportedWithPublication
$queues->expects('connection')->returns($queue);
$queue->expects('pushRaw')->throws($publication);
$repository->expects('settle')->throws($settlement);
- $exceptions->expects('report')->with($publication, Argument::type('array'));
- $exceptions->expects('report')->with($settlement, Argument::type('array'));
+ $exceptions->expects('report')->with(Argument::same($publication), Argument::type('array'));
+ $exceptions->expects('report')->with(Argument::same($settlement), Argument::type('array'));
$events->listen(OutboxBatchDeliveryFailed::class, function (OutboxBatchDeliveryFailed $event) use ($publication): void {
$this->assertSame($publication, $event->exception);
});
@@ -234,7 +230,7 @@ public function testListenerFailureDoesNotThrottleDeliveryAndReporterFailureEsca
throw $listenerFailure;
});
$events->listen(OutboxBatchDeliveryFailed::class, fn () => $this->fail('Listener failure must not change the delivery event.'));
- $report = $exceptions->expects('report')->with($listenerFailure, Argument::type('array'));
+ $report = $exceptions->expects('report')->with(Argument::same($listenerFailure), Argument::type('array'));
if ($reporterFails) {
$report->throws($reporterFailure);
diff --git a/tests/Queue/Outbox/OutboxWorkerTest.php b/tests/Queue/Outbox/OutboxWorkerTest.php
index 720c7c94e1..7461da7c71 100644
--- a/tests/Queue/Outbox/OutboxWorkerTest.php
+++ b/tests/Queue/Outbox/OutboxWorkerTest.php
@@ -81,7 +81,7 @@ public function testFailedSourceCoolsDownWithoutDelayingHealthySources(): void
$this->relay->expects('claim')->with('broken', 1)->throws($failure);
$this->relay->expects('claim')->with('healthy', 1)->times(3)->returns([$this->message(1)]);
$this->relay->expects('deliver')->with('healthy', Argument::type('array'))->times(3)->returns(true);
- $this->exceptions->expects('report')->with($failure, ['outbox_database' => 'broken']);
+ $this->exceptions->expects('report')->with(Argument::same($failure), ['outbox_database' => 'broken']);
$this->assertSame(0, $worker->run(null, new OutboxWorkerOptions(batch: 1, sleep: 60, maxJobs: 3, memory: 1024)));
Sleep::assertNeverSlept();
@@ -94,7 +94,7 @@ public function testStopWhenEmptyTreatsFailedSourcesAsEmptyAndDoesNotRecheckAfte
$failure = new RuntimeException('Missing table.');
$this->relay->expects('claim')->with('broken', 100)->throws($failure);
$this->relay->expects('claim')->with('empty', 100)->returns([]);
- $this->exceptions->expects('report')->with($failure, ['outbox_database' => 'broken']);
+ $this->exceptions->expects('report')->with(Argument::same($failure), ['outbox_database' => 'broken']);
$this->assertSame(0, $worker->run(null, new OutboxWorkerOptions(memory: 1024, stopWhenEmpty: true)));
Sleep::assertNeverSlept();
diff --git a/tests/Queue/Outbox/RedisOutboxPublicationTest.php b/tests/Queue/Outbox/RedisOutboxPublicationTest.php
index ea1194b4e8..03fe7435ea 100644
--- a/tests/Queue/Outbox/RedisOutboxPublicationTest.php
+++ b/tests/Queue/Outbox/RedisOutboxPublicationTest.php
@@ -173,7 +173,7 @@ public function testCancellationDuringObserverFailureReportingPropagates(): void
$connection->expects('evalWithShaCache')->with(Argument::any(), Argument::satisfies(fn (array $keys): bool => $keys[0] === 'queues:second'), Argument::any())->throws(new RuntimeException('Redis unavailable.'));
$cancellation = new RuntimeException('Reporting cleanup failed.', previous: new CanceledException);
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($observerFailure)->throws($cancellation);
+ $handler->expects('report')->with(Argument::same($observerFailure))->throws($cancellation);
Container::getInstance()->instance(ExceptionHandler::class, $handler);
try {
diff --git a/tests/Queue/PruneBatchesCommandTest.php b/tests/Queue/PruneBatchesCommandTest.php
index 90158b89a5..46ffe39785 100644
--- a/tests/Queue/PruneBatchesCommandTest.php
+++ b/tests/Queue/PruneBatchesCommandTest.php
@@ -19,8 +19,10 @@ class PruneBatchesCommandTest extends TestCase
public function testAllowPruningAllUnfinishedBatches(): void
{
- $repo = Double::for(DatabaseBatchRepository::class);
+ $now = $this->freezeSecond();
+ $repo = Double::for(DatabaseBatchRepository::class)->strict();
$repo->expects('prune');
+ $repo->expects('pruneUnfinished')->with($now);
$this->app->instance(BatchRepository::class, $repo);
@@ -28,14 +30,14 @@ public function testAllowPruningAllUnfinishedBatches(): void
$command->setHypervel($this->app);
$command->run(new ArrayInput(['--unfinished' => 0]), new NullOutput);
-
- $repo->received('pruneUnfinished')->times(1);
}
public function testAllowPruningAllCancelledBatches(): void
{
- $repo = Double::for(DatabaseBatchRepository::class);
+ $now = $this->freezeSecond();
+ $repo = Double::for(DatabaseBatchRepository::class)->strict();
$repo->expects('prune');
+ $repo->expects('pruneCancelled')->with($now);
$this->app->instance(BatchRepository::class, $repo);
@@ -43,7 +45,5 @@ public function testAllowPruningAllCancelledBatches(): void
$command->setHypervel($this->app);
$command->run(new ArrayInput(['--cancelled' => 0]), new NullOutput);
-
- $repo->received('pruneCancelled')->times(1);
}
}
diff --git a/tests/Queue/QueueBeanstalkdJobTest.php b/tests/Queue/QueueBeanstalkdJobTest.php
index 295b24126b..47fa4146d1 100644
--- a/tests/Queue/QueueBeanstalkdJobTest.php
+++ b/tests/Queue/QueueBeanstalkdJobTest.php
@@ -64,7 +64,7 @@ public function testFailProperlyCallsTheJobHandler(): void
$job = $this->getJob(json_encode(['job' => 'foo', 'uuid' => 'test-uuid', 'data' => ['data']]));
$handler = new BeanstalkdJobTestFailedTest;
$job->getContainer()->instance('foo', $handler);
- $job->getPheanstalk()->expects('delete')->with($job->getPheanstalkJob());
+ $job->getPheanstalk()->expects('delete')->with(Argument::same($job->getPheanstalkJob()));
$events = new EventsDispatcher;
$failed = [];
$events->listen(JobFailed::class, function (JobFailed $event) use (&$failed): void {
@@ -87,7 +87,7 @@ public function testFailProperlyCallsTheJobHandler(): void
public function testFailWithNullFailedDriverDoesNotRollBackDatabaseTransaction(): void
{
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$job = $this->getJob(
json_encode(['job' => 'foo', 'uuid' => 'test-uuid', 'data' => ['data']]),
$container->instance(),
@@ -102,10 +102,10 @@ public function testFailWithNullFailedDriverDoesNotRollBackDatabaseTransaction()
]));
$container->expects('bound')->never();
$container->expects('make')->never()->with('db');
- $container->expects('make')->with('foo')->returns($handler = Double::for(BeanstalkdJobTestFailedTest::class));
- $job->getPheanstalk()->expects('delete')->with($job->getPheanstalkJob());
+ $container->expects('make')->with('foo')->returns($handler = Double::for(BeanstalkdJobTestFailedTest::class)->strict());
+ $job->getPheanstalk()->expects('delete')->with(Argument::same($job->getPheanstalkJob()));
$handler->expects('failed')->with(['data'], Argument::type(TimeoutExceededException::class), 'test-uuid', Argument::type(BeanstalkdJob::class));
- $container->expects('make')->with(Dispatcher::class)->returns($events = Double::for(Dispatcher::class));
+ $container->expects('make')->with(Dispatcher::class)->returns($events = Double::for(Dispatcher::class)->strict());
$events->expects('hasListeners')->with(JobFailed::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(JobFailed::class))->returns(null);
@@ -115,7 +115,7 @@ public function testFailWithNullFailedDriverDoesNotRollBackDatabaseTransaction()
public function testDeleteRemovesTheJobFromBeanstalkd(): void
{
$job = $this->getJob();
- $job->getPheanstalk()->expects('delete')->with($job->getPheanstalkJob());
+ $job->getPheanstalk()->expects('delete')->with(Argument::same($job->getPheanstalkJob()));
$job->delete();
}
@@ -123,7 +123,7 @@ public function testDeleteRemovesTheJobFromBeanstalkd(): void
public function testReleaseProperlyReleasesJobOntoBeanstalkd(): void
{
$job = $this->getJob();
- $job->getPheanstalk()->expects('release')->with($job->getPheanstalkJob(), Pheanstalk::DEFAULT_PRIORITY, 0);
+ $job->getPheanstalk()->expects('release')->with(Argument::same($job->getPheanstalkJob()), Pheanstalk::DEFAULT_PRIORITY, 0);
$job->release();
}
@@ -131,7 +131,7 @@ public function testReleaseProperlyReleasesJobOntoBeanstalkd(): void
public function testBuryProperlyBuryTheJobFromBeanstalkd(): void
{
$job = $this->getJob();
- $job->getPheanstalk()->expects('bury')->with($job->getPheanstalkJob());
+ $job->getPheanstalk()->expects('bury')->with(Argument::same($job->getPheanstalkJob()));
$job->bury();
}
@@ -141,7 +141,7 @@ public function testDeleteReleasesPoolLeaseAfterBackendCall(): void
[$pool, $lease] = $this->lease();
$job = $this->getJob();
$job->getPheanstalk()->expects('statsJob')->returns($this->stats(1));
- $job->getPheanstalk()->expects('delete')->with($job->getPheanstalkJob())
+ $job->getPheanstalk()->expects('delete')->with(Argument::same($job->getPheanstalkJob()))
->resolves(function () use ($pool): void {
$this->assertSame(1, $pool->getBorrowedCount());
});
@@ -158,7 +158,7 @@ public function testReleaseReleasesPoolLeaseAfterBackendCall(): void
$job = $this->getJob();
$job->getPheanstalk()->expects('statsJob')->returns($this->stats(1));
$job->getPheanstalk()->expects('release')
- ->with($job->getPheanstalkJob(), Pheanstalk::DEFAULT_PRIORITY, 5)
+ ->with(Argument::same($job->getPheanstalkJob()), Pheanstalk::DEFAULT_PRIORITY, 5)
->resolves(function () use ($pool): void {
$this->assertSame(1, $pool->getBorrowedCount());
});
@@ -174,7 +174,7 @@ public function testBuryReleasesPoolLeaseAfterBackendCall(): void
[$pool, $lease] = $this->lease();
$job = $this->getJob();
$job->getPheanstalk()->expects('statsJob')->returns($this->stats(1));
- $job->getPheanstalk()->expects('bury')->with($job->getPheanstalkJob())
+ $job->getPheanstalk()->expects('bury')->with(Argument::same($job->getPheanstalkJob()))
->resolves(function () use ($pool): void {
$this->assertSame(1, $pool->getBorrowedCount());
});
@@ -277,7 +277,7 @@ protected function getJob(string $data = '', ?ContainerContract $container = nul
{
return new BeanstalkdJob(
$container ?? new Container,
- Double::for(PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class),
+ Double::for(PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class)->strict(),
new PheanstalkJob(new JobId(1), $data),
'connection-name',
'default'
diff --git a/tests/Queue/QueueBeanstalkdQueueTest.php b/tests/Queue/QueueBeanstalkdQueueTest.php
index accd2226e1..74bdb870c7 100644
--- a/tests/Queue/QueueBeanstalkdQueueTest.php
+++ b/tests/Queue/QueueBeanstalkdQueueTest.php
@@ -213,7 +213,7 @@ public function testJobQueuedReceivesTheExactBeanstalkdJobIdentifier(): void
{
$this->setQueue('default', 60);
- $jobId = Double::for(JobIdInterface::class);
+ $jobId = Double::for(JobIdInterface::class)->strict();
$pheanstalk = $this->queue->getPheanstalk();
$pheanstalk->expects('useTube')->with(Argument::satisfies(fn (TubeName $tube): bool => $tube->value === '0'));
$pheanstalk->expects('put')->returns($jobId);
@@ -273,7 +273,7 @@ public function testPopProperlyPopsJobOffOfBeanstalkd(): void
$pheanstalk->expects('watch')->with(Argument::type(TubeName::class));
$pheanstalk->expects('listTubesWatched')->returns(new TubeList($tube));
- $jobId = Double::for(JobIdInterface::class);
+ $jobId = Double::for(JobIdInterface::class)->strict();
$jobId->expects('getId');
$job = new Job($jobId, '');
$pheanstalk->expects('reserveWithTimeout')->with(0)->returns($job);
@@ -292,7 +292,7 @@ public function testBlockingPopProperlyPopsJobOffOfBeanstalkd(): void
$pheanstalk->expects('watch')->with(Argument::type(TubeName::class));
$pheanstalk->expects('listTubesWatched')->returns(new TubeList($tube));
- $jobId = Double::for(JobIdInterface::class);
+ $jobId = Double::for(JobIdInterface::class)->strict();
$jobId->expects('getId');
$job = new Job($jobId, '');
$pheanstalk->expects('reserveWithTimeout')->with(60)->returns($job);
@@ -319,7 +319,7 @@ public function testDeleteProperlyRemoveJobsOffBeanstalkd(): void
private function setQueue(string $default, int $timeToRun, int $blockFor = 0): void
{
$this->queue = new BeanstalkdQueue(
- Double::for(PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class),
+ Double::for(PheanstalkManagerInterface::class, PheanstalkPublisherInterface::class, PheanstalkSubscriberInterface::class)->strict(),
$default,
$timeToRun,
$blockFor
diff --git a/tests/Queue/QueueClearCommandTest.php b/tests/Queue/QueueClearCommandTest.php
index 3434557ec0..ff09282ccb 100644
--- a/tests/Queue/QueueClearCommandTest.php
+++ b/tests/Queue/QueueClearCommandTest.php
@@ -87,7 +87,7 @@ public function testProhibitedCommandCannotBeForced(): void
ClearCommand::prohibit();
$container = new Application;
- $queueManager = Double::for(QueueManager::class);
+ $queueManager = Double::for(QueueManager::class)->strict();
$queueManager->expects('connection')->never();
$container->instance('queue', $queueManager);
@@ -107,13 +107,13 @@ protected function runClearCommand(Queue&ClearableQueue $queue, array $arguments
$container = new Application;
$container->instance('env', 'testing');
- $config = Double::for(Repository::class);
+ $config = Double::for(Repository::class)->strict();
$config->expects('string')->with('queue.default')->returns('redis');
$config->allows('string')->with('queue.connections.redis.queue', 'default')->returns('default');
$container->instance('config', $config);
- $queueManager = Double::for(QueueManager::class);
+ $queueManager = Double::for(QueueManager::class)->strict();
$queueManager->expects('connection')->with('redis')->returns($queue);
$container->instance('queue', $queueManager);
diff --git a/tests/Queue/QueueDatabaseQueueUnitTest.php b/tests/Queue/QueueDatabaseQueueUnitTest.php
index 2242fb3dae..072f2f2688 100644
--- a/tests/Queue/QueueDatabaseQueueUnitTest.php
+++ b/tests/Queue/QueueDatabaseQueueUnitTest.php
@@ -66,7 +66,7 @@ public function testRetryAfterMustBeAnInteger(): void
$this->expectException(TypeError::class);
new DatabaseQueue(
- resolver: Double::for(ConnectionResolverInterface::class),
+ resolver: Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
retryAfter: null,
@@ -76,7 +76,7 @@ public function testRetryAfterMustBeAnInteger(): void
public function testQueueNamesPreserveZeroAndDefaultEmptyString(): void
{
$queue = new TestDatabaseQueue(
- resolver: Double::for(ConnectionResolverInterface::class),
+ resolver: Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -94,8 +94,8 @@ public function testQueueNamesPreserveZeroAndDefaultEmptyString(): void
#[TestWith([false, true])]
public function testLockForPoppingUsesTheConnectionCapability(bool $supportsSkipLocked, bool|string $lock): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
$resolver->expects('connection')->with(null)->returns($connection);
$connection->expects('supportsSkipLocked')->returns($supportsSkipLocked);
@@ -183,7 +183,7 @@ public function testDelayedPushRoundsUpFractionalDeadlines(DateInterval|DateTime
Str::createUuidsUsing(fn (): Uuid => $uuid);
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -191,8 +191,8 @@ public function testDelayedPushRoundsUpFractionalDeadlines(DateInterval|DateTime
);
$container = Double::for(Container::class, override: true)->passthru(new Container);
$queue->setContainer($container->instance());
- $connection = Double::for(Connection::class);
- $query = Double::for(Builder::class);
+ $connection = Double::for(Connection::class)->strict();
+ $query = Double::for(Builder::class)->strict();
$connection->expects('table')->with('table')->returns($query);
$resolver->expects('connection')->returns($connection);
@@ -230,7 +230,7 @@ public function testFailureToCreatePayloadFromObject(): void
$job = new stdClass;
$job->invalid = "\xc3\x28";
- $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class), null, 'table', 'default');
+ $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class)->strict(), null, 'table', 'default');
$class = new ReflectionClass(Queue::class);
$createPayload = $class->getMethod('createPayload');
@@ -244,7 +244,7 @@ public function testFailureToCreatePayloadFromArray(): void
{
$this->expectException(InvalidArgumentException::class);
- $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class), null, 'table', 'default');
+ $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class)->strict(), null, 'table', 'default');
$class = new ReflectionClass(Queue::class);
$createPayload = $class->getMethod('createPayload');
@@ -257,7 +257,7 @@ public function testFailureToCreatePayloadFromArray(): void
public function testBulkUsesOneInsertWithoutATransactionAtTheBindingLimit(): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -265,10 +265,10 @@ public function testBulkUsesOneInsertWithoutATransactionAtTheBindingLimit(): voi
);
$queue->setContainer(new Container);
- $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class));
+ $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class)->strict());
$connection->expects('maxBindings')->returns(12);
$connection->expects('transaction')->never();
- $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class));
+ $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class)->strict());
$query->expects('insert')->with(Argument::satisfies(static fn (array $rows): bool => count($rows) === 2))->returns(true);
$this->assertTrue($queue->bulk(['first', 'second']));
@@ -277,7 +277,7 @@ public function testBulkUsesOneInsertWithoutATransactionAtTheBindingLimit(): voi
public function testBulkUsesTheMinimumChunksInsideOneTransactionAboveTheBindingLimit(): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -285,12 +285,12 @@ public function testBulkUsesTheMinimumChunksInsideOneTransactionAboveTheBindingL
);
$queue->setContainer(new Container);
- $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class));
+ $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class)->strict());
$connection->expects('maxBindings')->returns(12);
$connection->expects('transaction')->resolves(
static fn (Closure $callback): mixed => $callback()
);
- $connection->expects('table')->times(2)->with('table')->returns($query = Double::for(Builder::class));
+ $connection->expects('table')->times(2)->with('table')->returns($query = Double::for(Builder::class)->strict());
$chunkSizes = [];
$query->expects('insert')->times(2)->resolves(static function (array $rows) use (&$chunkSizes): bool {
$chunkSizes[] = count($rows);
@@ -305,7 +305,7 @@ public function testBulkUsesTheMinimumChunksInsideOneTransactionAboveTheBindingL
public function testBulkTreatsAnExplicitFalseInsertAsFailure(): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -313,8 +313,8 @@ public function testBulkTreatsAnExplicitFalseInsertAsFailure(): void
);
$queue->setContainer(new Container);
- $resolver->expects('connection')->with(null)->returns($connection = Double::for(Connection::class));
- $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class));
+ $resolver->expects('connection')->with(null)->returns($connection = Double::for(Connection::class)->strict());
+ $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class)->strict());
$query->expects('insert')->returns(false);
$this->expectExceptionObject(new RuntimeException('Unable to insert queued jobs into the database.'));
@@ -325,7 +325,7 @@ public function testBulkTreatsAnExplicitFalseInsertAsFailure(): void
public function testBulkRetainsDispatchOwnershipUntilTheTransactionCommits(): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -334,11 +334,11 @@ public function testBulkRetainsDispatchOwnershipUntilTheTransactionCommits(): vo
$queue->setContainer(new Container);
$first = new DatabaseBulkOwnedJob;
$second = new DatabaseBulkOwnedJob;
- $cache = Double::for(CacheRepository::class);
+ $cache = Double::for(CacheRepository::class)->strict();
DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1');
DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2');
- $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class));
+ $resolver->expects('connection')->with(null)->returns($connection = Double::for(PdoConnection::class)->strict());
$connection->expects('maxBindings')->returns(6);
$connection->expects('transactionLevel')->times(2)->returns(0);
$connection->expects('transaction')->resolves(function (Closure $callback) use ($first, $second): mixed {
@@ -352,7 +352,7 @@ public function testBulkRetainsDispatchOwnershipUntilTheTransactionCommits(): vo
return $result;
});
- $connection->expects('table')->times(2)->with('table')->returns($query = Double::for(Builder::class));
+ $connection->expects('table')->times(2)->with('table')->returns($query = Double::for(Builder::class)->strict());
$query->expects('insert')->times(2)->returns(true);
$this->assertTrue($queue->bulk([$first, $second]));
@@ -363,7 +363,7 @@ public function testBulkRetainsDispatchOwnershipUntilTheTransactionCommits(): vo
public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -375,15 +375,15 @@ public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void
$queue->setConnectionName('database');
$first = new DatabaseBulkOwnedJob;
$second = new DatabaseBulkOwnedJob;
- $cache = Double::for(CacheRepository::class);
+ $cache = Double::for(CacheRepository::class)->strict();
DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1');
DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2');
$exception = new RuntimeException('Listener failed.');
$notified = [];
- $resolver->expects('connection')->with(null)->returns($connection = Double::for(Connection::class));
+ $resolver->expects('connection')->with(null)->returns($connection = Double::for(Connection::class)->strict());
$connection->expects('transactionLevel')->times(2)->returns(0);
- $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class));
+ $connection->expects('table')->with('table')->returns($query = Double::for(Builder::class)->strict());
$query->expects('insert')->returns(true);
$dispatcher->listen(JobQueued::class, static function (JobQueued $event) use (&$notified): void {
$notified[] = $event->job;
@@ -407,7 +407,7 @@ public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void
public function testBulkRaisesExactSuccessEventsAroundOneInsert(): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -418,8 +418,8 @@ public function testBulkRaisesExactSuccessEventsAroundOneInsert(): void
$queue->setContainer($container);
$queue->setConnectionName('database');
- $connection = Double::for(Connection::class);
- $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class));
+ $connection = Double::for(Connection::class)->strict();
+ $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class)->strict());
$resolver->expects('connection')->with(null)->returns($connection);
$query->expects('insert')->resolves(function (array $records): bool {
$this->assertSame('first-final', json_decode($records[0]['payload'], true)['telemetry']);
@@ -461,7 +461,7 @@ public function testBulkRaisesExactSuccessEventsAroundOneInsert(): void
public function testBulkRaisesExactFailureEventsWhenInsertThrows(): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -473,8 +473,8 @@ public function testBulkRaisesExactFailureEventsWhenInsertThrows(): void
$queue->setConnectionName('database');
$exception = new RuntimeException('Insert failed.');
- $connection = Double::for(Connection::class);
- $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class));
+ $connection = Double::for(Connection::class)->strict();
+ $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class)->strict());
$resolver->expects('connection')->with(null)->returns($connection);
$query->expects('insert')->throws($exception);
@@ -513,7 +513,7 @@ public function testBulkRaisesExactFailureEventsWhenInsertThrows(): void
public function testBulkInsertFailureListenerErrorReporting(string $reporting): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -526,8 +526,8 @@ public function testBulkInsertFailureListenerErrorReporting(string $reporting):
$queue->setConnectionName('database');
$exception = new RuntimeException('Insert failed.');
- $connection = Double::for(Connection::class);
- $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class));
+ $connection = Double::for(Connection::class)->strict();
+ $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class)->strict());
$resolver->expects('connection')->with(null)->returns($connection);
$query->expects('insert')->throws($exception);
@@ -537,8 +537,8 @@ public function testBulkInsertFailureListenerErrorReporting(string $reporting):
$failed[] = $event->job;
});
$dispatcher->listen(JobQueueingFailed::class, static fn () => throw $listener);
- $handler = Double::for(ExceptionHandler::class);
- $report = $handler->expects('report')->with($listener);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $report = $handler->expects('report')->with(Argument::same($listener));
$reportingFailure = match ($reporting) {
'ordinary' => new RuntimeException('Reporting failed.'),
'cancellation' => new CanceledException,
@@ -585,7 +585,7 @@ public function testBulkInsertFailureListenerErrorReporting(string $reporting):
#[TestWith([true])]
public function testOutboxSelectionCancellationRaisesACanceledEventInsteadOfAFailureEvent(bool $cleanupThrows): void
{
- $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class), null, 'jobs', 'default');
+ $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class)->strict(), null, 'jobs', 'default');
$queue->setConnectionName('database');
$container = new Container;
$events = new Dispatcher($container);
@@ -638,7 +638,7 @@ public function testOutboxSelectionCancellationRaisesACanceledEventInsteadOfAFai
public function testBulkCancellationRaisesCanceledEventsInsteadOfFailureEvents(bool $cleanupThrows): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -649,8 +649,8 @@ public function testBulkCancellationRaisesCanceledEventsInsteadOfFailureEvents(b
$queue->setContainer($container);
$queue->setConnectionName('database');
- $connection = Double::for(Connection::class);
- $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class));
+ $connection = Double::for(Connection::class)->strict();
+ $connection->allows('table')->with('table')->returns($query = Double::for(Builder::class)->strict());
$resolver->expects('connection')->with(null)->returns($connection);
$gate = $this->armCurrentCoroutineCancellation();
$cleanup = new RuntimeException('Insert cleanup failed.');
@@ -711,14 +711,14 @@ public function testBulkSplitsImmediateAndAfterCommitJobsAndReacquiresTheQueue()
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestamp(1732502704));
$queue = new TestDatabaseQueue(
- resolver: $immediateResolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $immediateResolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
currentTime: 1732502704,
);
$deferredQueue = new TestDatabaseQueue(
- resolver: $deferredResolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $deferredResolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -732,8 +732,8 @@ public function testBulkSplitsImmediateAndAfterCommitJobsAndReacquiresTheQueue()
$queue->setContainer($container);
$deferredQueue->setContainer(new Container);
- $immediateConnection = Double::for(Connection::class);
- $immediateConnection->allows('table')->with('table')->returns($immediateQuery = Double::for(Builder::class));
+ $immediateConnection = Double::for(Connection::class)->strict();
+ $immediateConnection->allows('table')->with('table')->returns($immediateQuery = Double::for(Builder::class)->strict());
$immediateResolver->expects('connection')->with(null)->returns($immediateConnection);
$immediateRecords = [];
$immediateQuery->expects('insert')->resolves(static function (array $records) use (&$immediateRecords): bool {
@@ -742,8 +742,8 @@ public function testBulkSplitsImmediateAndAfterCommitJobsAndReacquiresTheQueue()
return true;
});
- $deferredConnection = Double::for(Connection::class);
- $deferredConnection->allows('table')->with('table')->returns($deferredQuery = Double::for(Builder::class));
+ $deferredConnection = Double::for(Connection::class)->strict();
+ $deferredConnection->allows('table')->with('table')->returns($deferredQuery = Double::for(Builder::class)->strict());
$deferredResolver->expects('connection')->with(null)->returns($deferredConnection);
$deferredRecords = [];
$deferredQuery->expects('insert')->resolves(static function (array $records) use (&$deferredRecords): bool {
@@ -780,7 +780,7 @@ public function testBulkSplitsImmediateAndAfterCommitJobsAndReacquiresTheQueue()
public function testBulkRollbackDoesNotBeginAnEnqueueAttempt(): void
{
$queue = new TestDatabaseQueue(
- resolver: $resolver = Double::for(ConnectionResolverInterface::class),
+ resolver: $resolver = Double::for(ConnectionResolverInterface::class)->strict(),
connection: null,
table: 'table',
default: 'default',
@@ -815,7 +815,7 @@ public function testBulkRollbackDoesNotBeginAnEnqueueAttempt(): void
public function testBuildDatabaseRecordWithPayloadAtTheEnd(): void
{
- $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class), null, 'table', 'default');
+ $queue = new DatabaseQueue(Double::for(ConnectionResolverInterface::class)->strict(), null, 'table', 'default');
$class = new ReflectionClass(DatabaseQueue::class);
$record = $class->getMethod('buildDatabaseRecord')->invoke($queue, 'queue', 'any_payload', 0);
$this->assertArrayHasKey('payload', $record);
@@ -834,11 +834,11 @@ public function testReservedTimestampRoundsUpAtFractionalSecond(): void
public function testGetLockForPoppingIsCached(): void
{
- $pdo = Double::for(PDO::class);
+ $pdo = Double::for(PDO::class)->strict();
// Initial resolution reads the version and identifies MariaDB; later calls reuse the lock.
$pdo->expects('getAttribute')->times(2)->with(PDO::ATTR_SERVER_VERSION)->returns('8.0.36');
$database = new MySqlConnection($pdo, 'test');
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$resolver->expects('connection')->times(2)->with(null)->returns($database);
$queue = new TestDatabaseQueue($resolver, null, 'table', 'default', 1732502704);
@@ -878,14 +878,14 @@ public function testInvalidInspectedPayloadIdentifiesItsQueueAndRecord(): void
*/
private function createFailingReservationQueue(Throwable $failure): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
$resolver->allows('connection')->with(null)->returns($connection);
$connection->allows('transactionLevel')->returns(0);
$connection->expects('transaction')->resolves(static fn (Closure $callback): mixed => $callback());
$container = new Container;
- $events = Double::for(DispatcherContract::class);
+ $events = Double::for(DispatcherContract::class)->strict();
$container->instance(DispatcherContract::class, $events);
$queue = Double::for(DatabaseQueue::class)->passthru(new DatabaseQueue($resolver, null, 'jobs'));
$queue->setContainer($container);
@@ -896,7 +896,7 @@ private function createFailingReservationQueue(Throwable $failure): array
'attempts' => 255,
]);
$queue->expects('getNextAvailableJob')->with('default')->returns($record);
- $queue->expects('marshalJob')->with('default', $record)->throws($failure);
+ $queue->expects('marshalJob')->with('default', Argument::same($record))->throws($failure);
return [$queue, $events];
}
@@ -906,9 +906,9 @@ private function createFailingReservationQueue(Throwable $failure): array
*/
private function createInspectionQueue(): array
{
- $resolver = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
- $query = Double::for(Builder::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
+ $query = Double::for(Builder::class)->strict();
$resolver->expects('connection')->with(null)->returns($connection);
$connection->expects('table')->with('table')->returns($query);
diff --git a/tests/Queue/QueueForgetFailedCommandTest.php b/tests/Queue/QueueForgetFailedCommandTest.php
index 9df3611a73..d38d98c42c 100644
--- a/tests/Queue/QueueForgetFailedCommandTest.php
+++ b/tests/Queue/QueueForgetFailedCommandTest.php
@@ -21,7 +21,7 @@ class QueueForgetFailedCommandTest extends TestCase
public function testItForgetsASingleJob(): void
{
$container = new Application;
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$failer->expects('forget')->with('5')->returns(true);
$container->instance(FailedJobProviderInterface::class, $failer);
@@ -37,7 +37,7 @@ public function testItForgetsASingleJob(): void
public function testItForgetsMultipleJobs(): void
{
$container = new Application;
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$failer->expects('forget')->with('5')->returns(true);
$failer->expects('forget')->with('6')->returns(true);
$container->instance(FailedJobProviderInterface::class, $failer);
@@ -58,7 +58,7 @@ public function testItForgetsMultipleJobs(): void
public function testItFailsWhenAJobCannotBeFound(): void
{
$container = new Application;
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$failer->expects('forget')->with('5')->returns(false);
$container->instance(FailedJobProviderInterface::class, $failer);
@@ -74,7 +74,7 @@ public function testItFailsWhenAJobCannotBeFound(): void
public function testItForgetsTheRemainingJobsWhenOneCannotBeFound(): void
{
$container = new Application;
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$failer->expects('forget')->with('5')->returns(true);
$failer->expects('forget')->with('6')->returns(false);
$failer->expects('forget')->with('7')->returns(true);
diff --git a/tests/Queue/QueueListFailedCommandTest.php b/tests/Queue/QueueListFailedCommandTest.php
index ead57f4249..fa7605cab4 100644
--- a/tests/Queue/QueueListFailedCommandTest.php
+++ b/tests/Queue/QueueListFailedCommandTest.php
@@ -169,7 +169,7 @@ private function executeCommand(array $rows): string
$container = new Application;
// The command resolves the failer via the queue.failer container binding.
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$failer->expects('all')->returns($rows);
$container->instance('queue.failer', $failer);
diff --git a/tests/Queue/QueueListenerTest.php b/tests/Queue/QueueListenerTest.php
index d3a1609ef1..8fa8d2d443 100644
--- a/tests/Queue/QueueListenerTest.php
+++ b/tests/Queue/QueueListenerTest.php
@@ -71,7 +71,6 @@ public function testListenRestsForFractionalSecondsBetweenWorkers(): void
$stop = new RuntimeException('Stop listening.');
$runs = 0;
$listener = Double::for(Listener::class)->passthru(new Listener(__DIR__));
- $listener->allows('makeProcess')->returns(Double::for(Process::class));
$listener->expects('runProcess')->times(2)->resolves(static function () use (&$runs, $stop): void {
if (++$runs === 2) {
throw $stop;
diff --git a/tests/Queue/QueueManagerTest.php b/tests/Queue/QueueManagerTest.php
index 92cfb1131b..9fb42dc823 100644
--- a/tests/Queue/QueueManagerTest.php
+++ b/tests/Queue/QueueManagerTest.php
@@ -31,6 +31,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use ReflectionProperty;
use RuntimeException;
@@ -52,7 +53,7 @@ public function testIntegerEnumConnectionNamesAreNormalizedWithoutTreatingZeroAs
$queue = Double::for(NullQueue::class)->strict();
$queue->expects('setConnectionName')->with('0');
$queue->expects('setConfig');
- $queue->expects('setContainer')->with($container);
+ $queue->expects('setContainer')->with(Argument::same($container));
$connector->expects('connect')->with(['driver' => 'sync'])->returns($queue);
$manager->addConnector('sync', fn () => $connector);
@@ -367,7 +368,7 @@ public function testPoolableConnectionsConvergeByConstructionConfigAndApplyTheir
'driver' => 'custom',
'queue' => 'shared',
])->returns($queue);
- $queue->expects('setContainer')->with($container);
+ $queue->expects('setContainer')->with(Argument::same($container));
$queue->expects('setConfig')->with([
'driver' => 'custom',
'queue' => 'shared',
@@ -406,7 +407,7 @@ public function testPurgeInvalidatesCachedAndUncachedQueuePools(): void
'driver' => 'custom',
'queue' => 'shared',
])->returns($queue);
- $queue->expects('setContainer')->times(2)->with($container);
+ $queue->expects('setContainer')->times(2)->with(Argument::same($container));
$queue->expects('setConfig')->times(2)->with([
'driver' => 'custom',
'queue' => 'shared',
@@ -448,7 +449,7 @@ public function testConvergedConnectionsApplyTheirLogicalNameToPoppedJobs(): voi
$currentName = '';
$connector->expects('connect')->with($connectionConfig)->returns($queue);
- $queue->expects('setContainer')->with($container);
+ $queue->expects('setContainer')->with(Argument::same($container));
$queue->expects('setConfig')->with($connectionConfig);
$queue->expects('setConnectionName')->times(2)
->resolves(function (string $name) use (&$currentName, $queue): Queue {
@@ -492,8 +493,8 @@ public function testSetApplicationEvictsPooledConnectionsAndRebindsTheirFactory(
$manager->addConnector('custom', fn () => $connector);
$connector->expects('connect')->times(2)->returns($queue);
- $queue->expects('setContainer')->with($oldContainer);
- $queue->expects('setContainer')->with($newContainer);
+ $queue->expects('setContainer')->with(Argument::same($oldContainer));
+ $queue->expects('setContainer')->with(Argument::same($newContainer));
$queue->expects('setConfig')->times(2);
$queue->expects('setConnectionName')->times(2)->with('foo');
$queue->expects('size')->times(2)->with()->returns(1);
@@ -532,10 +533,10 @@ public function testSetApplicationUpdatesCachedDirectQueueInPlace(): void
$manager->addConnector('sync', fn () => $connector);
$connector->expects('connect')->with(['driver' => 'sync'])->returns($queue);
- $queue->expects('setContainer')->with($oldContainer);
+ $queue->expects('setContainer')->with(Argument::same($oldContainer));
$queue->expects('setConfig')->with(['driver' => 'sync']);
$queue->expects('setConnectionName')->with('sync');
- $queue->expects('setContainer')->with($newContainer);
+ $queue->expects('setContainer')->with(Argument::same($newContainer));
$this->assertSame($queue, $manager->connection('sync'));
$this->assertSame($manager, $manager->setApplication($newContainer));
diff --git a/tests/Queue/QueuePauseResumeTest.php b/tests/Queue/QueuePauseResumeTest.php
index a83fd7ff34..014428ef9e 100644
--- a/tests/Queue/QueuePauseResumeTest.php
+++ b/tests/Queue/QueuePauseResumeTest.php
@@ -65,7 +65,7 @@ protected function createManager(CacheContract $cache): QueueManager
],
],
]));
- $cacheManager = Double::for(CacheFactory::class);
+ $cacheManager = Double::for(CacheFactory::class)->strict();
$cacheManager->allows('store')->returns($cache);
$container->instance('cache', $cacheManager);
$container->instance('events', $this->events);
@@ -265,7 +265,7 @@ public function testGetPausedQueues(): void
public function testGetPausedQueuesUsesTheCacheRepositoryContract(): void
{
- $cache = Double::for(CacheContract::class);
+ $cache = Double::for(CacheContract::class)->strict();
$cache->expects('get')->with('illuminate:queues:paused', false)->returns(false);
$cache->expects('get')->with([
'illuminate:queue:paused:redis:default',
diff --git a/tests/Queue/QueuePoolProxyTest.php b/tests/Queue/QueuePoolProxyTest.php
index 2885c4a77a..d203c32b3c 100644
--- a/tests/Queue/QueuePoolProxyTest.php
+++ b/tests/Queue/QueuePoolProxyTest.php
@@ -29,6 +29,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use Pheanstalk\Contract\JobIdInterface;
use Pheanstalk\Contract\PheanstalkManagerInterface;
use Pheanstalk\Contract\PheanstalkPublisherInterface;
@@ -227,7 +228,7 @@ public function testPopFailureStaysPrimaryWhenReleaseCallbackAlsoFails(): void
$operationException = new Exception('pop failed');
$finalizationException = new Exception('reset failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($finalizationException);
+ $handler->expects('report')->with(Argument::same($finalizationException));
[$proxy, $pools] = $this->proxy(
fn () => new QueuePoolProxyTestQueue(popException: $operationException),
function () use ($finalizationException): never {
@@ -378,6 +379,7 @@ public function testTerminalBackendFailureDiscardsTheQueueAndCreatesAReplacement
$this->assertSame($backendException, $exception);
}
+ $this->assertSame('DeleteMessage', $handler->getLastCommand()->getName());
$pool = $pools->get($proxy->getPoolName());
$this->assertSame(0, $pool->getManagedCount());
@@ -436,7 +438,7 @@ public function testBeanstalkAttemptPrimingFailureRecoversTheReservedJob(
$handler = Double::for(ExceptionHandler::class)->strict();
if ($recoveryFails) {
- $handler->expects('report')->with($recoveryException);
+ $handler->expects('report')->with(Argument::same($recoveryException));
}
[$proxy, $pools] = $this->proxy(
diff --git a/tests/Queue/QueueRedisJobTest.php b/tests/Queue/QueueRedisJobTest.php
index 60e8359ab7..b87520488e 100644
--- a/tests/Queue/QueueRedisJobTest.php
+++ b/tests/Queue/QueueRedisJobTest.php
@@ -11,6 +11,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
class QueueRedisJobTest extends TestCase
{
@@ -31,7 +32,7 @@ public function testDeleteRemovesTheJobFromRedis(): void
{
$job = $this->getJob();
$job->getRedisQueue()->expects('deleteReserved')
- ->with('default', $job);
+ ->with('default', Argument::same($job));
$job->delete();
}
@@ -40,7 +41,7 @@ public function testReleaseProperlyReleasesJobOntoRedis(): void
{
$job = $this->getJob();
$job->getRedisQueue()->expects('deleteAndRelease')
- ->with('default', $job, 1);
+ ->with('default', Argument::same($job), 1);
$job->release(1);
}
@@ -106,7 +107,7 @@ protected function getJob(?string $payload = null, ?int $attempts = 2): RedisJob
{
return new RedisJob(
new Container,
- Double::for(RedisQueue::class),
+ Double::for(RedisQueue::class)->strict(),
$payload ?? json_encode(['job' => 'foo', 'data' => ['data'], 'attempts' => 1], JSON_THROW_ON_ERROR),
json_encode(['job' => 'foo', 'data' => ['data'], 'attempts' => 2], JSON_THROW_ON_ERROR),
'connection-name',
diff --git a/tests/Queue/QueueRedisQueueTest.php b/tests/Queue/QueueRedisQueueTest.php
index b9fcbb690c..7778614b0b 100644
--- a/tests/Queue/QueueRedisQueueTest.php
+++ b/tests/Queue/QueueRedisQueueTest.php
@@ -53,7 +53,7 @@ public function testTotalsCountPhysicalQueuesInsidePinnedConnection(string $tota
$routes->forward('emails', 'reports:high');
Container::getInstance()->instance('queue.routes', $routes);
$pinned = false;
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('withPinnedConnection')->resolves(function (callable $callback) use (&$pinned): int {
$pinned = true;
@@ -74,7 +74,7 @@ public function testTotalsCountPhysicalQueuesInsidePinnedConnection(string $tota
return 7;
});
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->allows('connection')->with(null)->returns($connection);
$queue = Double::for(RedisQueue::class)->passthru(new RedisQueue($redis, 'default'));
$queue->expects('allQueueNames')->resolves(function () use (&$pinned): Collection {
@@ -106,31 +106,16 @@ public function testBulkRespectsDelayAttributeWhenPushingOntoRedis(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000'));
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('isCluster')->returns(false);
$connection->expects('evalWithShaCache')
- ->with(Argument::all(function (string $script, array $keys, array $arguments): bool {
- $this->assertSame(LuaScripts::bulk(), $script);
- $this->assertSame([
- 'queues:critical',
- 'queues:critical:notify',
- 'queues:critical:delayed',
- ], $keys);
- $this->assertSame([1005, 1010, 'i'], [$arguments[0], $arguments[2], $arguments[4]]);
- $this->assertSame([
- RedisBulkPropertyDelayJob::class,
- RedisBulkAttributeDelayJob::class,
- 'plain',
- ], [
- json_decode($arguments[1], true)['displayName'],
- json_decode($arguments[3], true)['displayName'],
- json_decode($arguments[5], true)['displayName'],
- ]);
-
- return true;
- }))
+ ->with(LuaScripts::bulk(), [
+ 'queues:critical',
+ 'queues:critical:notify',
+ 'queues:critical:delayed',
+ ], Argument::capture($arguments))
->returns(3);
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->expects('connection')->with('default')->returns($connection);
$queue = new RedisQueue($redis, 'default', 'default');
@@ -141,11 +126,21 @@ public function testBulkRespectsDelayAttributeWhenPushingOntoRedis(): void
new RedisBulkAttributeDelayJob,
'plain',
], ['data'], 'critical'));
+ $this->assertSame([1005, 1010, 'i'], [$arguments[0], $arguments[2], $arguments[4]]);
+ $this->assertSame([
+ RedisBulkPropertyDelayJob::class,
+ RedisBulkAttributeDelayJob::class,
+ 'plain',
+ ], [
+ json_decode($arguments[1], true)['displayName'],
+ json_decode($arguments[3], true)['displayName'],
+ json_decode($arguments[5], true)['displayName'],
+ ]);
}
public function testBulkUsesOneClusterSafeLuaCall(): void
{
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('isCluster')->returns(true);
$connection->expects('evalWithShaCache')
->with(
@@ -157,7 +152,7 @@ public function testBulkUsesOneClusterSafeLuaCall(): void
&& json_decode($arguments[3], true)['job'] === 'second'),
)
->returns(2);
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->expects('connection')->with('default')->returns($connection);
$queue = new RedisQueue($redis, 'default', 'default');
@@ -169,10 +164,10 @@ public function testBulkUsesOneClusterSafeLuaCall(): void
public function testBulkRedisFailureIsNotReplacedByAFailingFailureListener(): void
{
$exception = new RuntimeException('Redis unavailable.');
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('isCluster')->returns(false);
$connection->expects('evalWithShaCache')->throws($exception);
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->expects('connection')->with('default')->returns($connection);
Container::setInstance($container = new Container);
@@ -188,8 +183,8 @@ public function testBulkRedisFailureIsNotReplacedByAFailingFailureListener(): vo
$failed[] = $event;
});
$events->listen(JobQueueingFailed::class, static fn () => throw $listener);
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($listener);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($listener));
$container->instance(ExceptionHandler::class, $handler);
try {
@@ -213,10 +208,10 @@ public function testCancellationRaisesCanceledEventsInsteadOfFailureEvents(strin
if ($cleanupThrows) {
$cancellation = new RuntimeException('Redis cleanup failed.', previous: $cancellation);
}
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('isCluster')->returns(false);
$connection->expects('evalWithShaCache')->throws($cancellation);
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->allows('connection')->with('default')->returns($connection);
Container::setInstance($container = new Container);
@@ -253,7 +248,7 @@ public function testCancellationRaisesCanceledEventsInsteadOfFailureEvents(strin
public function testEmptyBulkDoesNotResolveRedis(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->expects('connection')->never();
$this->assertNull((new RedisQueue($redis, 'default', 'default'))->bulk([]));
@@ -261,16 +256,16 @@ public function testEmptyBulkDoesNotResolveRedis(): void
public function testBulkAcceptsDispatchOwnershipOnlyAfterRedisConfirmsEveryJob(): void
{
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('isCluster')->returns(false);
$connection->expects('evalWithShaCache')->returns(2);
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->expects('connection')->with('default')->returns($connection);
$queue = new RedisQueue($redis, 'default', 'default');
$queue->setContainer(new Container);
$first = new RedisBulkOwnedJob;
$second = new RedisBulkOwnedJob;
- $cache = Double::for(CacheRepository::class);
+ $cache = Double::for(CacheRepository::class)->strict();
DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1');
DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2');
@@ -282,10 +277,10 @@ public function testBulkAcceptsDispatchOwnershipOnlyAfterRedisConfirmsEveryJob()
public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void
{
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('isCluster')->returns(false);
$connection->expects('evalWithShaCache')->returns(2);
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->expects('connection')->with('default')->returns($connection);
$queue = new RedisQueue($redis, 'default', 'default');
$dispatcher = new EventDispatcher($container = new Container);
@@ -294,7 +289,7 @@ public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void
$queue->setConnectionName('redis');
$first = new RedisBulkOwnedJob;
$second = new RedisBulkOwnedJob;
- $cache = Double::for(CacheRepository::class);
+ $cache = Double::for(CacheRepository::class)->strict();
DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1');
DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2');
$exception = new RuntimeException('Listener failed.');
@@ -321,16 +316,16 @@ public function testBulkAcceptsEveryDispatchBeforeRaisingSuccessEvents(): void
public function testBulkRetainsDispatchOwnershipWhenRedisDoesNotConfirmEveryJob(): void
{
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('isCluster')->returns(false);
$connection->expects('evalWithShaCache')->returns(1);
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->expects('connection')->with('default')->returns($connection);
$queue = new RedisQueue($redis, 'default', 'default');
$queue->setContainer(new Container);
$first = new RedisBulkOwnedJob;
$second = new RedisBulkOwnedJob;
- $cache = Double::for(CacheRepository::class);
+ $cache = Double::for(CacheRepository::class)->strict();
DispatchLockContext::registerDebounce($first, $cache, 'first', 'owner-1');
DispatchLockContext::registerDebounce($second, $cache, 'second', 'owner-2');
$caught = null;
@@ -348,7 +343,7 @@ public function testBulkRetainsDispatchOwnershipWhenRedisDoesNotConfirmEveryJob(
public function testBulkDefersAfterCommitMembersWithoutLosingOwnership(): void
{
- $connection = Double::for(QueueRedisProxy::class);
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$connection->expects('isCluster')->returns(false);
$storedJobs = [];
$connection->expects('evalWithShaCache')->times(2)->resolves(
@@ -358,7 +353,7 @@ static function (string $script, array $keys, array $arguments) use (&$storedJob
return 1;
}
);
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$redis->expects('connection')->times(2)->with('default')->returns($connection);
$transactions = new DatabaseTransactionsManager;
$transactions->begin('default', 1);
@@ -367,7 +362,7 @@ static function (string $script, array $keys, array $arguments) use (&$storedJob
$queue = new RedisQueue($redis, 'default', 'default');
$queue->setContainer($container);
$deferred = new RedisBulkAfterCommitJob;
- DispatchLockContext::registerDebounce($deferred, Double::for(CacheRepository::class), 'deferred', 'owner');
+ DispatchLockContext::registerDebounce($deferred, Double::for(CacheRepository::class)->strict(), 'deferred', 'owner');
$queue->bulk(['immediate', $deferred]);
@@ -386,18 +381,18 @@ public function testJobQueueingAndQueuedEventsAreSkippedWhenNoListenersAreRegist
CarbonImmutable::setTestNow($now);
$uuid = $this->mockUuid();
- $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default'])->getMock();
+ $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class)->strict(), 'default', 'default'])->getMock();
$queue->expects($this->once())->method('getRandomId')->willReturn('foo');
$container = Double::for(Container::class, override: true)->passthru(new Container);
$queue->setContainer($container->instance());
$queue->setConnectionName('default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(false);
$redisProxy->expects('evalWithShaCache')->with(LuaScripts::push(), ['queues:default', 'queues:default:notify'], [json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'stringJob' => true, 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $now->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => null])]);
$redis->expects('connection')->times(2)->returns($redisProxy);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->expects('hasListeners')->with(JobQueueing::class)->returns(false);
$events->expects('hasListeners')->with(JobQueued::class)->returns(false);
@@ -419,7 +414,7 @@ public function testFinalPayloadListenerMutatesTheBrokerAndTerminalPayload(): vo
$uuid = $this->mockUuid();
$queue = $this->getMockBuilder(RedisQueue::class)
->onlyMethods(['getRandomId'])
- ->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default'])
+ ->setConstructorArgs([$redis = Double::for(Redis::class)->strict(), 'default', 'default'])
->getMock();
$queue->expects($this->once())->method('getRandomId')->willReturn('job-id');
$dispatcher = new EventDispatcher($container = new Container);
@@ -441,7 +436,7 @@ public function testFinalPayloadListenerMutatesTheBrokerAndTerminalPayload(): vo
$events[] = $event;
});
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(false);
$redisProxy->expects('evalWithShaCache')->with(Argument::all(
static fn (string $script, array $keys, array $arguments): bool => $script === LuaScripts::push()
@@ -466,7 +461,7 @@ public function testFinalPayloadListenerFailureRaisesFailureBeforeQueueingAndBro
$exception = new RuntimeException('Unable to finalize payload.');
$queue = $this->getMockBuilder(RedisQueue::class)
->onlyMethods(['getRandomId'])
- ->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default'])
+ ->setConstructorArgs([$redis = Double::for(Redis::class)->strict(), 'default', 'default'])
->getMock();
$queue->expects($this->once())->method('getRandomId')->willReturn('job-id');
$dispatcher = new EventDispatcher($container = new Container);
@@ -506,18 +501,18 @@ public function testPushRaisesFailedEventWhenRedisThrows(): void
$uuid = $this->mockUuid();
$exception = new RuntimeException('Redis unavailable.');
- $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default'])->getMock();
+ $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class)->strict(), 'default', 'default'])->getMock();
$queue->expects($this->once())->method('getRandomId')->willReturn('foo');
$container = Double::for(Container::class, override: true)->passthru(new Container);
$queue->setContainer($container->instance());
$queue->setConnectionName('default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(false);
$redisProxy->expects('evalWithShaCache')->throws($exception);
$redis->expects('connection')->times(2)->returns($redisProxy);
- $events = Double::for(Dispatcher::class);
+ $events = Double::for(Dispatcher::class)->strict();
$events->expects('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->expects('hasListeners')->with(JobQueueing::class)->returns(true);
$events->expects('hasListeners')->with(JobQueueingFailed::class)->returns(true);
@@ -558,14 +553,14 @@ public function testDelayedPushRoundsUpFractionalDeadlines(): void
$now = CarbonImmutable::now();
$uuid = $this->mockUuid();
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis, 'default', 'default'])->getMock();
$container = Double::for(Container::class, override: true)->passthru(new Container);
$queue->setContainer($container->instance());
$queue->setConnectionName('default');
$queue->expects($this->once())->method('getRandomId')->willReturn('foo');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(false);
$redisProxy->expects('evalWithShaCache')->with(
LuaScripts::later(),
@@ -586,14 +581,14 @@ public function testDelayedDateTimePushRoundsUpFractionalDeadlines(): void
$uuid = $this->mockUuid();
$date = CarbonImmutable::createFromTimestampUTC('1001.100000');
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis, 'default', 'default'])->getMock();
$container = Double::for(Container::class, override: true)->passthru(new Container);
$queue->setContainer($container->instance());
$queue->setConnectionName('default');
$queue->expects($this->once())->method('getRandomId')->willReturn('foo');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(false);
$redisProxy->expects('evalWithShaCache')->with(
LuaScripts::later(),
@@ -613,13 +608,13 @@ public function testDelayedPushWithIntervalNeverRunsBeforeRequestedLifetime(): v
$uuid = $this->mockUuid();
$delay = new DateInterval('PT1S');
- $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default'])->getMock();
+ $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = Double::for(Redis::class)->strict(), 'default', 'default'])->getMock();
$container = Double::for(Container::class, override: true)->passthru(new Container);
$queue->setContainer($container->instance());
$queue->setConnectionName('default');
$queue->expects($this->once())->method('getRandomId')->willReturn('foo');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(false);
$redisProxy->expects('evalWithShaCache')->with(
LuaScripts::later(),
@@ -634,7 +629,7 @@ public function testDelayedPushWithIntervalNeverRunsBeforeRequestedLifetime(): v
public function testGetQueueRemainsUnchangedForNonCluster(): void
{
- $queue = new RedisQueue(Double::for(Redis::class), 'default', 'default');
+ $queue = new RedisQueue(Double::for(Redis::class)->strict(), 'default', 'default');
$this->assertSame('queues:default', $queue->getQueue(null));
$this->assertSame('queues:default', $queue->getQueue(''));
@@ -647,7 +642,7 @@ public function testGetQueueRemainsUnchangedForNonCluster(): void
public function testGetQueueRemainsUnchangedForCluster(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new RedisQueue($redis, 'default', 'default');
$redis->expects('connection')->never();
@@ -660,9 +655,9 @@ public function testGetQueueRemainsUnchangedForCluster(): void
public function testGetRedisKeyReturnsPlainKeyForNonCluster(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(false);
$redis->expects('connection')->returns($redisProxy);
@@ -674,9 +669,9 @@ public function testGetRedisKeyReturnsPlainKeyForNonCluster(): void
public function testGetRedisKeyWrapsWithHashTagsForPhpRedisCluster(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redis->expects('connection')->returns($redisProxy);
@@ -690,9 +685,9 @@ public function testGetRedisKeyWrapsWithHashTagsForPhpRedisCluster(): void
public function testGetRedisKeyDoesNotDoubleWrapExistingHashTags(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, '{default}', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redis->expects('connection')->returns($redisProxy);
@@ -702,9 +697,9 @@ public function testGetRedisKeyDoesNotDoubleWrapExistingHashTags(): void
public function testGetRedisKeySkipsWrappingWhenQueueNameContainsBraces(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redis->expects('connection')->returns($redisProxy);
@@ -714,9 +709,9 @@ public function testGetRedisKeySkipsWrappingWhenQueueNameContainsBraces(): void
public function testGetRedisKeyWrapsEmptyHashTagOnCluster(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redis->expects('connection')->returns($redisProxy);
@@ -726,9 +721,9 @@ public function testGetRedisKeyWrapsEmptyHashTagOnCluster(): void
public function testGetRedisKeyWrapsUnmatchedOpeningBrace(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redis->expects('connection')->returns($redisProxy);
@@ -738,9 +733,9 @@ public function testGetRedisKeyWrapsUnmatchedOpeningBrace(): void
public function testGetRedisKeyWrapsUnmatchedClosingBrace(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redis->expects('connection')->returns($redisProxy);
@@ -750,9 +745,9 @@ public function testGetRedisKeyWrapsUnmatchedClosingBrace(): void
public function testGetRedisKeyWrapsEmptyFirstHashTagFollowedByValidPair(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redis->expects('connection')->returns($redisProxy);
@@ -767,7 +762,7 @@ public function testPushUsesGetRedisKeyForLuaScript(): void
CarbonImmutable::setTestNow($now);
$uuid = $this->mockUuid();
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = $this->getMockBuilder(RedisQueue::class)
->onlyMethods(['getRandomId'])
->setConstructorArgs([$redis, 'default', 'default'])
@@ -777,7 +772,7 @@ public function testPushUsesGetRedisKeyForLuaScript(): void
$queue->setContainer($container->instance());
$queue->setConnectionName('default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redisProxy->expects('evalWithShaCache')->with(
LuaScripts::push(),
@@ -796,7 +791,7 @@ public function testPushPassesUnchangedQueueToCreatePayload(): void
CarbonImmutable::setTestNow($now);
$this->mockUuid();
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = $this->getMockBuilder(RedisQueue::class)
->onlyMethods(['getRandomId'])
->setConstructorArgs([$redis, 'default', 'default'])
@@ -805,7 +800,7 @@ public function testPushPassesUnchangedQueueToCreatePayload(): void
$queue->setContainer(new Container);
$queue->setConnectionName('default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redisProxy->expects('evalWithShaCache')->returns(null);
$redis->expects('connection')->times(2)->returns($redisProxy);
@@ -835,7 +830,7 @@ public function testLaterUsesClusterSafeRedisKeyForDelayedSet(): void
$queue = $this->getMockBuilder(RedisQueue::class)
->onlyMethods(['availableAt', 'getRandomId'])
- ->setConstructorArgs([$redis = Double::for(Redis::class), 'default', 'default'])
+ ->setConstructorArgs([$redis = Double::for(Redis::class)->strict(), 'default', 'default'])
->getMock();
$container = Double::for(Container::class, override: true)->passthru(new Container);
$queue->setContainer($container->instance());
@@ -843,7 +838,7 @@ public function testLaterUsesClusterSafeRedisKeyForDelayedSet(): void
$queue->expects($this->once())->method('getRandomId')->willReturn('foo');
$queue->expects($this->once())->method('availableAt')->with(1)->willReturn(2);
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redisProxy->expects('evalWithShaCache')->with(
LuaScripts::later(),
@@ -858,9 +853,9 @@ public function testLaterUsesClusterSafeRedisKeyForDelayedSet(): void
public function testSizeUsesGetRedisKeyOnCluster(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new RedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redisProxy->expects('eval')->with(
LuaScripts::size(),
@@ -878,9 +873,9 @@ public function testPopUsesClusterSafeRedisKeys(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000'));
- $queue = new RedisQueue($redis = Double::for(Redis::class), 'default', 'default');
+ $queue = new RedisQueue($redis = Double::for(Redis::class)->strict(), 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redisProxy->expects('eval')->with(
LuaScripts::migrateExpiredJobs(),
@@ -925,7 +920,7 @@ public function testPoppedJobPreservesZeroQueueAndDefaultsEmptyQueue(): void
foreach ([['0', '0'], ['', 'default']] as [$requested, $expected]) {
$queue = $this->getMockBuilder(RedisQueue::class)
->onlyMethods(['getQueueRedisKey', 'migrate', 'retrieveNextJob'])
- ->setConstructorArgs([Double::for(Redis::class), 'default', 'default'])
+ ->setConstructorArgs([Double::for(Redis::class)->strict(), 'default', 'default'])
->getMock();
$queue->setContainer(new Container);
$queue->setConnectionName('redis');
@@ -944,7 +939,7 @@ public function testPoppedRawZeroIsNotMistakenForAnEmptyQueue(): void
{
$queue = $this->getMockBuilder(RedisQueue::class)
->onlyMethods(['getQueueRedisKey', 'migrate', 'retrieveNextJob'])
- ->setConstructorArgs([Double::for(Redis::class), 'default', 'default'])
+ ->setConstructorArgs([Double::for(Redis::class)->strict(), 'default', 'default'])
->getMock();
$queue->setContainer(new Container);
$queue->setConnectionName('redis');
@@ -961,11 +956,11 @@ public function testPoppedRawZeroIsNotMistakenForAnEmptyQueue(): void
public function testDeleteReservedUsesClusterSafeRedisKey(): void
{
- $queue = new RedisQueue($redis = Double::for(Redis::class), 'default', 'default');
- $job = Double::for(RedisJob::class);
+ $queue = new RedisQueue($redis = Double::for(Redis::class)->strict(), 'default', 'default');
+ $job = Double::for(RedisJob::class)->strict();
$job->expects('getReservedJob')->returns('reserved-payload');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redisProxy->expects('zrem')->with('queues:{emails}:reserved', 'reserved-payload')->returns(1);
$redis->expects('connection')->times(2)->returns($redisProxy);
@@ -977,12 +972,12 @@ public function testDeleteAndReleaseUsesClusterSafeRedisKeys(): void
{
CarbonImmutable::setTestNow(CarbonImmutable::createFromTimestampUTC('1000.900000'));
- $queue = new RedisQueue($redis = Double::for(Redis::class), 'default', 'default');
+ $queue = new RedisQueue($redis = Double::for(Redis::class)->strict(), 'default', 'default');
- $job = Double::for(RedisJob::class);
+ $job = Double::for(RedisJob::class)->strict();
$job->expects('getReservedJob')->returns('reserved-payload');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redisProxy->expects('eval')->with(
LuaScripts::release(),
@@ -999,9 +994,9 @@ public function testDeleteAndReleaseUsesClusterSafeRedisKeys(): void
public function testClearUsesGetRedisKeyOnCluster(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new RedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redisProxy->expects('eval')->with(
LuaScripts::clear(),
@@ -1018,9 +1013,9 @@ public function testClearUsesGetRedisKeyOnCluster(): void
public function testIsClusterConnectionCachesResult(): void
{
- $redis = Double::for(Redis::class);
+ $redis = Double::for(Redis::class)->strict();
$queue = new TestableRedisQueue($redis, 'default', 'default');
- $redisProxy = Double::for(QueueRedisProxy::class);
+ $redisProxy = Double::for(QueueRedisProxy::class)->strict();
$redisProxy->expects('isCluster')->returns(true);
$redis->expects('connection')->returns($redisProxy);
@@ -1031,8 +1026,8 @@ public function testIsClusterConnectionCachesResult(): void
public function testSizeResolvesTheQueueNameFromAnEnum(): void
{
- $redis = Double::for(Redis::class);
- $connection = Double::for(QueueRedisProxy::class);
+ $redis = Double::for(Redis::class)->strict();
+ $connection = Double::for(QueueRedisProxy::class)->strict();
$redis->expects('connection')->times(2)->with(null)->returns($connection);
$connection->expects('isCluster')->returns(false);
$connection->expects('eval')->with(
diff --git a/tests/Queue/QueueRetryCommandTest.php b/tests/Queue/QueueRetryCommandTest.php
index 34de76a791..19b42bad6b 100644
--- a/tests/Queue/QueueRetryCommandTest.php
+++ b/tests/Queue/QueueRetryCommandTest.php
@@ -38,8 +38,8 @@ class QueueRetryCommandTest extends TestCase
public function testRetriesSingleJobByPushingItsRawPayload(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$job = $this->failedJob(id: '5', connection: 'database', queue: 'default');
@@ -52,8 +52,8 @@ public function testRetriesSingleJobByPushingItsRawPayload(): void
public function testRetriesSingleJobByPushingItsRawPayloadWithOptions(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(SqsQueue::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(SqsQueue::class)->strict();
$job = $this->failedJob(id: '5', connection: 'database', queue: 'default');
@@ -71,7 +71,7 @@ public function testRetriesSingleJobByPushingItsRawPayloadWithOptions(): void
#[TestWith(['0'])]
public function testDisplaysErrorWhenJobIsNotFound(string $id): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$failer->expects('find')->with($id)->returns(null);
$output = $this->runRetryCommand(['id' => [$id]], $failer, []);
@@ -83,8 +83,8 @@ public function testDisplaysErrorWhenJobIsNotFound(string $id): void
#[TestWith([[1, 2]])]
public function testRetriesAllFailedJobsUsingTheProvidersIds(array $ids): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('ids')->with()->returns($ids);
@@ -106,8 +106,8 @@ public function testRetriesAllFailedJobsUsingTheProvidersIds(array $ids): void
#[TestWith(['0'])]
public function testRetriesJobsOnTheSpecifiedQueue(string $queueName): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('ids')->with($queueName)->returns(['2']);
$failer->expects('find')->with('2')->returns($this->failedJob(id: '2', connection: 'database', queue: $queueName));
@@ -119,7 +119,7 @@ public function testRetriesJobsOnTheSpecifiedQueue(string $queueName): void
public function testDisplaysErrorWhenTheSpecifiedQueueHasNoFailedJobs(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$failer->expects('ids')->with('emails')->returns([]);
$output = $this->runRetryCommand(['--queue' => 'emails'], $failer, []);
@@ -130,8 +130,8 @@ public function testDisplaysErrorWhenTheSpecifiedQueueHasNoFailedJobs(): void
public function testRetriesJobsWithinTheGivenIdRange(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('find')->with('1')->returns($this->failedJob(id: '1', connection: 'database', queue: 'default'));
$queue->expects('pushRaw')->with($this->retriedPayload(id: '1'), 'default', []);
@@ -159,8 +159,8 @@ public function testDisplaysInfoWhenThereAreNoJobsToRetry(): void
public function testItResetsAttemptsCountWhenRetryingAJob(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$job = $this->failedJob(id: '1', connection: 'database', queue: 'default', payload: ['attempts' => 5]);
@@ -177,8 +177,8 @@ public function testItResetsAttemptsCountWhenRetryingAJob(): void
#[TestWith([true], 'custom object handler')]
public function testRefreshesTheRetryUntilTimestampWhenTheJobDefinesRetryUntil(bool $customHandler): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$job = $this->failedJob(
id: '1',
@@ -207,8 +207,8 @@ public function testRefreshesTheRetryUntilTimestampWhenTheJobDefinesRetryUntil(b
public function testPassesQueueableOptionsToTheQueueWhenRetryingASingleJob(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(SqsQueue::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(SqsQueue::class)->strict();
$job = $this->failedJob(id: '1', connection: 'sqs', queue: 'default');
@@ -224,9 +224,9 @@ public function testPassesQueueableOptionsToTheQueueWhenRetryingASingleJob(): vo
public function testDispatchesRetryRequestedEventWhenRetryingASingleJob(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
- $events = Double::for(Dispatcher::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
+ $events = Double::for(Dispatcher::class)->strict();
$job = $this->failedJob(id: '1', connection: 'database', queue: 'default');
@@ -240,8 +240,8 @@ public function testDispatchesRetryRequestedEventWhenRetryingASingleJob(): void
public function testRetriesCollectionOfJobs(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$jobs = new Collection([
'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'),
@@ -261,8 +261,8 @@ public function testRetriesCollectionOfJobs(): void
public function testRetriesALazyCollectionOfJobsAndDoesNotResolveThemAllEagerly(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$unresolvedCounts = [];
@@ -315,8 +315,8 @@ public function testRetriesALazyCollectionOfJobsAndDoesNotResolveThemAllEagerly(
public function testItResetsAttemptsCountWhenRetryingACollectionOfJobs(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$jobs = new Collection([
'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default', payload: ['attempts' => 5]),
@@ -333,8 +333,8 @@ public function testItResetsAttemptsCountWhenRetryingACollectionOfJobs(): void
public function testRefreshesTheRetryUntilTimestampWhenRetryingACollectionOfJobs(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$jobs = new Collection([
'job-1' => $this->failedJob(
@@ -357,7 +357,7 @@ public function testRefreshesTheRetryUntilTimestampWhenRetryingACollectionOfJobs
public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyCollection(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$failer->expects('find')->with('batch')->returns(new Collection);
$output = $this->runRetryCommand(['id' => ['batch']], $failer, []);
@@ -369,7 +369,7 @@ public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyCollection(): vo
public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyLazyCollection(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$resolved = false;
@@ -390,8 +390,8 @@ public function testDisplaysErrorWhenTheGivenIdResolvesToAnEmptyLazyCollection()
public function testContinuesRetryingRemainingJobsAfterAJobIsNotFound(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('find')->with('1')->returns(null);
@@ -407,8 +407,8 @@ public function testContinuesRetryingRemainingJobsAfterAJobIsNotFound(): void
public function testContinuesRetryingRemainingJobsAfterAnIdResolvesToAnEmptyCollection(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('find')->with('batch')->returns(new Collection);
@@ -424,8 +424,8 @@ public function testContinuesRetryingRemainingJobsAfterAnIdResolvesToAnEmptyColl
public function testRetriesAMixtureOfSingleJobsAndCollectionsOfJobs(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('find')->with('batch')->returns(new Collection([
'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'),
@@ -448,8 +448,8 @@ public function testRetriesAMixtureOfSingleJobsAndCollectionsOfJobs(): void
public function testForgetsJobsUsingTheCollectionKeyRatherThanTheJobId(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$key = 'https://cloud.test/failed-jobs/batch-1:job-1';
@@ -467,8 +467,8 @@ public function testForgetsJobsUsingTheCollectionKeyRatherThanTheJobId(): void
public function testForgetsJobsUsingTheCollectionKeyWhenTheCollectionIsNotKeyed(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('find')->with('batch')->returns(new Collection([
$this->failedJob(id: 'job-1', connection: 'database', queue: 'default'),
@@ -486,9 +486,9 @@ public function testForgetsJobsUsingTheCollectionKeyWhenTheCollectionIsNotKeyed(
public function testDispatchesRetryRequestedEventForEveryJobInACollection(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
- $events = Double::for(Dispatcher::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
+ $events = Double::for(Dispatcher::class)->strict();
$jobs = new Collection([
'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'),
@@ -514,8 +514,8 @@ public function testDispatchesRetryRequestedEventForEveryJobInACollection(): voi
public function testStopsRetryingWhenAJobInACollectionFailsToBePushed(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$pendingJobs = [
'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'),
@@ -557,8 +557,8 @@ public function testStopsRetryingWhenAJobInACollectionFailsToBePushed(): void
public function testRetriesRemainingJobsWhenAJobsModelNoLongerExists(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$missing = $this->failedJob(id: 'job-1', connection: 'database', queue: 'default', job: new QueueRetryCommandTestJobWithMissingModel);
@@ -580,8 +580,8 @@ public function testRetriesRemainingJobsWhenAJobsModelNoLongerExists(): void
public function testRetriesStringJobsWithoutInterpretingTheirCommandData(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$data = ['command' => 'backup:run', 'commandName' => 'backup:run'];
$job = $this->failedJob(id: '1', connection: 'database', queue: 'default');
$job->payload = (new QueueRetryCommandCustomQueue)->payloadFor('RunCommand@handle', $data);
@@ -595,7 +595,7 @@ public function testRetriesStringJobsWithoutInterpretingTheirCommandData(): void
public function testRetriesJobWithoutQueueableOptionsWhenItsModelNoLongerExists(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$handler = new MockHandler([new Result(['MessageId' => 'message-1'])]);
$sqs = $this->sqsClient($handler);
$queue = new SqsQueue($sqs, 'default', 'https://sqs.example.test');
@@ -616,7 +616,7 @@ public function testRetriesJobWithoutQueueableOptionsWhenItsModelNoLongerExists(
#[DataProvider('jobsWithoutRestorableObjects')]
public function testRetriesSqsJobsWithDefaultOptionsWhenNoObjectCanBeRestored(string $queueName, array $payload): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
$handler = new MockHandler([new Result(['MessageId' => 'message-1'])]);
$sqs = $this->sqsClient($handler);
$queue = new SqsQueue($sqs, $queueName, 'https://sqs.example.test');
@@ -671,9 +671,9 @@ public static function jobsWithoutRestorableObjects(): iterable
public function testDispatchesTheEventBeforePushingAndForgetsTheJobAfterwards(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
- $events = Double::for(Dispatcher::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
+ $events = Double::for(Dispatcher::class)->strict();
$jobs = new Collection([
'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'),
@@ -704,8 +704,8 @@ public function testDispatchesTheEventBeforePushingAndForgetsTheJobAfterwards():
public function testOutputsAnEntryForEveryJobInACollection(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$jobs = new Collection([
'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'),
@@ -728,8 +728,8 @@ public function testOutputsAnEntryForEveryJobInACollection(): void
public function testRetriesCollectionsOfJobsWhenRetryingAllFailedJobs(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('ids')->with()->returns(['batch-1', 'batch-2']);
@@ -752,8 +752,8 @@ public function testRetriesCollectionsOfJobsWhenRetryingAllFailedJobs(): void
public function testRetriesTheSameJobTwiceWhenItAppearsInTwoCollections(): void
{
- $failer = Double::for(FailedJobProviderInterface::class);
- $queue = Double::for(QueueContract::class);
+ $failer = Double::for(FailedJobProviderInterface::class)->strict();
+ $queue = Double::for(QueueContract::class)->strict();
$failer->expects('find')->with('batch-1')->returns(new Collection([
'job-1' => $this->failedJob(id: 'job-1', connection: 'database', queue: 'default'),
@@ -832,7 +832,7 @@ private function runRetryCommand(array $input, FailedJobProviderInterface $faile
$container->instance('queue.failer', $failer);
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
foreach ($connections as $name => $queue) {
$manager->allows('connection')->with($name)->returns($queue);
@@ -840,15 +840,11 @@ private function runRetryCommand(array $input, FailedJobProviderInterface $faile
$container->instance('queue', $manager);
- if (is_null($events)) {
- $events = Double::for(Dispatcher::class);
- $events->allows('dispatch');
+ if ($events !== null) {
+ $events->allows('hasListeners')->resolves(static fn (string $event): bool => $event === JobRetryRequested::class);
+ $container->instance('events', $events);
}
- $events->allows('hasListeners')->with(JobRetryRequested::class)->returns(true);
-
- $container->instance('events', $events);
-
$command = new RetryCommand;
$command->setHypervel($container);
diff --git a/tests/Queue/QueueSqsJobTest.php b/tests/Queue/QueueSqsJobTest.php
index dcb4afc3f3..6eba91d2e5 100644
--- a/tests/Queue/QueueSqsJobTest.php
+++ b/tests/Queue/QueueSqsJobTest.php
@@ -173,13 +173,13 @@ public function testGetRawBodyResolvesPointerFromCache(): void
$pointer = 'laravel:sqs-payloads:some-uuid';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('get')->with($pointer)->returns($payload);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$job = new SqsJob(
@@ -207,13 +207,13 @@ public function testGetRawBodyCachesOriginalPointerWhenOverflowPayloadIsUnavaila
$pointer = 'laravel:sqs-payloads:missing';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('get')->with($pointer)->returns($payload);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$job = new SqsJob(
@@ -248,7 +248,7 @@ public function testGetRawBodyReturnsPointerBodyWhenExtendedStoreIsDisabled(): v
'@pointer' => 'laravel:sqs-payloads:disabled',
], JSON_THROW_ON_ERROR);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->never();
$job = new SqsJob(
@@ -268,13 +268,13 @@ public function testGetRawBodyCachesResult(): void
$pointer = 'laravel:sqs-payloads:some-uuid';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('get')->with($pointer)->returns($payload);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$job = new SqsJob(
@@ -296,7 +296,7 @@ public function testDeleteCleansUpCacheKeyWhenCleanupEnabled(): void
$pointer = 'laravel:sqs-payloads:delete';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('forget')->with($pointer)->resolves(
function (): bool {
$this->assertSame('DeleteMessage', $this->handler->getLastCommand()->getName());
@@ -305,10 +305,10 @@ function (): bool {
}
);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$this->handler->append(new Result([]));
@@ -331,7 +331,7 @@ public function testDeleteDoesNotCleanUpWhenCleanupDisabled(): void
'@pointer' => 'laravel:sqs-payloads:retained',
], JSON_THROW_ON_ERROR);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->never();
$this->handler->append(new Result([]));
@@ -349,7 +349,7 @@ public function testDeleteDoesNotCleanUpWhenCleanupDisabled(): void
public function testDeleteDoesNotCleanUpWhenNoPointer(): void
{
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->never();
$this->handler->append(new Result([]));
@@ -376,7 +376,7 @@ public function testReleaseNeverCleansOverflowPayload(): void
'@pointer' => 'laravel:sqs-payloads:released',
], JSON_THROW_ON_ERROR);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->never();
$this->handler->append(new Result([]));
@@ -399,7 +399,7 @@ public function testDeleteRetainsOverflowPayloadWhenSqsDeletionFails(): void
'@pointer' => 'laravel:sqs-payloads:retained',
], JSON_THROW_ON_ERROR);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->never();
$expected = new Exception('delete failed');
$this->handler->append($expected);
@@ -432,13 +432,13 @@ public function testDeleteCleansOverflowPayloadAfterLeaseReleaseFails(): void
$pointer = 'laravel:sqs-payloads:cleanup';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('forget')->with($pointer)->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$this->handler->append(new Result([]));
@@ -472,11 +472,8 @@ public function testDeleteDoesNotStartOverflowCleanupAfterLeaseReleaseCancellati
);
$pointer = 'laravel:sqs-payloads:cleanup';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
- $cache = Double::for(CacheFactory::class);
- $cache->allows('store')->returns($store);
- $container = Double::for(Container::class, override: true);
- $container->allows('make')->returns($cache);
+ $container = Double::for(Container::class, override: true)->strict();
+ $container->expects('make')->with('cache')->never();
$this->handler->append(new Result([]));
$job = new SqsJob(
$container->instance(),
@@ -493,8 +490,6 @@ public function testDeleteDoesNotStartOverflowCleanupAfterLeaseReleaseCancellati
} catch (Throwable $exception) {
$this->assertSame($releaseCancellation, $exception);
}
-
- $store->received('forget')->never();
}
public function testDeleteSurfacesOverflowCleanupFailureAfterSuccessfulDeletion(): void
@@ -502,13 +497,13 @@ public function testDeleteSurfacesOverflowCleanupFailureAfterSuccessfulDeletion(
$pointer = 'laravel:sqs-payloads:cleanup';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('forget')->with($pointer)->returns(false);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$this->handler->append(new Result([]));
@@ -537,24 +532,18 @@ public function testDeleteReportsCleanupFailureWithoutReplacingLeaseReleaseFailu
$pointer = 'laravel:sqs-payloads:cleanup';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('forget')->with($pointer)->returns(false);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$this->handler->append(new Result([]));
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with(Argument::satisfies(
- function (Throwable $exception) use (&$cleanupFailure): bool {
- $cleanupFailure = $exception;
-
- return true;
- }
- ));
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::capture($cleanupFailure));
$application = new Application;
$application->instance(ExceptionHandler::class, $handler);
@@ -594,11 +583,11 @@ public function testOverflowCleanupCancellationSupersedesAnOrdinaryLeaseReleaseF
);
$pointer = 'laravel:sqs-payloads:cleanup';
$pointerBody = json_encode(['@pointer' => $pointer], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('forget')->with($pointer)->throws($cleanupCancellation);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(Container::class, override: true);
+ $container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with('cache')->returns($cache);
$this->handler->append(new Result([]));
$job = new SqsJob(
diff --git a/tests/Queue/QueueSqsQueueTest.php b/tests/Queue/QueueSqsQueueTest.php
index a9460890b1..6fa6038005 100644
--- a/tests/Queue/QueueSqsQueueTest.php
+++ b/tests/Queue/QueueSqsQueueTest.php
@@ -1095,8 +1095,12 @@ public function testPushCancellationPublishesTheKnownOutcome(string $phase): voi
$container->instance('events', $events);
$cancellation = new RuntimeException('Listener cleanup failed.', previous: new CanceledException);
$earlierFailure = new RuntimeException('Earlier notification failed.');
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->times($phase === 'queued' ? 1 : 0)->with($earlierFailure);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ if ($phase === 'queued') {
+ $handler->expects('report')->with(Argument::same($earlierFailure));
+ } else {
+ $handler->expects('report')->never();
+ }
$container->instance(ExceptionHandler::class, $handler);
$notified = [];
$canceled = null;
@@ -1152,10 +1156,10 @@ public function testPushRawStoresPayloadToCacheWhenExceedingThreshold(): void
$path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . $uuid;
$pointer = json_encode(['@pointer' => $path], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($path, $payload)->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = Double::for(Container::class, override: true)->passthru(new Container);
@@ -1216,10 +1220,10 @@ public function testPushRawAlwaysStoresToCacheWhenAlwaysIsTrue(): void
$path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'always-overflow';
$pointer = json_encode(['@pointer' => $path], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($path, $payload)->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = Double::for(Container::class, override: true)->passthru(new Container);
@@ -1275,10 +1279,10 @@ public function testPushRawGeneratesOverflowPathForEveryNonStringOrEmptyUuid(mix
], JSON_THROW_ON_ERROR);
$path = null;
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with(Argument::capture($path), $payload)->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = Double::for(Container::class, override: true)->passthru(new Container);
@@ -1332,7 +1336,7 @@ public function testPushRawFailsBeforeSendingWhenOverflowStorageReturnsFalse(?bo
$cancellation = new RuntimeException('Delete cleanup failed.', previous: $cancellation);
}
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->returns(false);
if ($cleanupThrows === null) {
$store->expects('forget')->with($path)->returns(true);
@@ -1340,10 +1344,10 @@ public function testPushRawFailsBeforeSendingWhenOverflowStorageReturnsFalse(?bo
$store->expects('forget')->with($path)->throws($cancellation);
}
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes);
$container->expects('make')->with('cache')->returns($cache);
@@ -1382,11 +1386,15 @@ public function testPushRawPreservesCancellationAndCleansTheAttemptedOverflowPay
$cleanupCancellation = new RuntimeException('delete cleanup failed', previous: $cleanupCancellation);
}
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($cleanupCancellation)->times($deleteCleanupThrows ? 1 : 0);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ if ($deleteCleanupThrows) {
+ $handler->expects('report')->with(Argument::same($cleanupCancellation));
+ } else {
+ $handler->expects('report')->never();
+ }
Container::getInstance()->instance(ExceptionHandler::class, $handler);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($path, $payload)->throws($cancellation);
if ($deleteCleanupThrows === null) {
$store->expects('forget')->with($path)->returns(true);
@@ -1394,10 +1402,10 @@ public function testPushRawPreservesCancellationAndCleansTheAttemptedOverflowPay
$store->expects('forget')->with($path)->throws($cleanupCancellation);
}
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes);
$container->expects('make')->with('cache')->returns($cache);
@@ -1435,11 +1443,11 @@ public function testPushRawRetainsOverflowPayloadWhenSqsDeliveryIsAmbiguous(): v
{
$payload = json_encode(['uuid' => 'ambiguous'], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->returns(true);
$store->expects('forget')->never();
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = Double::for(Container::class, override: true)->passthru(new Container);
@@ -1467,11 +1475,11 @@ public function testPushRawRetainsOverflowPayloadWhenSqsDeliveryIsCanceled(): vo
$payload = json_encode(['uuid' => 'canceled-delivery'], JSON_THROW_ON_ERROR);
$cancellation = new CanceledException;
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->returns(true);
$store->expects('forget')->never();
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = Double::for(Container::class, override: true)->passthru(new Container);
@@ -1501,7 +1509,7 @@ public function testClearFlushesOverflowStoreWhenFlushOnClearEnabled(): void
$store = new Repository(new ArrayStore);
$store->put('foo', 'bar');
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = $this->createSpyContainer();
@@ -1534,16 +1542,16 @@ public function testClearFlushesOverflowStoreWhenFlushOnClearEnabled(): void
public function testClearFailsWhenTheOverflowStoreCannotBeFlushed(): void
{
- $store = Double::for(CacheStore::class);
+ $store = Double::for(CacheStore::class)->strict();
$store->expects('flush')->returns(false);
- $repository = Double::for(CacheRepository::class);
+ $repository = Double::for(CacheRepository::class)->strict();
$repository->expects('getStore')->returns($store);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($repository);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes);
$container->expects('make')->with('cache')->returns($cache);
@@ -1631,7 +1639,7 @@ public function testClearForwardsConfiguredStoreNameToFactory(): void
$store = new Repository(new ArrayStore);
$store->put('foo', 'bar');
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('redis')->returns($store);
$container = $this->createSpyContainer();
@@ -1680,7 +1688,8 @@ public function testMixedBulkRejectsPositiveFifoDelayBeforeTransactionLookupOrPa
{
$immediate = new FakeSqsJob;
$afterCommit = (new FakeSqsJob)->afterCommit()->delay(10);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
+ $container->allows('bound')->with('queue.routes')->returns(false);
$container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes);
$container->expects('has')->never();
@@ -1692,7 +1701,7 @@ public function testMixedBulkRejectsPositiveFifoDelayBeforeTransactionLookupOrPa
$queue->expects($this->never())->method('createPayload');
$this->expectException(LogicException::class);
-
+ $this->expectExceptionMessageIs('SQS FIFO queues do not support per-message delays.');
$queue->bulk([$immediate, $afterCommit], 'data', $this->fifoQueueName);
}
@@ -1761,7 +1770,7 @@ public function testBulkChunksWhenCumulativePayloadSizeExceedsLimit(): void
public function testBulkRaisesQueueingAndQueuedEventsForEachJob(): void
{
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->allows('hasListeners')->with(JobQueueing::class)->returns(true);
$events->allows('hasListeners')->with(JobQueued::class)->returns(true);
@@ -1966,7 +1975,7 @@ public static function defaultFifoQueueNames(): array
public function testBulkRaisesExactEventsForSuccessfulAndRejectedEntries(): void
{
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(true);
$events->allows('hasListeners')->with(JobQueueing::class)->returns(true);
$events->allows('hasListeners')->with(JobQueued::class)->returns(true);
@@ -2032,13 +2041,13 @@ public function testBulkCleansOnlyRejectedOverflowPointers(): void
$acceptedPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'accepted';
$rejectedPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'rejected';
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($acceptedPath, $firstPayload)->returns(true);
$store->expects('put')->with($rejectedPath, $secondPayload)->returns(true);
$store->expects('forget')->with($rejectedPath)->returns(true);
$store->expects('forget')->never()->with($acceptedPath);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = new Container;
@@ -2077,11 +2086,11 @@ public function testBulkRetainsOverflowPointersForServerFaultRejections(): void
$payload = json_encode(['uuid' => 'ambiguous'], JSON_THROW_ON_ERROR);
$path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'ambiguous';
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($path, $payload)->returns(true);
$store->expects('forget')->never();
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = new Container;
@@ -2120,16 +2129,16 @@ public function testBulkCleansEarlierWritesWhenAWriteFailsBeforeSending(): void
$firstPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'job-1';
$secondPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'job-2';
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($firstPath, $firstPayload)->ordered()->returns(true);
$store->expects('put')->with($secondPath, $secondPayload)->ordered()->returns(false);
$store->expects('forget')->with($firstPath)->ordered()->returns(true);
$store->expects('forget')->with($secondPath)->ordered()->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->allows('hasListeners')->with(JobQueueing::class)->returns(true);
$events->allows('hasListeners')->with(JobQueueingFailed::class)->returns(true);
@@ -2195,11 +2204,15 @@ public function testBulkPreservesWriteCancellationWhileDrainingAttemptedPointers
$cleanupCancellation = new RuntimeException('delete cleanup failed', previous: $cleanupCancellation);
}
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($cleanupCancellation)->times($deleteCleanupThrows ? 1 : 0);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ if ($deleteCleanupThrows) {
+ $handler->expects('report')->with(Argument::same($cleanupCancellation));
+ } else {
+ $handler->expects('report')->never();
+ }
Container::getInstance()->instance(ExceptionHandler::class, $handler);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($firstPath, $firstPayload)->ordered()->returns(true);
$store->expects('put')->with($secondPath, $secondPayload)->ordered()->throws($cancellation);
if ($deleteCleanupThrows === null) {
@@ -2209,10 +2222,10 @@ public function testBulkPreservesWriteCancellationWhileDrainingAttemptedPointers
}
$store->expects('forget')->with($secondPath)->ordered()->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->allows('hasListeners')->with(JobQueueing::class)->returns(true);
$events->expects('hasListeners')->with(JobQueueingFailed::class)->never();
@@ -2279,13 +2292,13 @@ public function testBulkCleanupCancellationSupersedesAnOrdinaryWriteFailure(bool
$cleanupCancellation = new RuntimeException('delete cleanup failed', previous: $cleanupCancellation);
}
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($firstPath, $firstPayload)->ordered()->returns(true);
$store->expects('put')->with($secondPath, $secondPayload)->ordered()->returns(false);
$store->expects('forget')->with($firstPath)->ordered()->throws($cleanupCancellation);
$store->expects('forget')->with($secondPath)->ordered()->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = new Container;
@@ -2328,14 +2341,14 @@ public function testBulkRetainsPointersAndPublishesCancellationInsteadOfFailureW
$cancellation = new RuntimeException('transport cleanup failed', previous: $cancellation);
}
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($path, $payload)->returns(true);
$store->expects('forget')->never();
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->allows('hasListeners')->with(JobQueueing::class)->returns(true);
$events->expects('hasListeners')->with(JobQueueingFailed::class)->never();
@@ -2392,7 +2405,7 @@ public function testBulkCleansOnlyTheCurrentChunkWhenItsOverflowWriteIsCanceled(
$currentPath = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'job-11';
$writes = 0;
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->times(11)->resolves(
function () use (&$writes, $cancellation): bool {
if (++$writes === 11) {
@@ -2404,7 +2417,7 @@ function () use (&$writes, $cancellation): bool {
);
$store->expects('forget')->with($currentPath)->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = new Container;
@@ -2442,14 +2455,14 @@ public function testBulkPreservesQueueingListenerCancellationBeforeWritingOverfl
$payload = json_encode(['uuid' => 'listener-canceled'], JSON_THROW_ON_ERROR);
$cancellation = new CanceledException;
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->never();
$store->expects('forget')->never();
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->expects('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->expects('hasListeners')->with(JobQueueing::class)->returns(true);
$events->expects('dispatch')->with(Argument::type(JobQueueing::class))->throws($cancellation);
@@ -2490,14 +2503,14 @@ public function testBulkPreservesQueueingListenerCancellationBeforeWritingOverfl
public function testBulkRetainsAmbiguousChunkPointersAndNeverWritesLaterChunks(): void
{
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->times(10)->returns(true);
$store->expects('forget')->never();
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->allows('hasListeners')->with(JobQueueing::class)->returns(true);
$events->allows('hasListeners')->with(JobQueueingFailed::class)->returns(true);
@@ -2616,7 +2629,7 @@ public function testBulkRegistersRollbackCallbacksForUniqueAfterCommitJobs(): vo
{
$job = new SqsQueueTestUniqueJob;
$job->afterCommit = true;
- DispatchLockContext::registerUnique($job, Double::for(CacheRepository::class), null, 'unique-key', 'owner');
+ DispatchLockContext::registerUnique($job, Double::for(CacheRepository::class)->strict(), null, 'unique-key', 'owner');
$transactions = Double::for(DatabaseTransactionsManager::class)->passthru(new DatabaseTransactionsManager);
$transactions->begin('default', 1);
@@ -2643,10 +2656,10 @@ public function testBulkComputesQueueableOptionsBeforeApplyingOverflow(): void
$path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . $this->mockedDeduplicationId;
$finalPayload = null;
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('put')->with($path, Argument::capture($finalPayload))->returns(true);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$dispatcher = new ConcreteEventDispatcher($container = new Container);
@@ -2688,7 +2701,7 @@ public function testBulkComputesQueueableOptionsBeforeApplyingOverflow(): void
public function testBulkFiresQueuedEventsForSuccessfulChunksWhenAnotherChunkFails(): void
{
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->allows('hasListeners')->with(JobPayloadFinalizing::class)->returns(false);
$events->allows('hasListeners')->with(JobQueueing::class)->returns(true);
$events->allows('hasListeners')->with(JobQueued::class)->returns(true);
@@ -2762,9 +2775,9 @@ public function testPopPassesOverflowStorageOptionsToJob(): void
$path = SqsQueue::EXTENDED_PAYLOAD_CACHE_PREFIX . 'popped-job';
$pointer = json_encode(['@pointer' => $path], JSON_THROW_ON_ERROR);
- $store = Double::for(CacheRepository::class);
+ $store = Double::for(CacheRepository::class)->strict();
$store->expects('get')->with($path)->returns($payload);
- $cache = Double::for(CacheFactory::class);
+ $cache = Double::for(CacheFactory::class)->strict();
$cache->expects('store')->with('database')->returns($store);
$container = Double::for(Container::class, override: true)->passthru(new Container);
$container->allows('make')->with(QueueRoutes::class)->returns(new QueueRoutes);
diff --git a/tests/Queue/QueueSyncQueueTest.php b/tests/Queue/QueueSyncQueueTest.php
index 07072a86fd..eebd7a8f50 100644
--- a/tests/Queue/QueueSyncQueueTest.php
+++ b/tests/Queue/QueueSyncQueueTest.php
@@ -139,7 +139,7 @@ public function testLifecycleEventsAreNotDispatchedWithoutListeners(): void
$sync = new SyncQueue;
$sync->setConnectionName('sync');
$container = $this->getContainer();
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->expects('hasListeners')->with(JobProcessing::class)->returns(false);
$events->expects('hasListeners')->with(JobProcessed::class)->returns(false);
$events->expects('hasListeners')->with(JobAttempted::class)->returns(false);
@@ -332,8 +332,8 @@ public function testCanceledAttemptListenerFailureIsReportedWithoutReplacingTheC
throw $listenerFailure;
});
$container->instance('events', $events);
- $handler = Double::for(ExceptionHandler::class);
- $handler->expects('report')->with($listenerFailure);
+ $handler = Double::for(ExceptionHandler::class)->strict();
+ $handler->expects('report')->with(Argument::same($listenerFailure));
$container->instance(ExceptionHandler::class, $handler);
$sync->setContainer($container);
@@ -351,7 +351,7 @@ public function testWrappedCancellationDuringFailureObservationSkipsFailureAndPu
$cleanupException = new RuntimeException('Failure observer cleanup failed.');
$jobFailure = new RuntimeException('Job failed.');
$gate = $this->armCurrentCoroutineCancellation();
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->allows('hasListeners')->with(JobProcessing::class)->returns(false);
$events->allows('hasListeners')->with(JobExceptionOccurred::class)->returns(true);
$events->allows('hasListeners')->with(JobAttempted::class)->returns(true);
@@ -369,7 +369,7 @@ public function testWrappedCancellationDuringFailureObservationSkipsFailureAndPu
));
$container = $this->getContainer();
$container->instance('events', $events);
- $job = Double::for(SyncJob::class);
+ $job = Double::for(SyncJob::class)->strict();
$job->expects('fire')->throws($jobFailure);
$job->expects('fail')->never();
$sync = Double::for(SyncQueue::class)->passthru(new SyncQueue);
@@ -394,10 +394,8 @@ public function testCancellationDuringSerializationIsNotWrapped(): void
CancelingSerializationJob::$gate = $this->armCurrentCoroutineCancellation();
try {
+ $this->expectException(CanceledException::class);
$sync->push(new CancelingSerializationJob);
- $this->fail('Expected cancellation to escape payload serialization.');
- } catch (CanceledException) {
- $this->addToAssertionCount(1);
} finally {
CancelingSerializationJob::$gate = null;
}
@@ -456,7 +454,7 @@ public function testItAddsATransactionCallbackForAfterCommitJobs(): void
$sync = new SyncQueue;
$sync->setConnectionName('sync');
$container = $this->getContainer();
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('addCallback')->returns(null);
$transactionManager->expects('addCallbackForRollback')->never();
@@ -471,7 +469,7 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitJobs()
$sync = new SyncQueue;
$sync->setConnectionName('sync');
$container = $this->getContainer();
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('addCallback')->returns(null);
$transactionManager->expects('addCallbackForRollback')->never();
@@ -486,7 +484,7 @@ public function testItAddsATransactionCallbackForAfterCommitUniqueJobs(): void
$sync = new SyncQueue;
$sync->setConnectionName('sync');
$container = $this->getContainer();
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('addCallback')->returns(null);
$transactionManager->expects('addCallbackForRollback')->returns(null);
@@ -504,7 +502,7 @@ public function testItAddsATransactionRollbackCallbackForAfterCommitDebouncedJob
$sync = new SyncQueue;
$sync->setConnectionName('sync');
$container = $this->getContainer();
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('addCallback')->returns(null);
$transactionManager->expects('addCallbackForRollback')->returns(null);
@@ -522,7 +520,7 @@ public function testItAddsATransactionCallbackForInterfaceBasedAfterCommitUnique
$sync = new SyncQueue;
$sync->setConnectionName('sync');
$container = $this->getContainer();
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('addCallback')->returns(null);
$transactionManager->expects('addCallbackForRollback')->returns(null);
@@ -540,7 +538,7 @@ public function testAfterCommitUniqueJobWithoutDispatchOwnershipDoesNotAddRollba
$sync = new SyncQueue;
$sync->setConnectionName('sync');
$container = $this->getContainer();
- $transactionManager = Double::for(DatabaseTransactionsManager::class);
+ $transactionManager = Double::for(DatabaseTransactionsManager::class)->strict();
$transactionManager->expects('hasApplicableTransaction')->with(null)->returns(true);
$transactionManager->expects('addCallback')->returns(null);
$transactionManager->expects('addCallbackForRollback')->never();
@@ -573,7 +571,7 @@ private function armCurrentCoroutineCancellation(): Channel
protected function getContainer(): Container
{
$container = new Container;
- $container->instance(Cache::class, Double::for(Cache::class));
+ $container->instance(Cache::class, Double::for(Cache::class)->strict());
$container->instance(EventDispatcher::class, new EventsDispatcher($container));
$container->instance(ContainerContract::class, $container);
Container::setInstance($container);
diff --git a/tests/Queue/QueueWorkerTest.php b/tests/Queue/QueueWorkerTest.php
index fad4c70c70..4885606c2e 100644
--- a/tests/Queue/QueueWorkerTest.php
+++ b/tests/Queue/QueueWorkerTest.php
@@ -360,7 +360,7 @@ public function testCancellationDuringFailureObservationStopsReleaseAndPublishes
public function testInvalidPayloadTerminatesBeforeProcessingAndIsReportedOnce(): void
{
$this->spyEvents();
- $this->exceptionHandler = Double::for(ExceptionHandlerContract::class);
+ $this->exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
$order = [];
$attemptedEvent = null;
$exception = new InvalidPayloadException('Invalid queue payload.', '{invalid');
@@ -378,7 +378,7 @@ function (object $event) use (&$order, &$attemptedEvent): void {
);
$this->exceptionHandler->expects('report')
->times(1)
- ->with($exception)
+ ->with(Argument::same($exception))
->resolves(function () use (&$order): void {
$order[] = 'reported';
});
@@ -553,6 +553,7 @@ public function testJobPoppingEvent(): void
public function testJobPopEventsAreSkippedWhenNoListenersAreRegistered(): void
{
$this->spyEvents();
+ $this->events->allows('dispatch');
$this->events->allows('hasListeners')->with(JobPopping::class)->returns(false);
$this->events->allows('hasListeners')->with(JobPopped::class)->returns(false);
@@ -673,6 +674,7 @@ public function testTimeoutMonitorUsesTheDefaultErrorExitAndTimedOutReason(?int
public function testNonKillingTimeoutUnwindsAndRetriesOnlyTheExpiredJob(bool $listenerThrows, bool $catchCancellation): void
{
$this->spyEvents();
+ $this->events->allows('dispatch');
Worker::$killOnTimeout = false;
Worker::$pausable = false;
$timer = new QueueWorkerTimer;
@@ -846,8 +848,8 @@ public function testNonKillingTimeoutHandlesCleanupAndReportingFailures(bool $re
$errorLog = null;
if ($reportingMode !== 'normal') {
$errorLog = $this->captureErrorLog();
- $this->exceptionHandler = Double::for(ExceptionHandlerContract::class);
- $report = $this->exceptionHandler->expects('report')->with($cleanupException);
+ $this->exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
+ $report = $this->exceptionHandler->expects('report')->with(Argument::same($cleanupException));
if ($reportingMode === 'cancellation') {
$report->resolves(function () use ($reportingFailure): never {
try {
@@ -866,11 +868,11 @@ public function testNonKillingTimeoutHandlesCleanupAndReportingFailures(bool $re
$command = new class {
use InteractsWithQueue;
};
- $limiter = Double::for(Limiter::class);
+ $limiter = Double::for(Limiter::class)->strict();
$limiter->expects('inspect')->with(Argument::type(Limit::class))->returns(new LimitResult(true, 10, 10, 0, 0));
$limiter->expects('consume')->never();
$limiter->expects('clear')->never();
- $rateLimiter = Double::for(RateLimiter::class, override: true);
+ $rateLimiter = Double::for(RateLimiter::class, override: true)->strict();
$rateLimiter->expects('store')->with(null)->returns($limiter);
$this->container->instance(RateLimiter::class, $rateLimiter->instance());
$job = Double::for(WorkerFakeJob::class)->passthru(new WorkerFakeJob(static function () use ($command, $gate, $cleanupException): void {
@@ -1028,6 +1030,7 @@ public function testNonKillingTimeoutDoesNotInterruptPostExecutionListeners(bool
public function testTimeoutScanDoesNotCancelCompletedCleanupOrTimeoutAnotherFinishedJob(): void
{
$this->spyEvents();
+ $this->events->allows('dispatch');
Worker::$killOnTimeout = false;
$timer = new QueueWorkerTimer;
$firstGate = new Channel(1);
@@ -1051,14 +1054,14 @@ public function testTimeoutScanDoesNotCancelCompletedCleanupOrTimeoutAnotherFini
$worker->currentTime = 100;
$options = new WorkerOptions;
$worker->startMonitorForTest($options);
- $interruptible = Double::for(Interruptible::class);
+ $interruptible = Double::for(Interruptible::class)->strict();
$interruptible->expects('interrupted')->with(SIGALRM)->resolves(
static function () use ($firstGate, $secondGate): void {
$firstGate->push(true);
$secondGate->push(true);
}
);
- $handler = Double::for(CallQueuedHandler::class);
+ $handler = Double::for(CallQueuedHandler::class)->strict();
$handler->expects('getRunningCommand')->returns($interruptible);
$first->resolvedJob = $handler;
$coroutines = [];
@@ -1106,7 +1109,7 @@ public function testTimeoutMonitorRunsInAnOwnedCoroutineWithWorkerContextAndStop
$callbackCoroutineIds = [];
$contextValues = [];
$completed = new Channel(1);
- $logger = Double::for(LoggerInterface::class);
+ $logger = Double::for(LoggerInterface::class)->strict();
$logger->expects('error')->times(1)->resolves(
static fn (string $message): bool => $completed->push($message),
);
@@ -1193,8 +1196,8 @@ public function testTimeoutHandlingErrorsDoNotAbandonOtherAttempts(string $failu
$errorLog = null;
if ($reportingThrows) {
$errorLog = $this->captureErrorLog();
- $this->exceptionHandler = Double::for(ExceptionHandlerContract::class);
- $this->exceptionHandler->expects('report')->with($error)->throws(new RuntimeException('Reporting failed.'));
+ $this->exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
+ $this->exceptionHandler->expects('report')->with(Argument::same($error))->throws(new RuntimeException('Reporting failed.'));
}
$timer = new QueueWorkerTimer;
$worker = new KillTestWorker(...$this->workerDependencies(timer: $timer));
@@ -1294,18 +1297,19 @@ public function testTimeoutMonitorUsesTheConfiguredExitCode(): void
public function testDaemonClearsItsMonitorWhenTheLoopThrows(): void
{
$timer = new QueueWorkerTimer;
+ $failure = new LoopBreakerException;
$worker = $this->getWorker(
'default',
['queue' => []],
- static fn (): never => throw new LoopBreakerException,
+ static fn (): never => throw $failure,
$timer,
);
try {
$worker->daemon('default', 'queue', new WorkerOptions);
$this->fail('Expected the daemon loop to fail.');
- } catch (LoopBreakerException) {
- $this->addToAssertionCount(1);
+ } catch (LoopBreakerException $exception) {
+ $this->assertSame($failure, $exception);
}
$this->assertSame([1], $timer->registered);
@@ -1704,7 +1708,7 @@ protected function currentMemoryUsage(): float
public function testDaemonShouldRunSkipsLoopingEventWhenNoListenersAreRegistered(): void
{
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->expects('hasListeners')->times(1)->with(Looping::class)->returns(false);
$events->expects('until')->never();
@@ -1721,7 +1725,7 @@ public function testDaemonShouldRunSkipsLoopingEventWhenNoListenersAreRegistered
public function testLoopingEventCarriesWorkerOptions(): void
{
$options = new WorkerOptions;
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->expects('hasListeners')->times(1)->with(Looping::class)->returns(true);
$events->expects('until')->times(1)->with(Argument::satisfies(
static fn (object $event): bool => $event instanceof Looping
@@ -1742,7 +1746,7 @@ public function testLoopingEventCarriesWorkerOptions(): void
public function testForcedWorkerDoesNotCheckMaintenanceMode(): void
{
- $events = Double::for(EventDispatcher::class);
+ $events = Double::for(EventDispatcher::class)->strict();
$events->expects('hasListeners')->times(1)->with(Looping::class)->returns(false);
$worker = new LoopAwareWorker(
@@ -1759,7 +1763,7 @@ public function testQueuePauseEventsTrackOnlyTheCurrentSelection(): void
{
$this->spyEvents();
$paused = ['emails'];
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->allows('connection')->with('first')->returns(
new WorkerFakeConnection('first', ['emails' => [], 'default' => []]),
);
@@ -1774,7 +1778,7 @@ static function (array $queues, string $connection) use (&$paused): array {
},
);
$worker = new InsomniacWorker($manager, $this->events, $this->exceptionHandler, static fn (): bool => false);
- $worker->setCache(Double::for(CacheContract::class));
+ $worker->setCache(Double::for(CacheContract::class)->strict());
$options = new WorkerOptions(sleep: 0);
$observed = [];
$this->events->allows('dispatch')->resolves(function (object $event) use (&$observed): void {
@@ -1808,7 +1812,7 @@ static function (array $queues, string $connection) use (&$paused): array {
public function testPauseHistoryIsRetainedWithoutEventListeners(): void
{
$this->spyEvents();
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->allows('connection')->with('default')->returns(
new WorkerFakeConnection('default', ['queue' => []]),
);
@@ -1824,7 +1828,7 @@ static function (string $event) use (&$listening): bool {
},
);
$worker = new InsomniacWorker($manager, $this->events, $this->exceptionHandler, static fn (): bool => false);
- $worker->setCache(Double::for(CacheContract::class));
+ $worker->setCache(Double::for(CacheContract::class)->strict());
$worker->runNextJob('default', 'queue', new WorkerOptions(sleep: 0));
$this->assertSame([], $dispatched);
@@ -1841,12 +1845,12 @@ static function (string $event) use (&$listening): bool {
public function testEachDaemonRunReportsInitiallyPausedQueues(): void
{
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->allows('connection')->with('default')->returns(
new WorkerFakeConnection('default', ['queue' => []]),
);
$manager->allows('getPausedQueues')->with(['queue'], 'default')->returns(['queue']);
- $cache = Double::for(CacheContract::class);
+ $cache = Double::for(CacheContract::class)->strict();
$cache->allows('get')->with(Worker::RESTART_SIGNAL_CACHE_KEY)->returns(null);
$worker = new InsomniacWorker($manager, $this->events, $this->exceptionHandler, static fn (): bool => false);
$worker->setCache($cache);
@@ -1911,8 +1915,8 @@ public function testExceptionIsReportedIfConnectionThrowsExceptionOnJobPop(bool
$e = new RuntimeException('Pop failed.');
if ($reportingThrows) {
$this->captureErrorLog();
- $this->exceptionHandler = Double::for(ExceptionHandlerContract::class);
- $this->exceptionHandler->expects('report')->with($e)->throws(new RuntimeException('Reporting failed.'));
+ $this->exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
+ $this->exceptionHandler->expects('report')->with(Argument::same($e))->throws(new RuntimeException('Reporting failed.'));
}
$worker = new InsomniacWorker(
new WorkerFakeManager('default', new BrokenQueueConnection('default', $e)),
@@ -2053,7 +2057,7 @@ public function testReleasedAttemptReportsItsErrorWithoutAnotherOutcome(string $
};
if ($scenario === 'do not retry') {
$this->exceptionHandler = Double::for(ShouldntRetryExceptionHandler::class)->passthru(new ShouldntRetryExceptionHandler);
- $this->exceptionHandler->expects('report')->with($exception);
+ $this->exceptionHandler->expects('report')->with(Argument::same($exception));
$this->exceptionHandler->expects('shouldStopRetries')->never();
}
$worker = $this->getWorker('default', ['queue' => [$job]]);
@@ -2444,7 +2448,7 @@ public function testTimeoutPoliciesWaitForTheInterruptionHandlerOutcome(bool $bo
$job->expects($outcome === 'release' ? 'delete' : 'release')->never();
$job->shouldFailOnTimeout = true;
$job->maxExceptions = 2;
- $interruptible = Double::for(Interruptible::class);
+ $interruptible = Double::for(Interruptible::class)->strict();
$interruptible->expects('interrupted')->with(SIGALRM)->resolves(
static function () use ($notificationGate, &$notificationStarted, $job, $outcome): void {
$notificationStarted = true;
@@ -2452,7 +2456,7 @@ static function () use ($notificationGate, &$notificationStarted, $job, $outcome
$job->{$outcome}();
}
);
- $handler = Double::for(CallQueuedHandler::class);
+ $handler = Double::for(CallQueuedHandler::class)->strict();
$handler->expects('getRunningCommand')->returns($interruptible);
$job->resolvedJob = $handler;
$worker = new KillTestWorker(...$this->workerDependencies('default', ['queue' => [$job]], timer: $timer));
@@ -2557,9 +2561,9 @@ public function testInterruptedReleaseSerializesMarkerCleanupWithTheFinishingBod
}
$releaseStarted->push(true);
}, 5));
- $interruptible = Double::for(Interruptible::class);
+ $interruptible = Double::for(Interruptible::class)->strict();
$interruptible->expects('interrupted')->with(SIGALRM)->resolves(static fn (): mixed => $first->release());
- $handler = Double::for(CallQueuedHandler::class);
+ $handler = Double::for(CallQueuedHandler::class)->strict();
$handler->expects('getRunningCommand')->returns($interruptible);
$first->allows('getResolvedJob')->returns($handler);
$first->onReleased = static function () use (&$handedOff, &$coroutines, &$failures, $worker, $next): void {
@@ -2669,7 +2673,7 @@ public function testJobIsFailedWhenTheMaxExceptionsCounterReachesTheLimit(): voi
$exception = new RuntimeException('Job failed.');
$job = new WorkerFakeJob;
$job->maxExceptions = 3;
- $cache = Double::for(CacheContract::class);
+ $cache = Double::for(CacheContract::class)->strict();
$cache->expects('get')->with('job-exceptions:' . $job->uuid)->returns(true);
$cache->expects('increment')->with('job-exceptions:' . $job->uuid)->returns(3);
$cache->expects('forget')->with('job-exceptions:' . $job->uuid)->returns(true);
@@ -2686,7 +2690,7 @@ public function testBooleanMaxExceptionsCounterResultsDoNotFailTheJob(): void
$exception = new RuntimeException('Job failed.');
$job = new WorkerFakeJob;
$job->maxExceptions = 0;
- $cache = Double::for(CacheContract::class);
+ $cache = Double::for(CacheContract::class)->strict();
$cache->expects('get')->with('job-exceptions:' . $job->uuid)->returns(true);
$cache->expects('increment')->with('job-exceptions:' . $job->uuid)->returns($counterResult);
$cache->expects('forget')->never();
@@ -2907,8 +2911,8 @@ public function testStoppingListenerFailureCannotPreventTheKillCallbackOrTermina
$failure = new RuntimeException('The stopping listener failed.');
$this->spyEvents();
$this->events->expects('dispatch')->times(1)->with(Argument::type(WorkerStopping::class))->throws($failure);
- $this->exceptionHandler = Double::for(ExceptionHandlerContract::class);
- $report = $this->exceptionHandler->expects('report')->times(1)->with($failure);
+ $this->exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
+ $report = $this->exceptionHandler->expects('report')->times(1)->with(Argument::same($failure));
if ($reportingThrows) {
$this->captureErrorLog();
$report->throws(new RuntimeException('Reporting failed.'));
@@ -2996,8 +3000,8 @@ public function testWorkerStopsWithLostConnectionReason(Throwable $failure, bool
{
if ($reportingThrows) {
$this->captureErrorLog();
- $this->exceptionHandler = Double::for(ExceptionHandlerContract::class);
- $this->exceptionHandler->expects('report')->with($failure)->throws(new RuntimeException('Reporting failed.'));
+ $this->exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
+ $this->exceptionHandler->expects('report')->with(Argument::same($failure))->throws(new RuntimeException('Reporting failed.'));
}
$workerOptions = new WorkerOptions(stopWhenEmpty: true);
$worker = $this->getWorker('default', ['queue' => [
@@ -3144,7 +3148,7 @@ public function interrupted(int $signal): void
}
};
- $handler = Double::for(CallQueuedHandler::class);
+ $handler = Double::for(CallQueuedHandler::class)->strict();
$handler->expects('getRunningCommand')->returns($interruptible);
$job = new WorkerFakeJob;
@@ -3197,7 +3201,7 @@ public function interrupted(int $signal): void
$this->releaseJob->push(true);
}
};
- $handler = Double::for(CallQueuedHandler::class);
+ $handler = Double::for(CallQueuedHandler::class)->strict();
$handler->expects('getRunningCommand')->returns($interruptible);
$job = new WorkerFakeJob(function () use (&$worker, $options, $releaseJob): void {
$worker->handleInterruptionSignalForTest(SIGTERM, 'default', 'queue', $options);
@@ -3503,7 +3507,7 @@ private function captureErrorLog(): string
*/
private function spyEvents(): void
{
- $this->events = Double::for(EventDispatcher::class);
+ $this->events = Double::for(EventDispatcher::class)->strict();
$this->events->allows('hasListeners')->returns(true);
}
@@ -3562,7 +3566,7 @@ private function registerRunningJob(InsomniacWorker $worker, Job $job, WorkerOpt
private function workerJobWithRunningCommand(object $command): WorkerFakeJob
{
- $handler = Double::for(CallQueuedHandler::class);
+ $handler = Double::for(CallQueuedHandler::class)->strict();
$handler->expects('getRunningCommand')->returns($command);
$job = new WorkerFakeJob;
diff --git a/tests/Queue/RelayCommandTest.php b/tests/Queue/RelayCommandTest.php
index 507b650c35..9837af2fd3 100644
--- a/tests/Queue/RelayCommandTest.php
+++ b/tests/Queue/RelayCommandTest.php
@@ -21,20 +21,16 @@ class RelayCommandTest extends TestCase
public function testCommandPassesThePinnedSourceAndTypedOptionsToTheWorker(): void
{
$worker = Double::for(OutboxWorker::class)->strict();
- $worker->expects('run')->with('orders', Argument::satisfies(function (OutboxWorkerOptions $options): bool {
- $this->assertEquals(new OutboxWorkerOptions(
- batch: 50,
- sleep: 0.25,
- concurrency: 4,
- maxJobs: 500,
- maxTime: 60,
- memory: 256,
- stopWhenEmpty: true,
- once: true,
- ), $options);
-
- return true;
- }))->returns(12);
+ $worker->expects('run')->with('orders', new OutboxWorkerOptions(
+ batch: 50,
+ sleep: 0.25,
+ concurrency: 4,
+ maxJobs: 500,
+ maxTime: 60,
+ memory: 256,
+ stopWhenEmpty: true,
+ once: true,
+ ))->returns(12);
$this->app->instance(OutboxWorker::class, $worker);
$this->assertSame(12, Artisan::call('queue:relay', [
@@ -53,7 +49,7 @@ public function testCommandPassesThePinnedSourceAndTypedOptionsToTheWorker(): vo
public function testCommandDefaultsToAllConfiguredSources(): void
{
$worker = Double::for(OutboxWorker::class)->strict();
- $worker->expects('run')->with(null, Argument::satisfies(fn (OutboxWorkerOptions $options): bool => $options == new OutboxWorkerOptions))->returns(0);
+ $worker->expects('run')->with(null, new OutboxWorkerOptions)->returns(0);
$this->app->instance(OutboxWorker::class, $worker);
$this->assertSame(0, Artisan::call('queue:relay'));
diff --git a/tests/Queue/RetryBatchCommandTest.php b/tests/Queue/RetryBatchCommandTest.php
index dd4e4beff4..1955c1eec9 100644
--- a/tests/Queue/RetryBatchCommandTest.php
+++ b/tests/Queue/RetryBatchCommandTest.php
@@ -26,7 +26,7 @@ class RetryBatchCommandTest extends TestCase
#[TestWith(['0'])]
public function testItFailsWhenTheBatchCannotBeFound(string $id): void
{
- $repo = Double::for(BatchRepository::class);
+ $repo = Double::for(BatchRepository::class)->strict();
$repo->expects('find')->with($id)->returns(null);
$this->app->instance(BatchRepository::class, $repo);
@@ -45,8 +45,8 @@ public function testItFailsWhenTheBatchCannotBeFound(string $id): void
public function testItFailsWhenTheBatchHasNoFailedJobs(): void
{
$batch = new Batch(
- Double::for(QueueFactory::class),
- Double::for(BatchRepository::class),
+ Double::for(QueueFactory::class)->strict(),
+ Double::for(BatchRepository::class)->strict(),
'empty-batch',
'Empty Batch',
0,
@@ -57,7 +57,7 @@ public function testItFailsWhenTheBatchHasNoFailedJobs(): void
CarbonImmutable::now(),
);
- $repo = Double::for(BatchRepository::class);
+ $repo = Double::for(BatchRepository::class)->strict();
$repo->expects('find')->with('empty-batch')->returns($batch);
$this->app->instance(BatchRepository::class, $repo);
@@ -79,12 +79,12 @@ public function testItFailsWhenTheBatchHasNoFailedJobs(): void
public function testItCanBeRunInIsolation(): void
{
- $repo = Double::for(BatchRepository::class);
+ $repo = Double::for(BatchRepository::class)->strict();
$repo->expects('find')->with('batch-id')->returns(null);
$this->app->instance(BatchRepository::class, $repo);
- $mutex = Double::for(CommandMutex::class);
+ $mutex = Double::for(CommandMutex::class)->strict();
$mutex->expects('create')->returns(true);
$mutex->expects('forget')->returns(true);
diff --git a/tests/Queue/SqsBatchLifecycleTest.php b/tests/Queue/SqsBatchLifecycleTest.php
index b36148df19..1cb21f4d0b 100644
--- a/tests/Queue/SqsBatchLifecycleTest.php
+++ b/tests/Queue/SqsBatchLifecycleTest.php
@@ -100,7 +100,7 @@ public function testCustomBulkDispatchRetainsTheAcceptedUniqueLock(bool $afterCo
#[TestWith([JobQueueing::class])]
public function testPreparationFailureTerminatesEveryOutstandingMember(string $eventClass): void
{
- [$queue, $transport, $events] = $this->queue();
+ [$queue, , $events] = $this->queue();
$exception = new RuntimeException('Second member failed.');
$count = 0;
$events->listen($eventClass, static function () use (&$count, $exception): void {
@@ -120,7 +120,6 @@ public function testPreparationFailureTerminatesEveryOutstandingMember(string $e
$this->assertSame($exception, $caught);
}
- $this->assertNull($transport->getLastCommand());
$this->assertSame(['first', 'second', 'third'], array_column($failed, 'job'));
$this->assertSame([$exception, $exception, $exception], array_column($failed, 'exception'));
}
@@ -129,7 +128,7 @@ public function testPreparationFailureTerminatesEveryOutstandingMember(string $e
#[TestWith([JobQueueing::class])]
public function testPreparationCancellationNotifiesOutstandingMembersOfTheCancellation(string $eventClass): void
{
- [$queue, $transport, $events] = $this->queue();
+ [$queue, , $events] = $this->queue();
$cleanup = new RuntimeException('Preparation cleanup failed.');
$gate = $this->armCurrentCoroutineCancellation();
$events->listen($eventClass, static function () use ($gate, $cleanup): never {
@@ -157,7 +156,6 @@ public function testPreparationCancellationNotifiesOutstandingMembersOfTheCancel
$gate->close();
}
- $this->assertNull($transport->getLastCommand());
$this->assertSame([], $failed);
$this->assertSame(['first', 'second'], array_column($canceled, 'job'));
$this->assertSame([$cleanup, $cleanup], array_column($canceled, 'cancellation'));
@@ -176,7 +174,7 @@ public function testFailureNotificationsDrainAndRetainThePrimaryAttemptError():
});
$events->listen(JobQueueingFailed::class, static fn () => throw $listener);
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($listener);
+ $handler->expects('report')->with(Argument::same($listener));
$container->instance(ExceptionHandler::class, $handler);
try {
@@ -229,7 +227,7 @@ public function testNotificationCancellationStillNotifiesLaterMembersAndReportsT
$canceled[] = $event;
});
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($listenerFailure);
+ $handler->expects('report')->with(Argument::same($listenerFailure));
$container->instance(ExceptionHandler::class, $handler);
try {
@@ -282,7 +280,7 @@ public function testSuccessListenerFailurePreservesAcceptedEntriesAndCleansExpli
}
});
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($listener);
+ $handler->expects('report')->with(Argument::same($listener));
if ($failureListenerCanceled) {
$handler->expects('report')->with(Argument::type(SqsException::class));
}
@@ -354,7 +352,7 @@ public function testCancellationDuringReportingStillNotifiesEveryMemberAndReport
$gate = $this->armCurrentCoroutineCancellation();
$cleanup = new RuntimeException('Reporting cleanup failed.');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($reportedFailure)->resolves(static function () use ($gate, $cleanup, $cleanupThrows): void {
+ $handler->expects('report')->with(Argument::same($reportedFailure))->resolves(static function () use ($gate, $cleanup, $cleanupThrows): void {
try {
$gate->push(true);
} finally {
diff --git a/tests/RateLimiter/DatabaseStoreTest.php b/tests/RateLimiter/DatabaseStoreTest.php
index 42a4b1819b..8f46d3286d 100644
--- a/tests/RateLimiter/DatabaseStoreTest.php
+++ b/tests/RateLimiter/DatabaseStoreTest.php
@@ -317,14 +317,14 @@ public function testSqliteMutationInsertsBeforeReadingTheLockedState(): void
});
$update->expects('where')->with('key', 'physical-key');
$update->expects('update')
- ->with(Argument::satisfies(static function (array $state) use (&$operations): bool {
+ ->with(Argument::satisfies(static fn (array $state): bool => $state['value'] === 1
+ && $state['secondary_value'] === 0
+ && $state['expires_at'] > 60_000_000))
+ ->resolves(static function () use (&$operations): int {
$operations[] = 'update';
- return $state['value'] === 1
- && $state['secondary_value'] === 0
- && $state['expires_at'] > 60_000_000;
- }))
- ->returns(1);
+ return 1;
+ });
$result = (new DatabaseStore($connections, 'limiter', 'custom_rate_limits'))
->consume('physical-key', Limit::perMinute(10));
diff --git a/tests/RateLimiter/RateLimiterServiceProviderTest.php b/tests/RateLimiter/RateLimiterServiceProviderTest.php
index e2d5d56f03..b77d61ecf2 100644
--- a/tests/RateLimiter/RateLimiterServiceProviderTest.php
+++ b/tests/RateLimiter/RateLimiterServiceProviderTest.php
@@ -15,6 +15,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use Swoole\Server as SwooleServer;
class RateLimiterServiceProviderTest extends TestCase
@@ -47,8 +48,8 @@ public function testLifecycleListenersAreResolvedAtEventTime(): void
$beforeServerStart = new BeforeServerStart('server');
$server = Double::for(SwooleServer::class)->strict();
$afterWorkerStart = new AfterWorkerStart($server, 0);
- $tables->expects('handle')->with($beforeServerStart);
- $timers->expects('handle')->with($afterWorkerStart);
+ $tables->expects('handle')->with(Argument::same($beforeServerStart));
+ $timers->expects('handle')->with(Argument::same($afterWorkerStart));
(new RateLimiterServiceProvider($application->instance()))->boot();
diff --git a/tests/RateLimiter/SwooleStoreTest.php b/tests/RateLimiter/SwooleStoreTest.php
index 0bfed648a8..16474b7e6b 100644
--- a/tests/RateLimiter/SwooleStoreTest.php
+++ b/tests/RateLimiter/SwooleStoreTest.php
@@ -31,9 +31,9 @@
class SwooleStoreTest extends TestCase
{
- use VerifiesDoubles;
use InteractsWithSwooleTables;
use RateLimiterStoreContract;
+ use VerifiesDoubles;
public function testFixedWindowOperationsUseNumericState(): void
{
diff --git a/tests/Redis/ConcurrencyLimiterTest.php b/tests/Redis/ConcurrencyLimiterTest.php
index c4c20b3b5e..44e32f1b87 100644
--- a/tests/Redis/ConcurrencyLimiterTest.php
+++ b/tests/Redis/ConcurrencyLimiterTest.php
@@ -136,7 +136,7 @@ public function testBlockPreservesCallbackFailureWhenReleaseAlsoFails(string $ki
public function testBlockThrowsTimeoutExceptionWhenCannotAcquire(): void
{
$redis = $this->mockRedis();
- $connection = Double::for(RedisConnection::class);
+ $connection = Double::for(RedisConnection::class)->strict();
// acquire() always fails (returns falsy)
$redis->allows('withConnection')
@@ -157,7 +157,7 @@ public function testBlockCanAcquireAtTheDeadlineWithAShorterFinalSleep(): void
Sleep::fake(syncWithCarbon: true);
CarbonImmutable::setTestNow(CarbonImmutable::now());
$redis = $this->mockRedis();
- $connection = Double::for(RedisConnection::class);
+ $connection = Double::for(RedisConnection::class)->strict();
$redis->allows('withConnection')
->resolves(fn (callable $callback): mixed => $callback($connection));
$connection->expects('evalWithShaCache')->times(4)
@@ -255,8 +255,7 @@ public function testLeaseReturnsRemainingLifetime(): void
public function testAcquireUsesHashTagsOnPhpRedisClusterConnection(): void
{
- $redis = $this->mockRedis();
- $redis->expects('isCluster')->returns(true);
+ $redis = $this->mockRedis(cluster: true);
$this->expectSlotClaim(
$redis,
@@ -280,7 +279,6 @@ function (string $script, array $keys, array $arguments): bool {
public function testAcquireUsesPlainKeysOnNonClusterConnection(): void
{
$redis = $this->mockRedis();
- $redis->expects('isCluster')->returns(false);
$this->expectSlotClaim(
$redis,
@@ -306,8 +304,7 @@ function (string $script, array $keys, array $arguments): bool {
public function testReleaseKeyMatchesAcquireKeyOnCluster(): void
{
- $redis = $this->mockRedis();
- $redis->expects('isCluster')->returns(true);
+ $redis = $this->mockRedis(cluster: true);
// Acquire returns the slot key.
$this->expectSlotClaim($redis, '{mykey}2');
@@ -323,8 +320,7 @@ public function testReleaseKeyMatchesAcquireKeyOnCluster(): void
#[DataProvider('existingHashTags')]
public function testAcquireDoesNotDoubleWrapPreExistingHashTags(string $name): void
{
- $redis = $this->mockRedis();
- $redis->expects('isCluster')->returns(true);
+ $redis = $this->mockRedis(cluster: true);
// The name already has a hash tag and must not be double-wrapped.
$this->expectSlotClaim($redis, $name . '1', function (string $script, array $keys, array $arguments) use ($name): bool {
@@ -351,8 +347,7 @@ public static function existingHashTags(): array
public function testAcquireWrapsUnmatchedBraceOnCluster(): void
{
- $redis = $this->mockRedis();
- $redis->expects('isCluster')->returns(true);
+ $redis = $this->mockRedis(cluster: true);
// An opening brace without a closing brace is not a valid hash tag.
$this->expectSlotClaim($redis, '{my{lock}1', function (string $script, array $keys, array $arguments): bool {
@@ -371,8 +366,7 @@ public function testAcquireWrapsUnmatchedBraceOnCluster(): void
public function testAcquireWrapsEmptyBracesOnCluster(): void
{
- $redis = $this->mockRedis();
- $redis->expects('isCluster')->returns(true);
+ $redis = $this->mockRedis(cluster: true);
// Empty braces are not a valid hash tag.
$this->expectSlotClaim($redis, '{my{}lock}1', function (string $script, array $keys, array $arguments): bool {
@@ -392,9 +386,12 @@ public function testAcquireWrapsEmptyBracesOnCluster(): void
/**
* Create a mock RedisProxy.
*/
- private function mockRedis(): ConcurrencyLimiterRedisProxy
+ private function mockRedis(bool $cluster = false): ConcurrencyLimiterRedisProxy
{
- return Double::for(ConcurrencyLimiterRedisProxy::class);
+ $redis = Double::for(ConcurrencyLimiterRedisProxy::class)->strict();
+ $redis->expects('isCluster')->returns($cluster);
+
+ return $redis;
}
/**
@@ -405,7 +402,7 @@ private function expectSlotClaim(
false|string $result,
?callable $assertion = null,
): void {
- $connection = Double::for(RedisConnection::class);
+ $connection = Double::for(RedisConnection::class)->strict();
$redis->expects('withConnection')
->resolves(fn (callable $callback): mixed => $callback($connection));
diff --git a/tests/Redis/Operations/FlushByPatternTest.php b/tests/Redis/Operations/FlushByPatternTest.php
index 4551682cad..519e349314 100644
--- a/tests/Redis/Operations/FlushByPatternTest.php
+++ b/tests/Redis/Operations/FlushByPatternTest.php
@@ -246,7 +246,7 @@ class FlushingRedisClient extends FakeRedisClient
public ?Closure $unlinkCallback = null;
/**
- * Record deletion batches while retaining the real scan cursor updates.
+ * Record each deletion batch.
*/
public function unlink(array|string $key, string ...$other_keys): Redis|int|false
{
diff --git a/tests/Redis/PhpRedisClusterConnectionTest.php b/tests/Redis/PhpRedisClusterConnectionTest.php
index 34f6563574..e77441fba1 100644
--- a/tests/Redis/PhpRedisClusterConnectionTest.php
+++ b/tests/Redis/PhpRedisClusterConnectionTest.php
@@ -99,7 +99,7 @@ public function testTransformFiresInAtomicMode(): void
$connection = new PhpRedisClusterConnectionStub;
// In atomic mode, isQueueingMode() returns false, so transforms fire
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('setNx')
->with('key', 'value')
@@ -119,7 +119,7 @@ public function testTransformSkippedInMultiMode(): void
// In multi mode, isQueueingMode() returns true, so transforms are skipped
// and the raw command is forwarded directly to the client
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::MULTI);
$client->expects('setnx')
->with('key', 'value')
@@ -186,7 +186,7 @@ public function testItFlushesAllMasterNodesAsync(): void
public function testFlushdbAttemptsEveryMasterAndAggregatesFailures(): void
{
$masters = [['127.0.0.1', 6379], ['127.0.0.1', 6380], ['127.0.0.1', 6381]];
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('_masters')->returns($masters);
$client->expects('flushdb')->with($masters[0])->returns(true);
@@ -460,7 +460,7 @@ public function testItContinuesWithAnotherMasterWhenTheCurrentMasterDisappears()
public function testInfoTransformIncludesTheDefaultNodeAndSections(): void
{
$defaultNode = ['127.0.0.1', 6379];
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('_masters')->returns([$defaultNode]);
$client->expects('info')
@@ -480,7 +480,7 @@ public function testInfoTransformIncludesTheDefaultNodeAndSections(): void
public function testInfoTransformSupportsAnUnfilteredRequest(): void
{
$defaultNode = ['127.0.0.1', 6379];
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('_masters')->returns([$defaultNode]);
$client->expects('info')
@@ -500,7 +500,7 @@ public function testInfoTransformSupportsAnUnfilteredRequest(): void
public function testPingTransformRoutesToTheDefaultNode(): void
{
$defaultNode = ['127.0.0.1', 6379];
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('_masters')->returns([$defaultNode]);
$client->expects('ping')->with($defaultNode)->returns(true);
@@ -516,7 +516,7 @@ public function testPingTransformRoutesToTheDefaultNode(): void
public function testExecuteRawRoutesByTheFirstArgumentAndNormalizesNullReplies(): void
{
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('rawCommand')
->with('{user}:1', 'GET', '{user}:1')
@@ -531,7 +531,7 @@ public function testExecuteRawRoutesByTheFirstArgumentAndNormalizesNullReplies()
public function testExecuteRawRoutesByTheFirstArgumentWhileQueueing(): void
{
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->expects('getMode')->returns(Redis::MULTI);
$client->expects('rawCommand')
->with('{user}:1', 'GET', '{user}:1')
@@ -550,7 +550,7 @@ public function testExecuteRawRoutesByTheFirstArgumentWhileQueueing(): void
public function testExecuteRawRoutesKeylessCommandsToTheDefaultNode(): void
{
$defaultNode = ['127.0.0.1', 6379];
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('_masters')->returns([$defaultNode]);
$client->expects('rawCommand')
@@ -802,7 +802,7 @@ public function setOptionsForTest(RedisCluster $redis): void
$this->setOptions($redis);
}
};
- $redis = Double::for(RedisCluster::class);
+ $redis = Double::for(RedisCluster::class)->strict();
$redis->expects('setOption')
->with(RedisCluster::OPT_SLAVE_FAILOVER, RedisCluster::FAILOVER_DISTRIBUTE)
->returns(true);
@@ -826,7 +826,7 @@ public function setOptionsForTest(RedisCluster $redis): void
$this->setOptions($redis);
}
};
- $redis = Double::for(RedisCluster::class);
+ $redis = Double::for(RedisCluster::class)->strict();
$this->expectDefaultConnectionOptions($redis);
$this->expectExceptionObject(new InvalidRedisOptionException(
@@ -860,7 +860,7 @@ public function setOptionsForTest(RedisCluster $redis): void
$this->setOptions($redis);
}
};
- $redis = Double::for(RedisCluster::class);
+ $redis = Double::for(RedisCluster::class)->strict();
$this->expectDefaultConnectionOptions($redis);
$connection->setOptionsForTest($redis);
@@ -927,7 +927,7 @@ public function formatClusterPasswordForTest(): mixed
public function testDefaultNodeIsCached(): void
{
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('_masters')
->returns([['127.0.0.1', 6379]]);
@@ -946,7 +946,7 @@ public function testDefaultNodeIsCached(): void
public function testDefaultNodeThrowsWhenNoMasters(): void
{
- $client = Double::for(RedisCluster::class);
+ $client = Double::for(RedisCluster::class)->strict();
$client->allows('getMode')->returns(Redis::ATOMIC);
$client->expects('_masters')
->returns([]);
@@ -964,8 +964,8 @@ public function testDefaultNodeThrowsWhenNoMasters(): void
public function testConnectionRebuildsItsClientOnNextAcquisitionWithoutReplayingCommand(): void
{
$exception = new RedisException('Connection lost');
- $failedClient = Double::for(RedisCluster::class);
- $healthyClient = Double::for(RedisCluster::class);
+ $failedClient = Double::for(RedisCluster::class)->strict();
+ $healthyClient = Double::for(RedisCluster::class)->strict();
$this->expectDefaultConnectionOptions($failedClient);
$this->expectDefaultConnectionOptions($healthyClient);
$failedClient->expects('get')->with('foo')->throws($exception);
@@ -1013,22 +1013,22 @@ protected function createRedisCluster(): RedisCluster
public function testReconnectClearsCachedDefaultNode(): void
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('getOptions')->returns(PoolOptions::fromArray([]));
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->allows('has')->returns(false);
$container->allows('bound')->with('events')->returns(false);
// First client: master is node A
- $clientA = Double::for(RedisCluster::class);
+ $clientA = Double::for(RedisCluster::class)->strict();
$clientA->expects('_masters')->returns([['10.0.0.1', 6379]]);
$clientA->allows('getMode')->returns(Redis::ATOMIC);
$clientA->expects('ping')->with(['10.0.0.1', 6379])->returns(true);
$clientA->allows('setOption')->returns(true);
// Second client (after reconnect): master is node B
- $clientB = Double::for(RedisCluster::class);
+ $clientB = Double::for(RedisCluster::class)->strict();
$clientB->expects('_masters')->returns([['10.0.0.2', 6379]]);
$clientB->allows('getMode')->returns(Redis::ATOMIC);
$clientB->expects('ping')->with(['10.0.0.2', 6379])->returns(true);
@@ -1122,7 +1122,7 @@ private function expectDefaultConnectionOptions(RedisCluster $redis): void
*/
private function getMockedPool(): ConnectionPool
{
- $pool = Double::for(ConnectionPool::class);
+ $pool = Double::for(ConnectionPool::class)->strict();
$pool->allows('getOptions')->returns(PoolOptions::fromArray([]));
return $pool;
@@ -1133,7 +1133,7 @@ private function getMockedPool(): ConnectionPool
*/
private function getContainer(): ContainerContract
{
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->allows('has')->returns(false);
$container->allows('bound')->with('events')->returns(false);
diff --git a/tests/Redis/RedisConnectionTest.php b/tests/Redis/RedisConnectionTest.php
index 9a069f1fb3..f93808f387 100644
--- a/tests/Redis/RedisConnectionTest.php
+++ b/tests/Redis/RedisConnectionTest.php
@@ -69,8 +69,7 @@ public function testRelease(): void
$pool->expects('release');
$connection = $this->mockRedisConnection(pool: $pool);
- $redis = Double::for(Redis::class)->strict();
- $redis->expects('getMode')->returns(Redis::ATOMIC);
+ $redis = $this->mockIdleRedisClient();
$connection->setActiveConnection($redis);
$connection->shouldTransform(true);
@@ -242,10 +241,9 @@ public function testSuccessfulTerminalCommandsClearTrackedWatchState(
): void {
$pool = $this->getMockedPool();
$pool->expects('release')->with(Argument::type(RedisConnection::class));
- $redis = Double::for(Redis::class)->strict();
+ $redis = $this->mockIdleRedisClient();
$redis->expects('watch')->with('key')->returns(true);
$redis->expects(strtolower($command))->returns($result);
- $redis->expects('getMode')->returns(Redis::ATOMIC);
$connection = $this->mockRedisConnection(pool: $pool);
$connection->setActiveConnection($redis);
@@ -282,10 +280,9 @@ public function testNativeDiscardClearsTrackedWatchState(): void
{
$pool = $this->getMockedPool();
$pool->expects('release')->with(Argument::type(RedisConnection::class));
- $redis = Double::for(Redis::class)->strict();
+ $redis = $this->mockIdleRedisClient();
$redis->expects('watch')->with('key')->returns(true);
$redis->expects('discard')->returns(true);
- $redis->expects('getMode')->returns(Redis::ATOMIC);
$connection = $this->mockRedisConnection(pool: $pool);
$connection->setActiveConnection($redis);
@@ -298,9 +295,8 @@ public function testClearWatchStateAllowsOrdinaryRelease(): void
{
$pool = $this->getMockedPool();
$pool->expects('release')->with(Argument::type(RedisConnection::class));
- $redis = Double::for(Redis::class)->strict();
+ $redis = $this->mockIdleRedisClient();
$redis->expects('watch')->with('key')->returns(true);
- $redis->expects('getMode')->returns(Redis::ATOMIC);
$connection = $this->mockRedisConnection(pool: $pool);
$connection->setActiveConnection($redis);
@@ -3821,6 +3817,19 @@ protected function expectDefaultConnectionOptions(Redis $redis): void
$redis->expects('setOption')->with(Redis::OPT_BACKOFF_CAP, 1000)->returns(true);
}
+ /**
+ * Create a connected client ready to return to the pool on its default database.
+ */
+ protected function mockIdleRedisClient(): Redis
+ {
+ $redis = Double::for(Redis::class)->strict();
+ $redis->expects('getMode')->returns(Redis::ATOMIC);
+ $redis->allows('isConnected')->returns(true);
+ $redis->allows('getDBNum')->returns(0);
+
+ return $redis;
+ }
+
/**
* Create a Redis connection test double.
*/
diff --git a/tests/Redis/RedisEventsTest.php b/tests/Redis/RedisEventsTest.php
index b5ca8dcc64..6f7e0f5076 100644
--- a/tests/Redis/RedisEventsTest.php
+++ b/tests/Redis/RedisEventsTest.php
@@ -104,7 +104,7 @@ public function testCommandFailedEventContainsTime(): void
{
$exception = new Exception('Test exception');
- $mockEventDispatcher = Double::for(Dispatcher::class);
+ $mockEventDispatcher = Double::for(Dispatcher::class)->strict();
$mockEventDispatcher->allows('hasListeners')
->with(CommandFailed::class)
->returns(true);
@@ -132,7 +132,7 @@ public function testCommandFailedEventContainsTime(): void
public function testListenRegistersCallback(): void
{
- $mockEventDispatcher = Double::for(Dispatcher::class);
+ $mockEventDispatcher = Double::for(Dispatcher::class)->strict();
$mockEventDispatcher->expects('listen')
->with(CommandExecuted::class, Argument::type(Closure::class));
@@ -164,7 +164,7 @@ public function testListenForFailuresRegistersCallback(): void
public function testCommandExecutedNotDispatchedWhenNoListeners(): void
{
- $mockEventDispatcher = Double::for(Dispatcher::class);
+ $mockEventDispatcher = Double::for(Dispatcher::class)->strict();
$mockEventDispatcher->allows('hasListeners')
->with(CommandFailed::class)
->returns(false);
@@ -185,7 +185,7 @@ public function testCommandFailedNotDispatchedWhenNoListeners(): void
{
$exception = new Exception('Redis error');
- $mockEventDispatcher = Double::for(Dispatcher::class);
+ $mockEventDispatcher = Double::for(Dispatcher::class)->strict();
$mockEventDispatcher->allows('hasListeners')
->with(CommandFailed::class)
->returns(false);
@@ -215,12 +215,9 @@ public function testListenNoOpsWhenEventsUnbound(): void
$redis = $this->createRedis($this->createMockRedisConnection());
- // Should not throw
- $redis->listen(function (): void {
- // callback
- });
+ $redis->listen(fn () => $this->fail('Registering a listener must not invoke it.'));
- $this->assertTrue(true);
+ $this->assertFalse($container->bound('events'));
}
public function testListenForFailuresNoOpsWhenEventsUnbound(): void
@@ -232,12 +229,9 @@ public function testListenForFailuresNoOpsWhenEventsUnbound(): void
$redis = $this->createRedis($this->createMockRedisConnection());
- // Should not throw
- $redis->listenForFailures(function (): void {
- // callback
- });
+ $redis->listenForFailures(fn () => $this->fail('Registering a listener must not invoke it.'));
- $this->assertTrue(true);
+ $this->assertFalse($container->bound('events'));
}
/**
@@ -245,17 +239,17 @@ public function testListenForFailuresNoOpsWhenEventsUnbound(): void
*/
private function createRedis(RedisConnection $connection): RedisProxy
{
- $pool = Double::for(RedisPool::class);
+ $pool = Double::for(RedisPool::class)->strict();
$pool->allows('borrow')->returns($connection);
$pool->allows('getOptions')->returns(PoolOptions::fromArray([]));
- $poolManager = Double::for(PoolManager::class);
+ $poolManager = Double::for(PoolManager::class)->passthru();
$poolManager->allows('pool')->with('default')->returns($pool);
return new RedisProxy(
$poolManager,
'default',
- Double::for(RedisSentinelFactory::class),
+ Double::for(RedisSentinelFactory::class)->strict(),
);
}
@@ -268,7 +262,7 @@ private function createMockRedisConnection(
?Throwable $exception = null,
?Dispatcher $eventDispatcher = null
): RedisConnection&DoubleInterface {
- $mockRedisConnection = Double::for(RedisEventsConnection::class);
+ $mockRedisConnection = Double::for(RedisEventsConnection::class)->strict();
$mockRedisConnection->allows('shouldTransform')->returns($mockRedisConnection);
$mockRedisConnection->allows('getConnection')->returns($mockRedisConnection);
$mockRedisConnection->allows('getEventDispatcher')->returns($eventDispatcher);
diff --git a/tests/Redis/RedisPoolHeartbeatTest.php b/tests/Redis/RedisPoolHeartbeatTest.php
index ab2830cb88..8f7480d467 100644
--- a/tests/Redis/RedisPoolHeartbeatTest.php
+++ b/tests/Redis/RedisPoolHeartbeatTest.php
@@ -26,6 +26,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use Redis;
use RedisCluster;
@@ -496,7 +497,7 @@ public function testHeartbeatCancellationDuringStartupReportingStopsThePublished
$childCoroutineId = null;
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, $cleanupStarted, $releaseCleanup, &$childCoroutineId): void {
$childCoroutineId = Coroutine::id();
$reportStarted->push(true);
diff --git a/tests/Reverb/EventDispatcherTest.php b/tests/Reverb/EventDispatcherTest.php
index 432d1a9378..c9dcbb64c1 100644
--- a/tests/Reverb/EventDispatcherTest.php
+++ b/tests/Reverb/EventDispatcherTest.php
@@ -155,7 +155,7 @@ public function testCanceledDispatchStopsBeforeLaterChannelsAndWorkers(string $m
$channels->expects('find')->with('first')->returns($channel);
$channels->expects('find')->never()->with('later');
$manager = Double::for(ChannelManager::class)->strict();
- $manager->expects('for')->with($app)->returns($channels);
+ $manager->expects('for')->with(Argument::same($app))->returns($channels);
$this->app->instance(ChannelManager::class, $manager);
$server = Double::for(Server::class)->strict();
$server->setting = ['worker_num' => 2];
@@ -242,7 +242,7 @@ public function testSynchronousDispatchAttemptsEveryChannelAndFanOutBeforeThrowi
$channels->expects('find')->with('cache-first')->returns($cacheChannel);
$channels->expects('find')->with('later')->returns($laterChannel);
$manager = Double::for(ChannelManager::class)->strict();
- $manager->expects('for')->times(2)->with($app)->returns($channels);
+ $manager->expects('for')->times(2)->with(Argument::same($app))->returns($channels);
$this->app->instance(ChannelManager::class, $manager);
$sharedState = Double::for(SharedState::class)->strict();
$sharedState->expects('clearCacheMissLock')
diff --git a/tests/Reverb/Protocols/Pusher/Channels/ChannelTest.php b/tests/Reverb/Protocols/Pusher/Channels/ChannelTest.php
index 8c4a7c16d2..0df464aad7 100644
--- a/tests/Reverb/Protocols/Pusher/Channels/ChannelTest.php
+++ b/tests/Reverb/Protocols/Pusher/Channels/ChannelTest.php
@@ -26,6 +26,7 @@
use Hypervel\Tests\Reverb\Fixtures\FakeConnection;
use Hypervel\Tests\Reverb\ReverbTestCase;
use JMac\Testing\Double;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
use Swoole\Coroutine\Channel as CoroutineChannel;
@@ -82,7 +83,7 @@ public function testRemovesAChannelWhenNoSubscribersRemain(): void
$channel->unsubscribe($this->connection);
$scopedManager->received('remove')->times(1)
- ->with($channel);
+ ->with(Argument::same($channel));
}
public function testDuplicateSubscribeAndNonmemberUnsubscribeDoNotPublishSharedState(): void
@@ -287,7 +288,7 @@ public function send(string $message): void
$second = $failingConnection($secondFailure);
$last = new FakeConnection;
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($firstFailure);
+ $handler->expects('report')->with(Argument::same($firstFailure));
$this->app->instance(ExceptionHandler::class, $handler);
foreach ([$first, $middle, $second, $last] as $connection) {
diff --git a/tests/Reverb/Protocols/Pusher/Channels/PresenceCacheChannelTest.php b/tests/Reverb/Protocols/Pusher/Channels/PresenceCacheChannelTest.php
index f5695550e7..563273aff2 100644
--- a/tests/Reverb/Protocols/Pusher/Channels/PresenceCacheChannelTest.php
+++ b/tests/Reverb/Protocols/Pusher/Channels/PresenceCacheChannelTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\Reverb\Fixtures\FakeConnection;
use Hypervel\Tests\Reverb\ReverbTestCase;
use JMac\Testing\Double;
+use JMac\Testing\Matching\Argument;
class PresenceCacheChannelTest extends ReverbTestCase
{
@@ -106,7 +107,7 @@ public function testSendsNotificationOfSubscription(): void
$channel = $this->channels()->findOrCreate('presence-cache-test-channel');
$this->channelConnectionManager->expects('add')
- ->with($this->connection, []);
+ ->with(Argument::same($this->connection), []);
$this->channelConnectionManager->allows('all')
->returns($connections = static::factory(3));
@@ -126,7 +127,7 @@ public function testSendsNotificationOfSubscriptionWithData(): void
$data = json_encode(['name' => 'Joe']);
$this->channelConnectionManager->expects('add')
- ->with($this->connection, ['name' => 'Joe']);
+ ->with(Argument::same($this->connection), ['name' => 'Joe']);
$this->channelConnectionManager->allows('all')
->returns($connections = static::factory(3));
@@ -162,7 +163,7 @@ public function testSendsNotificationOfAnUnsubscribe(): void
->returns($connections = static::factory(3));
$this->channelConnectionManager->expects('remove')
- ->with($this->connection);
+ ->with(Argument::same($this->connection));
$channel->unsubscribe($this->connection);
@@ -178,7 +179,7 @@ public function testReceivesNoDataWhenNoPreviousEventTriggered(): void
$channel = $this->channels()->findOrCreate('presence-cache-test-channel');
$this->channelConnectionManager->expects('add')
- ->with($this->connection, []);
+ ->with(Argument::same($this->connection), []);
$channel->subscribe($this->connection, static::validAuth($this->connection->id(), 'presence-cache-test-channel'));
diff --git a/tests/Reverb/Protocols/Pusher/Channels/PresenceChannelTest.php b/tests/Reverb/Protocols/Pusher/Channels/PresenceChannelTest.php
index cce41e3d40..e48992968c 100644
--- a/tests/Reverb/Protocols/Pusher/Channels/PresenceChannelTest.php
+++ b/tests/Reverb/Protocols/Pusher/Channels/PresenceChannelTest.php
@@ -15,6 +15,7 @@
use Hypervel\Tests\Reverb\Fixtures\FakeConnection;
use Hypervel\Tests\Reverb\ReverbTestCase;
use JMac\Testing\Double;
+use JMac\Testing\Matching\Argument;
class PresenceChannelTest extends ReverbTestCase
{
@@ -128,7 +129,7 @@ public function testSendsNotificationOfSubscription(): void
$channel = $this->channels()->findOrCreate('presence-test-channel');
$this->channelConnectionManager->expects('add')
- ->with($this->connection, []);
+ ->with(Argument::same($this->connection), []);
$this->channelConnectionManager->allows('all')
->returns($connections = static::factory(3));
@@ -148,7 +149,7 @@ public function testSendsNotificationOfSubscriptionWithData(): void
$data = json_encode(['name' => 'Joe']);
$this->channelConnectionManager->expects('add')
- ->with($this->connection, ['name' => 'Joe']);
+ ->with(Argument::same($this->connection), ['name' => 'Joe']);
$this->channelConnectionManager->allows('all')
->returns($connections = static::factory(3));
@@ -184,7 +185,7 @@ public function testSendsNotificationOfAnUnsubscribe(): void
->returns($connections = static::factory(3));
$this->channelConnectionManager->expects('remove')
- ->with($this->connection);
+ ->with(Argument::same($this->connection));
$channel->unsubscribe($this->connection);
diff --git a/tests/Reverb/Protocols/Pusher/EventHandlerTest.php b/tests/Reverb/Protocols/Pusher/EventHandlerTest.php
index 907afdf464..bcdd48fb62 100644
--- a/tests/Reverb/Protocols/Pusher/EventHandlerTest.php
+++ b/tests/Reverb/Protocols/Pusher/EventHandlerTest.php
@@ -88,7 +88,7 @@ public function testSubscriptionSucceedsWhenWebhookHandoffFails(): void
$sender->expects('send')->throws($failure);
$this->app->instance(WebhookSender::class, $sender);
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($failure);
+ $exceptionHandler->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$this->pusher->subscribe($this->connection, 'test-channel');
@@ -132,7 +132,7 @@ public function testPresenceSubscriptionSurvivesSiblingPublicationFailure(): voi
$metrics = $this->app->make(MetricsHandler::class);
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($failure);
+ $exceptionHandler->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$data = ['user_id' => '1', 'user_info' => ['name' => 'Taylor']];
@@ -202,7 +202,7 @@ public function testPresenceSubscriptionSurvivesRedisPublicationFailure(): void
$this->app->make(ServerProviderManager::class)->withPublishing();
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($failure);
+ $exceptionHandler->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$data = ['user_id' => '1', 'user_info' => ['name' => 'Taylor']];
@@ -275,7 +275,7 @@ public function testFallsBackToLocalMembersWhenTheGatherFails(): void
$this->app->instance(MetricsHandler::class, $metrics);
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($failure);
+ $exceptionHandler->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$data = json_encode(['user_id' => 1, 'user_info' => ['name' => 'Joe']]);
diff --git a/tests/Reverb/Protocols/Pusher/MetricsHandlerTest.php b/tests/Reverb/Protocols/Pusher/MetricsHandlerTest.php
index c01de32243..32c9560631 100644
--- a/tests/Reverb/Protocols/Pusher/MetricsHandlerTest.php
+++ b/tests/Reverb/Protocols/Pusher/MetricsHandlerTest.php
@@ -538,7 +538,7 @@ public function testUnscaledMultiWorkerLocalMetricFailureRemovesPendingState():
$failure = new RuntimeException('Unable to read local channels.');
$serverManager = new ServerProviderManager($this->app);
$channels = Double::for(ChannelManager::class)->strict();
- $channels->expects('for')->with($app)->throws($failure);
+ $channels->expects('for')->with(Argument::same($app))->throws($failure);
$server = Double::for(Server::class)->strict();
$server->setting = ['worker_num' => 2];
$server->worker_id = 0;
diff --git a/tests/Reverb/Protocols/Pusher/PusherPubSubIncomingMessageHandlerTest.php b/tests/Reverb/Protocols/Pusher/PusherPubSubIncomingMessageHandlerTest.php
index ca890e8046..2720370686 100644
--- a/tests/Reverb/Protocols/Pusher/PusherPubSubIncomingMessageHandlerTest.php
+++ b/tests/Reverb/Protocols/Pusher/PusherPubSubIncomingMessageHandlerTest.php
@@ -32,34 +32,37 @@ public function testUnknownEventTypeIsSilentlyIgnored(): void
{
$handler = new PusherPubSubIncomingMessageHandler;
- // No listener registered, unknown type, no app_id — should not throw
+ $connection = $this->subscribeConnection('test-channel');
+
$handler->handle(json_encode([
'type' => 'completely_unknown',
'data' => [],
]));
- $this->assertTrue(true);
+ $connection->assertNothingReceived();
}
public function testMessageEventDispatchesToLocalConnections(): void
{
+ $connection = $this->subscribeConnection('test-channel');
$handler = new PusherPubSubIncomingMessageHandler;
+ $payload = ['channel' => 'test-channel', 'event' => 'TestEvent', 'data' => '{}'];
- // Message type requires app_id — verify it resolves the app
- // and dispatches synchronously (using the test app from ReverbTestCase)
$handler->handle(json_encode([
'type' => 'message',
'app_id' => '123456',
- 'payload' => [
- 'channel' => 'nonexistent-channel',
- 'event' => 'TestEvent',
- 'data' => '{}',
- ],
+ 'payload' => [...$payload, 'channel' => 'nonexistent-channel'],
+ ]));
+
+ $connection->assertNothingReceived();
+
+ $handler->handle(json_encode([
+ 'type' => 'message',
+ 'app_id' => '123456',
+ 'payload' => $payload,
]));
- // No exception — the channel doesn't exist locally so nothing broadcasts,
- // but the handler resolves the app and processes without error
- $this->assertTrue(true);
+ $connection->assertReceived($payload);
}
public function testMessageEventExcludesTheSocketOnTheWorkerThatOwnsIt(): void
diff --git a/tests/Reverb/Protocols/Pusher/ServerTest.php b/tests/Reverb/Protocols/Pusher/ServerTest.php
index 55e89d3306..ffc151ad3b 100644
--- a/tests/Reverb/Protocols/Pusher/ServerTest.php
+++ b/tests/Reverb/Protocols/Pusher/ServerTest.php
@@ -26,6 +26,7 @@
use Hypervel\Tests\Reverb\Fixtures\FakeConnection;
use Hypervel\Tests\Reverb\ReverbTestCase;
use JMac\Testing\Double;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
use Swoole\Coroutine\CanceledException;
@@ -124,7 +125,7 @@ public function testCanHandleADisconnection(): void
$server->open($connection = new FakeConnection);
$server->close($connection);
- $scopedManager->received('unsubscribeFromAll')->with($connection)->times(1);
+ $scopedManager->received('unsubscribeFromAll')->with(Argument::same($connection))->times(1);
}
public function testCanHandleANewMessage(): void
@@ -263,7 +264,7 @@ public function testReportsUnexpectedMessageFailuresWithoutChangingTheClientPayl
$handler->expects('handle')->throws($exception);
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($exception);
+ $exceptionHandler->expects('report')->with(Argument::same($exception));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$server = $this->app->makeWith(Server::class, ['handler' => $handler]);
diff --git a/tests/Reverb/Servers/Hypervel/ChannelBroadcastPipeMessageTest.php b/tests/Reverb/Servers/Hypervel/ChannelBroadcastPipeMessageTest.php
index 6e6427e2c8..9690f5dad2 100644
--- a/tests/Reverb/Servers/Hypervel/ChannelBroadcastPipeMessageTest.php
+++ b/tests/Reverb/Servers/Hypervel/ChannelBroadcastPipeMessageTest.php
@@ -242,7 +242,7 @@ public function testMetricsResponseIsDeliveredToThePendingGather(): void
{
$message = new MetricsResponsePipeMessage('request', ['count' => 1]);
$metrics = Double::for(MetricsHandler::class)->strict();
- $metrics->expects('receive')->with($message);
+ $metrics->expects('receive')->with(Argument::same($message));
$this->app->instance(MetricsHandler::class, $metrics);
event(new OnPipeMessage(Double::for(Server::class)->strict(), 2, $message));
diff --git a/tests/Reverb/Servers/Hypervel/GracefulShutdownTest.php b/tests/Reverb/Servers/Hypervel/GracefulShutdownTest.php
index a3f2f06470..ba98c0b0d3 100644
--- a/tests/Reverb/Servers/Hypervel/GracefulShutdownTest.php
+++ b/tests/Reverb/Servers/Hypervel/GracefulShutdownTest.php
@@ -131,9 +131,9 @@ public function testShutdownAttemptsEveryPhaseAndReportsEachFailure(): void
->with(OnWorkerExit::class, Argument::capture($listener));
$this->app->instance('events', $events);
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($failures['drain']);
- $exceptionHandler->expects('report')->with($failures['subscriber']);
- $exceptionHandler->expects('report')->with($failures['webhooks']);
+ $exceptionHandler->expects('report')->with(Argument::same($failures['drain']));
+ $exceptionHandler->expects('report')->with(Argument::same($failures['subscriber']));
+ $exceptionHandler->expects('report')->with(Argument::same($failures['webhooks']));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$provider = new GracefulShutdownServiceProviderProbe($this->app);
$provider->failures = $failures;
@@ -155,7 +155,7 @@ public function testShutdownReportingFallsBackToThePhpErrorLog(): void
$failure = new RuntimeException('Connection drain failed.');
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
$exceptionHandler->expects('report')
- ->with($failure)
+ ->with(Argument::same($failure))
->throws(new RuntimeException('Reporting failed.'));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$provider = new GracefulShutdownServiceProviderProbe($this->app);
@@ -244,7 +244,7 @@ public function testScheduleWebhookFlushesContinuesAfterOneApplicationsBufferFai
$buffer->expects('clearFlushLock')->never();
$this->app->instance(WebhookBatchBuffer::class, $buffer);
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($failure);
+ $exceptionHandler->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$provider = $this->app->getProvider(ReverbServiceProvider::class);
@@ -321,6 +321,7 @@ public function testShutdownDoesNotLosePreExistingDeferredWebhooks(): void
$sharedState->allows('getSubscriptionCount')
->with('test-app', 'test-channel')
->returns(0);
+ $sharedState->expects('clearSmoothingPending')->with('test-app', 'test-channel', 5000);
$this->app->instance(SharedState::class, $sharedState);
$webhooks = array_replace($this->webhookConfig(), [
diff --git a/tests/Reverb/Servers/Hypervel/HttpServerTest.php b/tests/Reverb/Servers/Hypervel/HttpServerTest.php
index 85dae6b06e..babf5ec894 100644
--- a/tests/Reverb/Servers/Hypervel/HttpServerTest.php
+++ b/tests/Reverb/Servers/Hypervel/HttpServerTest.php
@@ -191,8 +191,8 @@ public function testCancellationAfterAHeldFailurePublishesItAndReportsTheFailure
$router->expects('dispatch')->returns(new Response('OK'));
$this->app->instance(ReverbRouter::class, $router);
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($heldFailure)->ordered();
- $handler->expects('report')->with($listenerFailure)->ordered();
+ $handler->expects('report')->with(Argument::same($heldFailure))->ordered();
+ $handler->expects('report')->with(Argument::same($listenerFailure))->ordered();
$this->app->instance(ExceptionHandler::class, $handler);
$canceled = null;
@@ -274,7 +274,7 @@ public function testEmitsFallbackResponseWhenRequestIsUnavailable(): void
$original = new RuntimeException('Request body failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original);
+ $handler->expects('report')->with(Argument::same($original));
$handler->expects('render')->never();
$this->app->instance(ExceptionHandler::class, $handler);
@@ -291,7 +291,7 @@ public function testRetainsRequestFailureWhenExceptionReportingFails(): void
$original = new RuntimeException('Request failed');
$reportingFailure = new RuntimeException('Reporting failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original)->throws($reportingFailure);
+ $handler->expects('report')->with(Argument::same($original))->throws($reportingFailure);
$handler->expects('render')->never();
$this->app->instance(ExceptionHandler::class, $handler);
@@ -313,9 +313,9 @@ public function testReportsRendersAndEmitsRequestFailure(): void
$original = new RuntimeException('Request failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original);
+ $handler->expects('report')->with(Argument::same($original));
$handler->expects('render')
- ->with(Argument::type(Request::class), $original)
+ ->with(Argument::type(Request::class), Argument::same($original))
->returns(new Response('Internal Server Error', 500));
$this->app->instance(ExceptionHandler::class, $handler);
@@ -369,9 +369,9 @@ public function testRetainsRequestFailureWhenResponseEmissionFails(): void
$original = new RuntimeException('Request failed');
$emissionFailure = new RuntimeException('Response emission failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original);
+ $handler->expects('report')->with(Argument::same($original));
$handler->expects('render')
- ->with(Argument::type(Request::class), $original)
+ ->with(Argument::type(Request::class), Argument::same($original))
->returns(new Response('Internal Server Error', 500));
$this->app->instance(ExceptionHandler::class, $handler);
diff --git a/tests/Reverb/Servers/Hypervel/Scaling/RedisPubSubProviderTest.php b/tests/Reverb/Servers/Hypervel/Scaling/RedisPubSubProviderTest.php
index 6e82ab508d..b8bfe4654d 100644
--- a/tests/Reverb/Servers/Hypervel/Scaling/RedisPubSubProviderTest.php
+++ b/tests/Reverb/Servers/Hypervel/Scaling/RedisPubSubProviderTest.php
@@ -26,6 +26,7 @@
use Hypervel\Tests\Reverb\ReverbTestCase;
use JMac\Testing\Double;
use JMac\Testing\DoubleInterface;
+use JMac\Testing\Matching\Argument;
use JsonException;
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
use Redis;
@@ -85,7 +86,7 @@ public function testCallerCancellationDuringStartupReportingLeavesTheLifecycleCh
$provider = $this->provider($redis);
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
@@ -251,7 +252,7 @@ public function testMessageHandlerFailureDoesNotReplaceTheSubscriber(): void
throw $handlerFailure;
});
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($handlerFailure);
+ $exceptionHandler->expects('report')->with(Argument::same($handlerFailure));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$provider->connect();
diff --git a/tests/Reverb/Servers/Hypervel/Scaling/RedisSharedStateTest.php b/tests/Reverb/Servers/Hypervel/Scaling/RedisSharedStateTest.php
index 6d530874e0..2f7e67af45 100644
--- a/tests/Reverb/Servers/Hypervel/Scaling/RedisSharedStateTest.php
+++ b/tests/Reverb/Servers/Hypervel/Scaling/RedisSharedStateTest.php
@@ -62,14 +62,7 @@ public function testPresenceSubscribeUsesOneAtomicScript(): void
{
[$redis, $connection] = $this->redisConnection();
$connection->expects('evalWithShaCache')
- ->with(Argument::all(function (string $script, array $keys, array $arguments): bool {
- $this->assertStringContainsString("redis.call('INCR', KEYS[1])", $script);
- $this->assertStringContainsString("redis.call('INCR', KEYS[2])", $script);
- $this->assertCount(2, $keys);
- $this->assertSame([], $arguments);
-
- return true;
- }))
+ ->with(Argument::capture($script), Argument::capture($keys), [])
->returns([1, 1]);
$result = (new RedisSharedState($redis))->subscribe('app', 'presence-channel', 'user');
@@ -77,20 +70,16 @@ public function testPresenceSubscribeUsesOneAtomicScript(): void
$this->assertTrue($result->channelOccupied);
$this->assertTrue($result->memberAdded);
$this->assertSame(1, $result->subscriptionCount);
+ $this->assertStringContainsString("redis.call('INCR', KEYS[1])", $script);
+ $this->assertStringContainsString("redis.call('INCR', KEYS[2])", $script);
+ $this->assertCount(2, $keys);
}
public function testPresenceUnsubscribeUsesOneAtomicScript(): void
{
[$redis, $connection] = $this->redisConnection();
$connection->expects('evalWithShaCache')
- ->with(Argument::all(function (string $script, array $keys, array $arguments): bool {
- $this->assertStringContainsString("redis.call('DECR', KEYS[1])", $script);
- $this->assertStringContainsString("redis.call('DECR', KEYS[2])", $script);
- $this->assertCount(2, $keys);
- $this->assertSame([], $arguments);
-
- return true;
- }))
+ ->with(Argument::capture($script), Argument::capture($keys), [])
->returns([0, 0]);
$result = (new RedisSharedState($redis))->unsubscribe('app', 'presence-channel', 'user');
@@ -98,6 +87,9 @@ public function testPresenceUnsubscribeUsesOneAtomicScript(): void
$this->assertTrue($result->channelVacated);
$this->assertTrue($result->memberRemoved);
$this->assertSame(0, $result->subscriptionCount);
+ $this->assertStringContainsString("redis.call('DECR', KEYS[1])", $script);
+ $this->assertStringContainsString("redis.call('DECR', KEYS[2])", $script);
+ $this->assertCount(2, $keys);
}
/**
diff --git a/tests/Reverb/Servers/Hypervel/Scaling/SwooleTableSharedStateTest.php b/tests/Reverb/Servers/Hypervel/Scaling/SwooleTableSharedStateTest.php
index 5d7080a1c4..38f1cc7a67 100644
--- a/tests/Reverb/Servers/Hypervel/Scaling/SwooleTableSharedStateTest.php
+++ b/tests/Reverb/Servers/Hypervel/Scaling/SwooleTableSharedStateTest.php
@@ -175,8 +175,8 @@ public function testReleaseConnectionSlotIsSafeWhenNoSlotAcquired(): void
{
$this->state->releaseConnectionSlot('app1');
- // No exception — just a no-op
- $this->assertTrue(true);
+ $this->assertTrue($this->state->acquireConnectionSlot('app1', 1));
+ $this->assertFalse($this->state->acquireConnectionSlot('app1', 1));
}
public function testThrowsExceptionWhenTableIsFull(): void
diff --git a/tests/Reverb/Servers/Hypervel/WebSocketHandlerTest.php b/tests/Reverb/Servers/Hypervel/WebSocketHandlerTest.php
index 7bfb838490..f0b3c942ee 100644
--- a/tests/Reverb/Servers/Hypervel/WebSocketHandlerTest.php
+++ b/tests/Reverb/Servers/Hypervel/WebSocketHandlerTest.php
@@ -187,7 +187,7 @@ public function testOnMessageDelegatesTextFrameToServer(): void
$connection = $this->createStoredConnection(1);
$this->pusherServer->expects('message')
- ->with($connection, '{"event":"pusher:ping"}');
+ ->with(Argument::same($connection), '{"event":"pusher:ping"}');
$swooleServer = Double::for(WebSocketServer::class)->strict();
@@ -224,7 +224,7 @@ public function testOnMessageHandlesPingControlFrame(): void
$connection = $this->createStoredConnection(1);
$this->pusherServer->expects('control')
- ->with($connection, WEBSOCKET_OPCODE_PING);
+ ->with(Argument::same($connection), WEBSOCKET_OPCODE_PING);
$swooleServer = Double::for(WebSocketServer::class)->strict();
$swooleServer->expects('push')
@@ -242,7 +242,7 @@ public function testOnMessageHandlesPongControlFrame(): void
$connection = $this->createStoredConnection(1);
$this->pusherServer->expects('control')
- ->with($connection, WEBSOCKET_OPCODE_PONG);
+ ->with(Argument::same($connection), WEBSOCKET_OPCODE_PONG);
$swooleServer = Double::for(WebSocketServer::class)->strict();
// No pong response should be sent for pong frames
@@ -274,7 +274,7 @@ public function testOnCloseDelegatesToServerAndCleansUp(): void
{
$connection = $this->createStoredConnection(1);
- $this->pusherServer->expects('close')->with($connection);
+ $this->pusherServer->expects('close')->with(Argument::same($connection));
$swooleServer = Double::for(Server::class)->strict();
diff --git a/tests/Reverb/Webhooks/HttpWebhookDispatcherTest.php b/tests/Reverb/Webhooks/HttpWebhookDispatcherTest.php
index 9502fb57cd..ba7c210439 100644
--- a/tests/Reverb/Webhooks/HttpWebhookDispatcherTest.php
+++ b/tests/Reverb/Webhooks/HttpWebhookDispatcherTest.php
@@ -402,7 +402,7 @@ public function testBatchingClearsANewlyOwnedLockWhenQueueDispatchFails(): void
$dispatcher = new HttpWebhookDispatcher;
$exceptionHandler = Double::for(ExceptionHandler::class)->strict();
- $exceptionHandler->expects('report')->with($failure);
+ $exceptionHandler->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
$dispatcher->dispatch($app, 'channel_occupied', ['channel' => 'test-channel']);
@@ -423,7 +423,7 @@ public function testBufferFailuresAreReportedAndCancellationPropagates(bool $can
$exceptionHandler->expects('report')->never();
$this->expectExceptionObject($failure);
} else {
- $exceptionHandler->expects('report')->with($failure);
+ $exceptionHandler->expects('report')->with(Argument::same($failure));
}
$this->app->instance(ExceptionHandler::class, $exceptionHandler);
@@ -487,7 +487,7 @@ public function testImmediateWebhooksAreHandedToTheBoundSender(): void
]));
$sender = Double::for(WebhookSender::class)->strict();
$sender->expects('send')->with(
- $app,
+ Argument::same($app),
$app->webhooks(),
Argument::satisfies(static fn (WebhookPayload $payload): bool => $payload->events === [
['name' => 'channel_occupied', 'channel' => 'test-channel'],
diff --git a/tests/Reverb/Webhooks/Jobs/FlushWebhookBatchJobTest.php b/tests/Reverb/Webhooks/Jobs/FlushWebhookBatchJobTest.php
index 640d3cb4f0..d7d5b626ba 100644
--- a/tests/Reverb/Webhooks/Jobs/FlushWebhookBatchJobTest.php
+++ b/tests/Reverb/Webhooks/Jobs/FlushWebhookBatchJobTest.php
@@ -70,7 +70,7 @@ public function testHandsTheClaimedBatchToTheBoundSender(): void
$sender->expects('send')->with(
Argument::satisfies(static fn (Application $application): bool => $application->id() === '123456'),
$config,
- $batch['payload'],
+ Argument::same($batch['payload']),
);
$job = new FlushWebhookBatchJob('123456', $config);
diff --git a/tests/Routing/RoutePortTest.php b/tests/Routing/RoutePortTest.php
index 6e95fa5e08..78334b0bf0 100644
--- a/tests/Routing/RoutePortTest.php
+++ b/tests/Routing/RoutePortTest.php
@@ -393,10 +393,10 @@ public function testCompiledRouteDynamicAddWithSamePortAllowed(): void
$compiledCollection->setRouter($router);
$compiledCollection->setContainer($container);
- // Same port — no exception
- $compiledCollection->add((new Route('GET', 'foo', ['uses' => fn () => 'other', 'as' => 'foo2']))->port(8080));
+ $route = (new Route('GET', 'foo', ['uses' => fn () => 'other', 'as' => 'foo2']))->port(8080);
+ $compiledCollection->add($route);
- $this->assertTrue(true);
+ $this->assertSame($route, $compiledCollection->getByName('foo2'));
}
/**
diff --git a/tests/Routing/RoutingPipelineTest.php b/tests/Routing/RoutingPipelineTest.php
index b60987245e..eed1e85621 100644
--- a/tests/Routing/RoutingPipelineTest.php
+++ b/tests/Routing/RoutingPipelineTest.php
@@ -27,7 +27,7 @@ public function testReportingFailureRetainsTheOriginalException(): void
$original = new RuntimeException('original');
$failure = new LogicException('reporting failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original)->throws($failure);
+ $handler->expects('report')->with(Argument::same($original))->throws($failure);
$handler->expects('render')->never();
$caught = $this->handleAndCatch($handler, $original);
@@ -41,8 +41,8 @@ public function testRenderingFailureRetainsTheOriginalException(): void
$original = new RuntimeException('original');
$failure = new LogicException('rendering failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original);
- $handler->expects('render')->with(Argument::type(Request::class), $original)->throws($failure);
+ $handler->expects('report')->with(Argument::same($original));
+ $handler->expects('render')->with(Argument::type(Request::class), Argument::same($original))->throws($failure);
$caught = $this->handleAndCatch($handler, $original);
@@ -56,7 +56,7 @@ public function testHandlingFailureRetainsItsExistingChainBeforeTheOriginalExcep
$existing = new DomainException('existing');
$failure = new LogicException('reporting failed', previous: $existing);
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original)->throws($failure);
+ $handler->expects('report')->with(Argument::same($original))->throws($failure);
$caught = $this->handleAndCatch($handler, $original);
@@ -69,7 +69,7 @@ public function testRethrowingTheOriginalExceptionDoesNotCreateASelfReferentialC
{
$original = new RuntimeException('original');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original)->throws($original);
+ $handler->expects('report')->with(Argument::same($original))->throws($original);
$caught = $this->handleAndCatch($handler, $original);
@@ -82,8 +82,8 @@ public function testSuccessfulHandlingReturnsTheRenderedResponse(): void
$original = new RuntimeException('original');
$response = new Response('handled', 500);
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($original);
- $handler->expects('render')->with(Argument::type(Request::class), $original)->returns($response);
+ $handler->expects('report')->with(Argument::same($original));
+ $handler->expects('render')->with(Argument::type(Request::class), Argument::same($original))->returns($response);
$this->assertSame($response, $this->pipeline($handler)->handleThrowable(new Request, $original));
}
diff --git a/tests/Routing/RoutingRedirectorTest.php b/tests/Routing/RoutingRedirectorTest.php
index 9ba86e2c0f..3f75a04ac0 100644
--- a/tests/Routing/RoutingRedirectorTest.php
+++ b/tests/Routing/RoutingRedirectorTest.php
@@ -13,6 +13,7 @@
use Hypervel\Session\Store;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use Symfony\Component\HttpFoundation\HeaderBag;
class RoutingRedirectorTest extends RoutingTestCase
@@ -39,7 +40,7 @@ protected function setUp(): void
$this->request->setRouteResolver(fn (): bool => true);
$this->request->headers = $this->headers;
- $this->url = Double::for(UrlGenerator::class);
+ $this->url = Double::for(UrlGenerator::class)->strict();
$this->url->allows('getRequest')->returns($this->request);
$this->url->allows('to')->with('bar', [], null)->returns('http://foo.com/bar');
$this->url->allows('to')->with('bar', [], true)->returns('https://foo.com/bar');
@@ -159,9 +160,9 @@ public function testRoute(): void
public function testRouteAcceptsUrlRoutableParameters(): void
{
- $parameter = Double::for(UrlRoutable::class);
+ $parameter = Double::for(UrlRoutable::class)->strict();
- $this->url->expects('route')->with('home', $parameter)->returns('http://foo.com/bar');
+ $this->url->expects('route')->with('home', Argument::same($parameter))->returns('http://foo.com/bar');
$response = $this->redirect->route('home', $parameter);
diff --git a/tests/Routing/RoutingResponseFactoryTest.php b/tests/Routing/RoutingResponseFactoryTest.php
index c23d206bfe..88ed99f1fa 100644
--- a/tests/Routing/RoutingResponseFactoryTest.php
+++ b/tests/Routing/RoutingResponseFactoryTest.php
@@ -177,7 +177,7 @@ public function testStreamingFactoriesPassCancellationThroughWithoutReportingOrW
{
$failure = new CanceledException('response canceled');
$cleanup = new RuntimeException('cleanup failed');
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$handler->expects('report')->never();
Container::getInstance()->instance(ExceptionHandler::class, $handler);
$operation = static function () use ($failure, $cleanup, $cleanupThrows): never {
@@ -228,8 +228,8 @@ public static function streamingFactoryMethods(): array
private function factory(): ResponseFactory
{
return new ResponseFactory(
- Double::for(ViewFactory::class),
- Double::for(Redirector::class),
+ Double::for(ViewFactory::class)->strict(),
+ Double::for(Redirector::class)->strict(),
);
}
}
diff --git a/tests/Saloon/Unit/RequestOptionValidatorTest.php b/tests/Saloon/Unit/RequestOptionValidatorTest.php
index 4b7a475f54..bca87e41e9 100644
--- a/tests/Saloon/Unit/RequestOptionValidatorTest.php
+++ b/tests/Saloon/Unit/RequestOptionValidatorTest.php
@@ -45,13 +45,13 @@ public static function reservedOptions(): iterable
public function testItAllowsTransportOptions(): void
{
+ $this->expectNotToPerformAssertions();
+
RequestOptionValidator::validate([
'allow_redirects' => false,
'proxy' => 'http://proxy.example.com',
'timeout' => 10,
'verify' => true,
], 'request options');
-
- $this->addToAssertionCount(1);
}
}
diff --git a/tests/Saloon/Unit/ResponseTest.php b/tests/Saloon/Unit/ResponseTest.php
index b1fff31eca..772e26f9f5 100644
--- a/tests/Saloon/Unit/ResponseTest.php
+++ b/tests/Saloon/Unit/ResponseTest.php
@@ -697,6 +697,7 @@ public function testFailedBodyExportDoesNotCloseACallerOwnedResource(): void
$source->expects('isSeekable')->returns(false);
$source->expects('eof')->returns(false);
$source->expects('read')->throws(new RuntimeException('read failed'));
+ $source->allows('getMetadata')->with('timed_out')->returns(false);
$response = $this->response(200, body: $source);
$resource = fopen('php://temp', 'wb+');
$this->assertIsResource($resource);
diff --git a/tests/Sanctum/SanctumServiceProviderTest.php b/tests/Sanctum/SanctumServiceProviderTest.php
index 5721a66e42..12729e0fc7 100644
--- a/tests/Sanctum/SanctumServiceProviderTest.php
+++ b/tests/Sanctum/SanctumServiceProviderTest.php
@@ -107,7 +107,7 @@ public function testConsoleStartupUsesDefaultsForOmittedCacheMembers(): void
$manager->expects('store')->with(null)->returns($repository);
$validator = Double::for(ModelCacheStoreValidator::class)->strict();
$validator->expects('validate')
- ->with($repository, 'Sanctum token cache');
+ ->with(Argument::same($repository), 'Sanctum token cache');
$bootedCallback = null;
$application = $this->consoleApplication($manager, $config);
$application->expects('make')
@@ -191,7 +191,7 @@ public function testServerValidationUsesWorkerDependenciesAndRunsForTaskworkers(
$workerManager->expects('store')->with('worker')->returns($workerRepository);
$validator = Double::for(ModelCacheStoreValidator::class)->strict();
$validator->expects('validate')
- ->with($workerRepository, 'Sanctum token cache');
+ ->with(Argument::same($workerRepository), 'Sanctum token cache');
$listener = null;
$events = Double::for(Dispatcher::class)->strict();
$events->expects('listen')
diff --git a/tests/Scout/Feature/CollectionEngineTest.php b/tests/Scout/Feature/CollectionEngineTest.php
index 430bd3c304..06ff939475 100644
--- a/tests/Scout/Feature/CollectionEngineTest.php
+++ b/tests/Scout/Feature/CollectionEngineTest.php
@@ -225,7 +225,7 @@ public function testUpdateAndDeleteAreNoOps(): void
$engine->delete($model->newCollection([$model]));
$engine->flush($model);
- $this->assertTrue(true);
+ $this->assertTrue(SearchableModel::query()->whereKey($model->getKey())->exists());
}
public function testCreateAndDeleteIndexAreNoOps(): void
diff --git a/tests/Scout/Feature/DatabaseEngineTest.php b/tests/Scout/Feature/DatabaseEngineTest.php
index 7a644cb3be..f941d2ba34 100644
--- a/tests/Scout/Feature/DatabaseEngineTest.php
+++ b/tests/Scout/Feature/DatabaseEngineTest.php
@@ -297,7 +297,7 @@ public function testUpdateAndDeleteAreNoOps(): void
$engine->delete($model->newCollection([$model]));
$engine->flush($model);
- $this->assertTrue(true);
+ $this->assertTrue(SearchableModel::query()->whereKey($model->getKey())->exists());
}
public function testSearchAttributeMetadataIsCachedPerEngineInstance(): void
diff --git a/tests/Scout/Unit/EngineOperationRunnerTest.php b/tests/Scout/Unit/EngineOperationRunnerTest.php
index db391ef3f0..75463c3387 100644
--- a/tests/Scout/Unit/EngineOperationRunnerTest.php
+++ b/tests/Scout/Unit/EngineOperationRunnerTest.php
@@ -15,6 +15,7 @@
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 Swoole\Coroutine\CanceledException;
@@ -110,7 +111,7 @@ function () use ($startingFailure): never {
fn (): null => null,
));
- $this->bindReportingHandler()->expects('report')->with($completionFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($completionFailure));
$caught = null;
try {
@@ -203,7 +204,7 @@ function () use (&$finished, $secondFailure): never {
},
));
- $this->bindReportingHandler()->expects('report')->with($secondFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($secondFailure));
$caught = null;
try {
@@ -305,7 +306,7 @@ function () use (&$secondFinished): void {
$secondFinished = true;
},
));
- $this->bindReportingHandler()->expects('report')->with($operationFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($operationFailure));
$caught = null;
diff --git a/tests/Scout/Unit/Engines/AlgoliaEngineTest.php b/tests/Scout/Unit/Engines/AlgoliaEngineTest.php
index ed551c71ef..19e177963b 100644
--- a/tests/Scout/Unit/Engines/AlgoliaEngineTest.php
+++ b/tests/Scout/Unit/Engines/AlgoliaEngineTest.php
@@ -1087,11 +1087,10 @@ public function testIdentifyHeadersReflectTheCurrentRequestNotTheCachedOne(): vo
$capturedHeaders = [];
$client->expects('searchSingleIndex')
->times(2)
- ->with('users', Argument::any(), Argument::satisfies(function ($opts) use (&$capturedHeaders) {
- $capturedHeaders[] = $opts['headers']['X-Forwarded-For'] ?? null;
-
- return true;
- }));
+ ->with('users', Argument::any(), Argument::any())
+ ->resolves(static function (string $indexName, mixed $searchParams, array $requestOptions) use (&$capturedHeaders): void {
+ $capturedHeaders[] = $requestOptions['headers']['X-Forwarded-For'] ?? null;
+ });
$engine = new AlgoliaEngine($client, identify: true);
@@ -1128,11 +1127,10 @@ public function testIdentifyHeadersDoNotLeakAcrossCoroutines(): void
$capturedHeaders = [];
$client->expects('searchSingleIndex')
->times(2)
- ->with('users', Argument::any(), Argument::satisfies(function ($opts) use (&$capturedHeaders) {
- $capturedHeaders[] = $opts['headers']['X-Forwarded-For'] ?? null;
-
- return true;
- }));
+ ->with('users', Argument::any(), Argument::any())
+ ->resolves(static function (string $indexName, mixed $searchParams, array $requestOptions) use (&$capturedHeaders): void {
+ $capturedHeaders[] = $requestOptions['headers']['X-Forwarded-For'] ?? null;
+ });
$engine = new AlgoliaEngine($client, identify: true);
diff --git a/tests/Scout/Unit/Engines/TypesenseEngineTest.php b/tests/Scout/Unit/Engines/TypesenseEngineTest.php
index 7112ce93d5..8db179920a 100644
--- a/tests/Scout/Unit/Engines/TypesenseEngineTest.php
+++ b/tests/Scout/Unit/Engines/TypesenseEngineTest.php
@@ -1177,15 +1177,12 @@ public function testPaginatePreservesValidatedPageSizeAndLargePage(): void
{
$engine = $this->createPartialEngineWithConfig(maxTotalResults: 10);
$engine->expects('performSearch')
- ->with(Argument::all(function (Builder $builder, array $options): bool {
- $this->assertSame(500_000_000, $options['page']);
- $this->assertSame(250, $options['per_page']);
-
- return true;
- }))
+ ->with(Argument::type(Builder::class), Argument::capture($options))
->returns(['hits' => [], 'found' => 0]);
$engine->paginate(new Builder(new TypesenseLifecycleModel, 'scout'), 250, 500_000_000);
+ $this->assertSame(500_000_000, $options['page']);
+ $this->assertSame(250, $options['per_page']);
}
public function testMapReturnsEmptyCollectionWhenNoResults(): void
diff --git a/tests/Scout/Unit/SearchableDispatchTest.php b/tests/Scout/Unit/SearchableDispatchTest.php
index 96d83f54f3..552e2cf93b 100644
--- a/tests/Scout/Unit/SearchableDispatchTest.php
+++ b/tests/Scout/Unit/SearchableDispatchTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\Scout\ScoutTestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
class SearchableDispatchTest extends ScoutTestCase
@@ -130,7 +131,7 @@ public function testAReportedFailureDoesNotStopLaterJobs(): void
{
$exception = new RuntimeException('indexing failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception, []);
+ $handler->expects('report')->with(Argument::same($exception), []);
$this->app->instance(ExceptionHandler::class, $handler);
$events = [];
diff --git a/tests/Sentry/EventHandlerTest.php b/tests/Sentry/EventHandlerTest.php
index d7bb38fc19..562588418e 100644
--- a/tests/Sentry/EventHandlerTest.php
+++ b/tests/Sentry/EventHandlerTest.php
@@ -120,7 +120,7 @@ public function testWorkerExitClosesTheTransportPoolWhenFlushFails(): void
SentrySdk::setCurrentHub(new Hub($client));
CoordinatorManager::initialize(Constants::WORKER_EXIT);
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
- $exceptionHandler->expects('report')->with($flushException);
+ $exceptionHandler->expects('report')->with(Argument::same($flushException));
$this->app->instance(ExceptionHandlerContract::class, $exceptionHandler);
try {
diff --git a/tests/Sentry/FlushLifecycleTest.php b/tests/Sentry/FlushLifecycleTest.php
index 00cde80b5c..07b4f87d06 100644
--- a/tests/Sentry/FlushLifecycleTest.php
+++ b/tests/Sentry/FlushLifecycleTest.php
@@ -28,6 +28,7 @@
use Sentry\ClientInterface;
use Sentry\Event;
use Sentry\EventType;
+use Sentry\Integration\OTLPIntegration;
use Sentry\Logs\Logs;
use Sentry\Metrics\TraceMetrics;
use Sentry\Options;
@@ -46,6 +47,8 @@ class FlushLifecycleTest extends TestCase
public function testDrainPublishesBufferedTelemetryBeforeTheBoundedWait(): void
{
$client = Double::for(ClientInterface::class)->strict();
+ // Once installed, Sentry's process-wide OTLP callback looks up the integration on the current client.
+ $client->allows('getIntegration')->with(OTLPIntegration::class)->returns(null);
$client->expects('getOptions')
->times(3)
->returns(new Options);
diff --git a/tests/Sentry/HttpPoolTransportNonCoroutineTest.php b/tests/Sentry/HttpPoolTransportNonCoroutineTest.php
index e2e3244980..a6f13f69b8 100644
--- a/tests/Sentry/HttpPoolTransportNonCoroutineTest.php
+++ b/tests/Sentry/HttpPoolTransportNonCoroutineTest.php
@@ -9,6 +9,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use Sentry\Event;
use Sentry\Options;
use Sentry\Transport\HttpTransport;
@@ -28,7 +29,7 @@ public function testRootCoroutineOwnsAndReleasesTheTransport(): void
->returns(new Result(ResultStatus::success()));
$pool = Double::for(HttpTransportPool::class)->strict();
$pool->expects('borrow')->returns($httpTransport);
- $pool->expects('release')->with($httpTransport);
+ $pool->expects('release')->with(Argument::same($httpTransport));
$transport = new HttpPoolTransport($pool, new Options(['dsn' => 'https://public@example.com/1']));
$event = Event::createEvent();
diff --git a/tests/Sentry/HttpPoolTransportTest.php b/tests/Sentry/HttpPoolTransportTest.php
index 7d193b545f..c039c8c69a 100644
--- a/tests/Sentry/HttpPoolTransportTest.php
+++ b/tests/Sentry/HttpPoolTransportTest.php
@@ -61,7 +61,7 @@ public function testAcceptedSendReturnsItsEventAndReleasesTransportAfterCompleti
$pool->expects('borrow')
->returns($httpTransport);
$pool->expects('release')
- ->with($httpTransport);
+ ->with(Argument::same($httpTransport));
$transport = new HttpPoolTransport($pool, $this->optionsWithDsn());
@@ -117,7 +117,7 @@ static function () use ($started, $finish): Result {
);
$pool = Double::for(HttpTransportPool::class)->strict();
$pool->expects('borrow')->returns($httpTransport);
- $pool->expects('release')->with($httpTransport);
+ $pool->expects('release')->with(Argument::same($httpTransport));
$transport = new HttpPoolTransport($pool, new Options(['spotlight' => true]));
$result = $transport->send(Event::createEvent());
@@ -165,7 +165,7 @@ public function testDeliveryMarkerIsAvailableToChildStartupHooks(): void
->returns(new Result(ResultStatus::success()));
$pool = Double::for(HttpTransportPool::class)->strict();
$pool->expects('borrow')->returns($httpTransport);
- $pool->expects('release')->with($httpTransport);
+ $pool->expects('release')->with(Argument::same($httpTransport));
$transport = new HttpPoolTransport($pool, $this->optionsWithDsn());
$transport->send(Event::createEvent());
@@ -184,7 +184,7 @@ public function testUnexpectedChildFailureDiscardsTransport(): void
$pool->expects('borrow')
->returns($httpTransport);
$pool->expects('discard')
- ->with($httpTransport);
+ ->with(Argument::same($httpTransport));
$transport = new HttpPoolTransport($pool, $this->optionsWithDsn());
@@ -299,7 +299,7 @@ public function testCoroutineCreationFailureBalancesTheGenerationAndReleasesTheT
$pool = Double::for(HttpTransportPool::class)->strict();
$pool->expects('borrow')->returns($httpTransport);
- $pool->expects('release')->with($httpTransport);
+ $pool->expects('release')->with(Argument::same($httpTransport));
$transport = new FailingCoroutineHttpPoolTransport($pool, $this->optionsWithDsn());
$result = $transport->send(Event::createEvent());
@@ -316,7 +316,7 @@ public function testStartupCancellationReleasesAnUntouchedTransport(): void
$httpTransport->expects('send')->never();
$pool = Double::for(HttpTransportPool::class)->strict();
$pool->expects('borrow')->returns($httpTransport);
- $pool->expects('release')->with($httpTransport);
+ $pool->expects('release')->with(Argument::same($httpTransport));
$pool->expects('discard')->never();
$transport = new HttpPoolTransport($pool, $this->optionsWithDsn());
$hookFailure = new RuntimeException('The startup hook failed.');
@@ -325,7 +325,7 @@ public function testStartupCancellationReleasesAnUntouchedTransport(): void
$childCoroutineId = null;
$handler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
diff --git a/tests/Sentry/WebSocketRuntimeContextTest.php b/tests/Sentry/WebSocketRuntimeContextTest.php
index 64e065473c..85f8871119 100644
--- a/tests/Sentry/WebSocketRuntimeContextTest.php
+++ b/tests/Sentry/WebSocketRuntimeContextTest.php
@@ -23,6 +23,7 @@
use Hypervel\WebSocketServer\Server;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use Sentry\EventType;
use Sentry\Logs\Log;
use Sentry\Metrics\Types\Metric;
@@ -78,6 +79,7 @@ public function testOpeningContextIncludesDeferredOnOpenTelemetry(): void
$route = Double::for(Route::class)->strict();
$route->allows('getControllerClass')->returns(SentryWebSocketRuntimeHandler::class);
$router = Double::for(Router::class)->strict();
+ $router->allows('gatherRouteMiddleware')->with(Argument::same($route))->returns([]);
$router->expects('dispatchToCallback')
->resolves(static function (HttpRequest $request) use ($route): Response {
$request->setRouteResolver(static fn (): Route => $route);
diff --git a/tests/Server/ServerTest.php b/tests/Server/ServerTest.php
index 77fa78cf34..d5db7bcb38 100644
--- a/tests/Server/ServerTest.php
+++ b/tests/Server/ServerTest.php
@@ -45,7 +45,7 @@ public function testResponseCallbackReportsAnEscapedExceptionAndCompletesTheResp
{
$exception = new RuntimeException('request callback failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception);
+ $handler->expects('report')->with(Argument::same($exception));
$container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with(ExceptionHandler::class)->returns($handler);
$response = Double::for(SwooleResponse::class)->strict();
@@ -80,7 +80,7 @@ public function testResponseCallbackDoesNotCompleteAnUnwritableResponse(): void
{
$exception = new RuntimeException('request callback failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception);
+ $handler->expects('report')->with(Argument::same($exception));
$container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with(ExceptionHandler::class)->returns($handler);
$response = Double::for(SwooleResponse::class)->strict();
@@ -104,7 +104,7 @@ public function testResponseCallbackFallsBackToThePhpErrorLogAndContainsCompleti
$previousErrorLog = ini_set('error_log', $errorLog);
$exception = new RuntimeException('request callback failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception)->throws(new RuntimeException('reporting failed'));
+ $handler->expects('report')->with(Argument::same($exception))->throws(new RuntimeException('reporting failed'));
$container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with(ExceptionHandler::class)->returns($handler);
$response = Double::for(SwooleResponse::class)->strict();
@@ -181,7 +181,7 @@ public function testWorkerDeliveryCallbackReportsAnEscapedException(): void
{
$exception = new RuntimeException('worker delivery callback failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception);
+ $handler->expects('report')->with(Argument::same($exception));
$container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with(ExceptionHandler::class)->returns($handler);
$callback = $this->server($container->instance())->guardedWorkerDeliveryCallback(
@@ -215,7 +215,7 @@ public function testWorkerDeliveryCallbackFallsBackToThePhpErrorLog(): void
$previousErrorLog = ini_set('error_log', $errorLog);
$exception = new RuntimeException('worker delivery callback failed');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception)->throws(new RuntimeException('reporting failed'));
+ $handler->expects('report')->with(Argument::same($exception))->throws(new RuntimeException('reporting failed'));
$container = Double::for(Container::class, override: true)->strict();
$container->expects('make')->with(ExceptionHandler::class)->returns($handler);
$callback = $this->server($container->instance())->guardedWorkerDeliveryCallback(
diff --git a/tests/ServerProcess/AbstractProcessTest.php b/tests/ServerProcess/AbstractProcessTest.php
index f028472af2..7a3b8b941c 100644
--- a/tests/ServerProcess/AbstractProcessTest.php
+++ b/tests/ServerProcess/AbstractProcessTest.php
@@ -387,7 +387,7 @@ public function testTeardownPreservesReporterFailureAfterLaterCleanupFailure():
$dispatcher->expects('dispatch')->with(Argument::type(AfterProcessHandle::class));
$handler = Double::for(ExceptionHandlerContract::class)->strict();
- $handler->expects('report')->with($operationFailure)->throws($reporterFailure);
+ $handler->expects('report')->with(Argument::same($operationFailure))->throws($reporterFailure);
$container = new Container;
$container->instance('events', $dispatcher);
diff --git a/tests/Session/EncryptedSessionStoreTest.php b/tests/Session/EncryptedSessionStoreTest.php
index ab116e0b17..f520b5039a 100644
--- a/tests/Session/EncryptedSessionStoreTest.php
+++ b/tests/Session/EncryptedSessionStoreTest.php
@@ -50,8 +50,8 @@ public function getSession(): EncryptedStore
{
return new EncryptedStore(
$this->getSessionName(),
- Double::for(SessionHandlerInterface::class),
- Double::for(Encrypter::class),
+ Double::for(SessionHandlerInterface::class)->strict(),
+ Double::for(Encrypter::class)->strict(),
$this->getSessionId()
);
}
diff --git a/tests/Session/FileSessionHandlerTest.php b/tests/Session/FileSessionHandlerTest.php
index 7b2a172091..8a747d186f 100644
--- a/tests/Session/FileSessionHandlerTest.php
+++ b/tests/Session/FileSessionHandlerTest.php
@@ -30,7 +30,7 @@ protected function setUp(): void
{
parent::setUp();
- $this->files = Double::for(Filesystem::class);
+ $this->files = Double::for(Filesystem::class)->strict();
$this->sessionHandler = new FileSessionHandler($this->files, '/path/to/sessions', 30);
}
@@ -140,7 +140,7 @@ public function testWriteRejectsFalseAndShortFilesystemWrites(): void
$data = 'session_data';
foreach ([false, strlen($data) - 1] as $written) {
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('put')
->with('/path/to/sessions/session_id', $data, true)
->returns($written);
diff --git a/tests/Session/Middleware/AuthenticateSessionTest.php b/tests/Session/Middleware/AuthenticateSessionTest.php
index eece16784e..0c49358566 100644
--- a/tests/Session/Middleware/AuthenticateSessionTest.php
+++ b/tests/Session/Middleware/AuthenticateSessionTest.php
@@ -22,7 +22,7 @@ class AuthenticateSessionTest extends TestCase
public function testGuardOverrideCanReturnAConcreteGuard(): void
{
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->allows('getAuthPassword')->returns('password-hash');
$request = new Request;
@@ -30,12 +30,12 @@ public function testGuardOverrideCanReturnAConcreteGuard(): void
$session = new Store('name', new ArraySessionHandler(1));
$request->setHypervelSession($session);
- $guard = Double::for(SessionGuard::class);
+ $guard = Double::for(SessionGuard::class)->strict();
$guard->expects('viaRemember')->returns(false);
$guard->expects('hashPasswordForCookie')->times(2)->with('password-hash')->returns('password-mac');
$guard->expects('user')->returns(null);
- $authFactory = Double::for(AuthFactory::class);
+ $authFactory = Double::for(AuthFactory::class)->strict();
$authFactory->allows('guard')->returns($guard);
$authFactory->allows('getDefaultDriver')->returns('web');
diff --git a/tests/Session/Middleware/StartSessionTest.php b/tests/Session/Middleware/StartSessionTest.php
index 26c36d800e..6267e3058c 100644
--- a/tests/Session/Middleware/StartSessionTest.php
+++ b/tests/Session/Middleware/StartSessionTest.php
@@ -153,7 +153,7 @@ public function testFailedSessionStartupDoesNotRegisterPersistenceRetry(): void
$session = Double::for(Session::class)->strict();
$middleware = new StartSession($manager, $cache, $exceptionHandler);
- $session->expects('setRequestOnHandler')->with($request);
+ $session->expects('setRequestOnHandler')->with(Argument::same($request));
$session->expects('start')->throws($failure);
$exceptionHandler->expects('afterResponse')->never();
@@ -183,7 +183,7 @@ public function testFailureAfterSuccessfulStartupRegistersPersistenceRetry(): vo
$middleware = new StartSession($manager, $cache, $exceptionHandler);
$afterResponse = null;
- $session->expects('setRequestOnHandler')->with($request);
+ $session->expects('setRequestOnHandler')->with(Argument::same($request));
$session->expects('start')->returns(true);
$session->expects('isReadOnly')->returns(false);
$manager->expects('getSessionConfig')->returns([
@@ -222,7 +222,7 @@ public function testPersistenceRetryFailureDoesNotReplacePrimaryFailure(): void
$middleware = new StartSession($manager, $cache, $exceptionHandler);
$afterResponse = null;
- $session->expects('setRequestOnHandler')->with($request);
+ $session->expects('setRequestOnHandler')->with(Argument::same($request));
$session->expects('start')->returns(true);
$session->expects('isReadOnly')->times(2)->returns(false);
$manager->expects('getSessionConfig')->times(2)->returns([
diff --git a/tests/Session/RedisSessionHandlerTest.php b/tests/Session/RedisSessionHandlerTest.php
index 4b298ea58e..52b75179a0 100644
--- a/tests/Session/RedisSessionHandlerTest.php
+++ b/tests/Session/RedisSessionHandlerTest.php
@@ -285,9 +285,10 @@ public function testProviderQualifiedOwnerDigestIsolatesEqualUserIdentifiers():
{
$owners = [];
- foreach (['users', 'admins'] as $authProvider) {
+ $connections = $this->expectConnections(2);
+ foreach (['users', 'admins'] as $index => $authProvider) {
+ $connection = $connections[$index];
$container = $this->authenticatedContainer('1', withRequest: false, authProvider: $authProvider);
- $connection = $this->expectConnection();
$connection->expects('getOption')->with(Redis::OPT_PREFIX)->returns('');
$connection->expects('evalSha')
@@ -348,13 +349,11 @@ public function testClusterWritePreservesSameOwnerMetadataWithOneIndexScript():
$owner = $this->ownerDigest('users', 'user-1');
$expiresAt = CarbonImmutable::now()->getTimestamp() + 600;
$handler = $this->handler(tracked: true);
- $readConnection = $this->expectConnection(cluster: true);
+ [$readConnection, $connection] = $this->expectConnections(2, cluster: true);
$readConnection->expects('get')->returns("\0HVS1{$owner}old");
$this->assertSame('old', $handler->read(self::SESSION_ID));
- $connection = $this->expectConnection(cluster: true);
-
$connection->expects('evalSha')
->ordered()
->with(
@@ -407,13 +406,11 @@ public function testClusterUnresolvedWriteDoesNotRefreshPayloadWhenIndexRefreshF
{
$owner = $this->ownerDigest('users', 'user-1');
$handler = $this->handler(tracked: true);
- $readConnection = $this->expectConnection(cluster: true);
+ [$readConnection, $connection] = $this->expectConnections(2, cluster: true);
$readConnection->expects('get')->returns("\0HVS1{$owner}old");
$this->assertSame('old', $handler->read(self::SESSION_ID));
- $connection = $this->expectConnection(cluster: true);
-
$connection->expects('evalSha')
->with(Argument::type('string'), Argument::satisfies(static fn (array $parameters): bool => $parameters[0] === 'sessions:_users:' . $owner . ':sessions'), 1)
->returns(false);
@@ -479,12 +476,11 @@ public function testClusterUnresolvedWriteRejectsAnOwnerAppearingAfterAnOwnerles
$owner = $this->ownerDigest('users', 'user-1');
$expiresAt = CarbonImmutable::now()->getTimestamp() + 600;
$handler = $this->handler(tracked: true);
- $readConnection = $this->expectConnection(cluster: true);
+ [$readConnection, $racedConnection, $retryConnection] = $this->expectConnections(3, cluster: true);
$readConnection->expects('get')->returns(false);
$this->assertSame('', $handler->read(self::SESSION_ID));
- $racedConnection = $this->expectConnection(cluster: true);
$racedConnection->expects('get')->never();
$racedConnection->expects('hsetex')->never();
$racedConnection->expects('evalSha')
@@ -498,7 +494,6 @@ public function testClusterUnresolvedWriteRejectsAnOwnerAppearingAfterAnOwnerles
$this->assertFalse($handler->write(self::SESSION_ID, 'first'));
- $retryConnection = $this->expectConnection(cluster: true);
$retryConnection->expects('get')->never();
$retryConnection->expects('evalSha')
->ordered()
@@ -524,12 +519,11 @@ public function testClusterUnresolvedWriteRejectsAReassignmentAfterPreIndexingTh
$actualOwner = $this->ownerDigest('users', 'actual-user');
$expiresAt = CarbonImmutable::now()->getTimestamp() + 600;
$handler = new ObservableRedisSessionHandler($this->redis, 'session', 'sessions:', 10, true);
- $readConnection = $this->expectConnection(cluster: true);
+ [$readConnection, $racedConnection, $retryConnection] = $this->expectConnections(3, cluster: true);
$readConnection->expects('get')->returns("\0HVS1{$observedOwner}old");
$this->assertSame('old', $handler->read(self::SESSION_ID));
- $racedConnection = $this->expectConnection(cluster: true);
$racedConnection->expects('get')->never();
$racedConnection->expects('evalSha')
->ordered()
@@ -548,7 +542,6 @@ public function testClusterUnresolvedWriteRejectsAReassignmentAfterPreIndexingTh
$this->assertFalse($handler->write(self::SESSION_ID, 'first'));
$this->assertSame($actualOwner, $handler->observedOwnerForTesting(self::SESSION_ID));
- $retryConnection = $this->expectConnection(cluster: true);
$retryConnection->expects('get')->never();
$retryConnection->expects('evalSha')
->ordered()
@@ -1112,23 +1105,42 @@ private function handler(bool $tracked = false, ?Container $container = null): R
*/
private function expectConnection(bool $cluster = false): (Redis&DoubleInterface)|(RedisCluster&DoubleInterface)
{
- $client = Double::for($cluster ? RedisCluster::class : Redis::class)->strict();
- $client->expects('getOption')->with(Redis::OPT_SERIALIZER)->returns(Redis::SERIALIZER_NONE);
- $client->expects('getOption')->with(Redis::OPT_COMPRESSION)->returns(Redis::COMPRESSION_NONE);
- $client->allows('clearLastError');
- $client->allows('getLastError')->returns(null);
-
- $connection = ($cluster ? new PhpRedisClusterConnectionStub : new PhpRedisConnectionStub)
- ->setActiveConnection($client);
- $proxy = Double::for(RedisProxy::class)->strict();
-
- $this->redis->allows('connection')->with('session')->returns($proxy);
- $proxy->expects('isCluster')->returns($cluster);
- $proxy->expects('withConnection')
- ->with(Argument::type('callable'), false)
- ->resolves(static fn (callable $callback): mixed => $callback($connection));
-
- return $client;
+ return $this->expectConnections(1, $cluster)[0];
+ }
+
+ /**
+ * Expect the session connection lookups in order and return their native client doubles.
+ *
+ * @return list<(DoubleInterface&Redis)|(DoubleInterface&RedisCluster)>
+ */
+ private function expectConnections(int $count, bool $cluster = false): array
+ {
+ $clients = [];
+ $proxies = [];
+
+ for ($i = 0; $i < $count; ++$i) {
+ $client = Double::for($cluster ? RedisCluster::class : Redis::class)->strict();
+ $client->expects('getOption')->with(Redis::OPT_SERIALIZER)->returns(Redis::SERIALIZER_NONE);
+ $client->expects('getOption')->with(Redis::OPT_COMPRESSION)->returns(Redis::COMPRESSION_NONE);
+ $client->allows('clearLastError');
+ $client->allows('getLastError')->returns(null);
+
+ $connection = ($cluster ? new PhpRedisClusterConnectionStub : new PhpRedisConnectionStub)
+ ->setActiveConnection($client);
+ $proxy = Double::for(RedisProxy::class)->strict();
+
+ $proxy->expects('isCluster')->returns($cluster);
+ $proxy->expects('withConnection')
+ ->with(Argument::type('callable'), false)
+ ->resolves(static fn (callable $callback): mixed => $callback($connection));
+
+ $clients[] = $client;
+ $proxies[] = $proxy;
+ }
+
+ $this->redis->expects('connection')->with('session')->times($count)->returns(...$proxies);
+
+ return $clients;
}
/**
diff --git a/tests/Session/SessionManagerTest.php b/tests/Session/SessionManagerTest.php
index 0b105f5cf1..3eecce2b7d 100644
--- a/tests/Session/SessionManagerTest.php
+++ b/tests/Session/SessionManagerTest.php
@@ -60,7 +60,7 @@ public function testEnumDefaultDriverIsNormalizedWithoutTreatingZeroAsAbsent():
],
]));
- $manager->extend('0', fn () => Double::for(SessionHandlerInterface::class));
+ $manager->extend('0', fn () => Double::for(SessionHandlerInterface::class)->strict());
$manager->setDefaultDriver(SessionIntegerIdentifier::Zero);
$this->assertSame('0', $manager->getDefaultDriver());
@@ -99,7 +99,7 @@ public function testRedisDriverUsesConfiguredSessionPrefix(): void
'session.track_user_sessions' => false,
'cache.prefix' => 'cache_prefix',
]);
- $container->instance(RedisFactory::class, Double::for(RedisFactory::class));
+ $container->instance(RedisFactory::class, Double::for(RedisFactory::class)->strict());
$sessionStore = (new SessionManager($container))->driver();
$handler = $this->handlerFromStore($sessionStore);
@@ -145,7 +145,7 @@ public function testExplicitSessionConnectionOverridesBothDrivers(): void
'session.prefix' => 'application_session:',
'session.track_user_sessions' => true,
]);
- $redis = Double::for(RedisFactory::class);
+ $redis = Double::for(RedisFactory::class)->strict();
$container->instance(RedisFactory::class, $redis);
$redisSessionStore = (new SessionManager($container))->driver();
@@ -182,7 +182,7 @@ public function testCapabilityProbeReflectsTheConfiguredHandler(): void
'session.prefix' => 'application_session:',
'session.track_user_sessions' => $tracking,
]);
- $container->instance(RedisFactory::class, Double::for(RedisFactory::class));
+ $container->instance(RedisFactory::class, Double::for(RedisFactory::class)->strict());
$this->assertSame(
$tracking,
@@ -228,7 +228,7 @@ public function testForUserExtractsAnAuthenticatableIdentifier(): void
{
$handler = new SessionManagerCapableHandler;
$manager = $this->customManager($handler);
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthIdentifier')->returns('user-1');
$manager->forUser($user)->all();
@@ -332,7 +332,7 @@ public function testForUserRejectsEmptyAndInvalidModelIdentifiers(): void
$this->assertSame('The user identifier may not be empty.', $exception->getMessage());
}
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthIdentifier')->returns(null);
$this->expectException(InvalidArgumentException::class);
@@ -360,7 +360,7 @@ public function testForUserRejectsUnsupportedAndDisabledDrivers(): void
'session.prefix' => 'application_session:',
'session.track_user_sessions' => false,
]);
- $container->instance(RedisFactory::class, Double::for(RedisFactory::class));
+ $container->instance(RedisFactory::class, Double::for(RedisFactory::class)->strict());
$disabled = new SessionManager($container);
foreach ([$unsupported, $disabled] as $manager) {
@@ -438,8 +438,8 @@ protected function getContainer(array $config): Container
$container = new Container;
$container->instance(ContainerContract::class, $container);
$container->instance('config', new ConfigRepository($config));
- $container->instance(Encrypter::class, Double::for(Encrypter::class));
- $container->instance('db', Double::for(ConnectionResolverInterface::class));
+ $container->instance(Encrypter::class, Double::for(Encrypter::class)->strict());
+ $container->instance('db', Double::for(ConnectionResolverInterface::class)->strict());
Container::setInstance($container);
diff --git a/tests/Session/SessionStoreTest.php b/tests/Session/SessionStoreTest.php
index 870518fd30..890baadd0a 100644
--- a/tests/Session/SessionStoreTest.php
+++ b/tests/Session/SessionStoreTest.php
@@ -96,7 +96,7 @@ public function testCantSetInvalidId(): void
public function testStoresUseIndependentCoroutineState(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->returns(serialize([]));
$first = new Store('first', $handler, str_repeat('a', 40));
@@ -116,7 +116,7 @@ public function testStoresUseIndependentCoroutineState(): void
public function testConstructionClearsStaleObjectSpecificCoroutineState(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$session = new class('name', $handler, str_repeat('b', 40)) extends Store {
public function __construct(string $name, SessionHandlerInterface $handler, ?string $id = null)
@@ -141,7 +141,7 @@ public function __construct(string $name, SessionHandlerInterface $handler, ?str
public function testStoreLazilyCreatesAnIdInAFreshCoroutine(): void
{
- $session = new Store('name', Double::for(SessionHandlerInterface::class), str_repeat('a', 40));
+ $session = new Store('name', Double::for(SessionHandlerInterface::class)->strict(), str_repeat('a', 40));
[$id] = parallel([
fn (): string => $session->getId(),
@@ -157,7 +157,7 @@ public function testInvalidSerializationFailsBeforeWritingContext(): void
$context = CoroutineContext::captureFrom();
try {
- new Store('name', Double::for(SessionHandlerInterface::class), serialization: 'yaml');
+ new Store('name', Double::for(SessionHandlerInterface::class)->strict(), serialization: 'yaml');
$this->fail('Expected invalid session serialization to be rejected.');
} catch (InvalidArgumentException $exception) {
@@ -320,7 +320,7 @@ public function testSessionIsReSavedWhenNothingHasChangedExceptSessionId(): void
public function testFailedSaveDoesNotPublishAgedFlashDataBeforeRetry(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->returns(serialize([]));
$attempts = 0;
@@ -407,7 +407,7 @@ public function testStartingTheSessionMakesItWritableAgain(): void
public function testReadOnlyIsIsolatedBetweenCoroutines(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->times(2)->returns(serialize([]));
$handler->expects('write')->returns(true);
$session = new Store('name', $handler, $this->getSessionId());
@@ -642,7 +642,7 @@ public function testHandlerNeedsRequest(): void
$session->setRequestOnHandler(new Request);
$session->getHandler()->unused();
- $handler = Double::for(new CookieSessionHandler(new CookieJar, 60, false));
+ $handler = Double::for(new CookieSessionHandler(new CookieJar, 60, false))->strict();
$session = new Store('test', $handler);
$this->assertTrue($session->handlerNeedsRequest());
$handler->expects('setRequest');
@@ -716,7 +716,7 @@ public function testPasswordConfirmedResolvesCurrentGuardWhenNoneGiven(): void
$container = Container::setInstance(new Container);
try {
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->expects('getDefaultDriver')->returns('admin');
$container->instance(AuthFactory::class, $auth);
@@ -811,7 +811,7 @@ public function testKeyHasAny(): void
public function testHasAnyStopsAfterTheFirstPresentKey(): void
{
- $session = new class('name', Double::for(SessionHandlerInterface::class), $this->getSessionId()) extends Store {
+ $session = new class('name', Double::for(SessionHandlerInterface::class)->strict(), $this->getSessionId()) extends Store {
public int $getCalls = 0;
public function get(UnitEnum|string $key, mixed $default = null): mixed
@@ -1085,7 +1085,7 @@ public function testValidationErrorsCanBeSerializedAsJson(): void
public function testFailedJsonSaveKeepsLiveErrorBagAndFlashUntilRetry(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->returns(json_encode([]));
$attempts = 0;
@@ -1131,7 +1131,7 @@ function (string $sessionId, string $data) use (&$attempts, &$payloads): bool {
public function testConsecutiveJsonSavesKeepTheLiveErrorBag(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->returns(json_encode([]));
$handler->expects('write')->times(2)->returns(true);
@@ -1154,7 +1154,7 @@ public function testJsonSessionRoundTripsAtTheMaximumSupportedNestingDepth(): vo
}
$storedPayload = null;
- $writer = Double::for(SessionHandlerInterface::class);
+ $writer = Double::for(SessionHandlerInterface::class)->strict();
$writer->expects('read')->returns('{}');
$writer->expects('write')->resolves(
function (string $sessionId, string $payload) use (&$storedPayload): bool {
@@ -1169,7 +1169,7 @@ function (string $sessionId, string $payload) use (&$storedPayload): bool {
$session->put('nested', $value);
$session->save();
- $reader = Double::for(SessionHandlerInterface::class);
+ $reader = Double::for(SessionHandlerInterface::class)->strict();
$reader->expects('read')->returns($storedPayload);
$restored = new Store('name', $reader, $this->getSessionId(), 'json');
@@ -1186,7 +1186,7 @@ public function testJsonSessionRejectsOneLevelOverTheMaximumNestingDepth(): void
$value = ['value' => $value];
}
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->returns('{}');
$handler->expects('write')->never();
@@ -1201,7 +1201,7 @@ public function testJsonSessionRejectsOneLevelOverTheMaximumNestingDepth(): void
public function testStartingJsonSessionRetainsLiveErrorBagWhenStorageHasNone(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->returns(json_encode([]));
$session = new Store('name', $handler, $this->getSessionId(), 'json');
@@ -1221,7 +1221,7 @@ public function testStartingJsonSessionRetainsLiveErrorBagWhenStorageHasNone():
public function testPersistedJsonErrorBagOverridesLiveErrorBagOnStart(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->returns(json_encode([
'errors' => [
'persisted' => [
@@ -1252,7 +1252,7 @@ public function testPersistedJsonErrorBagOverridesLiveErrorBagOnStart(): void
public function testJsonEncodingFailureLeavesLiveStateUntouched(): void
{
- $handler = Double::for(SessionHandlerInterface::class);
+ $handler = Double::for(SessionHandlerInterface::class)->strict();
$handler->expects('read')->returns(json_encode([]));
$handler->expects('write')->never();
@@ -1420,7 +1420,7 @@ public function getSession(string $serialization = 'php'): Store
{
return new Store(
$this->getSessionName(),
- Double::for(SessionHandlerInterface::class),
+ Double::for(SessionHandlerInterface::class)->strict(),
$this->getSessionId(),
$serialization
);
diff --git a/tests/Signal/SignalManagerListenRollbackTest.php b/tests/Signal/SignalManagerListenRollbackTest.php
index e899fc3329..1780547256 100644
--- a/tests/Signal/SignalManagerListenRollbackTest.php
+++ b/tests/Signal/SignalManagerListenRollbackTest.php
@@ -19,6 +19,7 @@
use Hypervel\Tests\TestCase;
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;
@@ -91,7 +92,7 @@ public function testOwnerCancellationAfterWatcherStartRollsBackTheWatcher(): voi
$childCoroutineId = null;
$exceptionHandler->expects('report')
- ->with($hookFailure)
+ ->with(Argument::same($hookFailure))
->resolves(static function () use ($reportStarted, $releaseReport, &$childCoroutineId): void {
$childCoroutineId = EngineCoroutine::id();
$reportStarted->push(true);
diff --git a/tests/Support/Facades/GrpcTest.php b/tests/Support/Facades/GrpcTest.php
index 8ffbd268a9..d2bf58f785 100644
--- a/tests/Support/Facades/GrpcTest.php
+++ b/tests/Support/Facades/GrpcTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
class GrpcTest extends TestCase
{
@@ -25,7 +26,7 @@ public function testResolvesAndForwardsToThePackageRegistrar(): void
$route = Double::for(Route::class)->strict();
$action = static fn (GPBEmpty $request): GPBEmpty => $request;
$registrar->expects('unary')
- ->with('testing.Service/Call', $action)
+ ->with('testing.Service/Call', Argument::same($action))
->returns($route);
$container->instance(GrpcRouteRegistrar::class, $registrar);
Facade::setFacadeApplication($container);
diff --git a/tests/Support/FailureReporterTest.php b/tests/Support/FailureReporterTest.php
index c4f18627ba..07a18a379f 100644
--- a/tests/Support/FailureReporterTest.php
+++ b/tests/Support/FailureReporterTest.php
@@ -13,6 +13,7 @@
use JMac\Testing\Double;
use JMac\Testing\DoubleInterface;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
use Swoole\Coroutine\CanceledException;
@@ -67,7 +68,7 @@ public function testReportsThroughTheBoundExceptionHandler(): void
Container::setInstance($container);
$exception = new RuntimeException('reported through handler');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception);
+ $handler->expects('report')->with(Argument::same($exception));
$container->instance(ExceptionHandler::class, $handler);
FailureReporter::report($exception);
@@ -91,7 +92,7 @@ public function testHandlerFailureFallsBackWithoutPropagating(): void
Container::setInstance($container);
$exception = new RuntimeException('original cleanup failure');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception)->throws(new RuntimeException('handler failed'));
+ $handler->expects('report')->with(Argument::same($exception))->throws(new RuntimeException('handler failed'));
$container->instance(ExceptionHandler::class, $handler);
$this->routeErrorsToTempFile();
@@ -122,7 +123,7 @@ public function testCancellationFromTheExceptionHandlerIsNotLogged(): void
Container::setInstance($container);
$exception = new RuntimeException('original cleanup failure');
$handler = Double::for(ExceptionHandler::class)->strict();
- $handler->expects('report')->with($exception)->throws(
+ $handler->expects('report')->with(Argument::same($exception))->throws(
new CanceledException('reporting canceled')
);
$container->instance(ExceptionHandler::class, $handler);
@@ -137,7 +138,7 @@ public function testPreferCancellationReportsTheFailureDisplacedByCancellation()
{
$failure = new RuntimeException('displaced failure');
$cancellation = new CanceledException('canceled');
- $this->bindReportingHandler()->expects('report')->with($failure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($failure));
$this->assertSame($cancellation, FailureReporter::preferCancellation($failure, $cancellation));
}
@@ -146,7 +147,7 @@ public function testPreferCancellationKeepsTheFirstFailureAndReportsTheLaterOne(
{
$first = new RuntimeException('first failure');
$later = new RuntimeException('later failure');
- $this->bindReportingHandler()->expects('report')->with($later);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($later));
$this->assertSame($first, FailureReporter::preferCancellation($first, $later));
}
diff --git a/tests/Support/SafeCallerTest.php b/tests/Support/SafeCallerTest.php
index a5591a8994..64224bd853 100644
--- a/tests/Support/SafeCallerTest.php
+++ b/tests/Support/SafeCallerTest.php
@@ -13,6 +13,7 @@
use Hypervel\Tests\TestCase;
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;
@@ -37,7 +38,7 @@ public function testCallReportsExceptionAndReturnsNull(): void
$exception = new RuntimeException('test error');
$handler = Double::for(ExceptionHandlerContract::class)->strict();
- $handler->expects('report')->with($exception);
+ $handler->expects('report')->with(Argument::same($exception));
$container = new Container;
$container->instance(ExceptionHandlerContract::class, $handler);
@@ -75,7 +76,7 @@ public function testCallReturnsDefaultWhenExceptionReportingFails(): void
$exception = new RuntimeException('protected operation failed');
$reportingFailure = new RuntimeException('exception reporting failed');
$handler = Double::for(ExceptionHandlerContract::class)->strict();
- $handler->expects('report')->with($exception)->throws($reportingFailure);
+ $handler->expects('report')->with(Argument::same($exception))->throws($reportingFailure);
$container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('has')->with(ExceptionHandlerContract::class)->returns(true);
$container->expects('make')->with(ExceptionHandlerContract::class)->returns($handler);
@@ -135,7 +136,7 @@ public function testCallPreservesCancellationFromExceptionReporter(bool $wrapped
$defaultCalled = false;
$handler = Double::for(ExceptionHandlerContract::class)->strict();
- $handler->expects('report')->with($failure)->throws($cancellation);
+ $handler->expects('report')->with(Argument::same($failure))->throws($cancellation);
$container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('has')->with(ExceptionHandlerContract::class)->returns(true);
$container->expects('make')->with(ExceptionHandlerContract::class)->returns($handler);
diff --git a/tests/Support/SleepTest.php b/tests/Support/SleepTest.php
index 560d6ce426..49b3a4ca53 100644
--- a/tests/Support/SleepTest.php
+++ b/tests/Support/SleepTest.php
@@ -6,7 +6,6 @@
use Carbon\CarbonInterval;
use DateInterval;
-use Exception;
use Hypervel\Support\Carbon;
use Hypervel\Support\CarbonImmutable;
use Hypervel\Support\Facades\Date;
@@ -641,13 +640,14 @@ public function testItCanRegisterCallbacksToRunInTests(): void
public function testItDoesntRunCallbacksWhenNotFaking(): void
{
- Sleep::whenFakingSleep(function (): never {
- throw new Exception('Should not run without faking.');
+ $called = false;
+ Sleep::whenFakingSleep(function () use (&$called): void {
+ $called = true;
});
Sleep::for(1)->millisecond();
- $this->assertTrue(true);
+ $this->assertFalse($called);
}
public function testItDoesNotSyncCarbon(): void
diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php
index 01f199c86b..fd8d2d5069 100644
--- a/tests/Support/SupportCollectionTest.php
+++ b/tests/Support/SupportCollectionTest.php
@@ -741,9 +741,9 @@ public function testGetArrayableItems($collection): void
#[DataProvider('collectionClassProvider')]
public function testToArrayCallsToArrayOnEachItemInCollection(string $collection): void
{
- $item1 = Double::for(Arrayable::class);
+ $item1 = Double::for(Arrayable::class)->strict();
$item1->expects('toArray')->returns(['foo.array']);
- $item2 = Double::for(Arrayable::class);
+ $item2 = Double::for(Arrayable::class)->strict();
$item2->expects('toArray')->returns(['bar.array']);
$c = new $collection([$item1, $item2]);
$results = $c->toArray();
@@ -766,9 +766,9 @@ public function testLazyReturnsLazyCollection(): void
#[DataProvider('collectionClassProvider')]
public function testJsonSerializeCallsToArrayOrJsonSerializeOnEachItemInCollection(string $collection): void
{
- $item1 = Double::for(JsonSerializable::class);
+ $item1 = Double::for(JsonSerializable::class)->strict();
$item1->expects('jsonSerialize')->returns('foo.json');
- $item2 = Double::for(Arrayable::class);
+ $item2 = Double::for(Arrayable::class)->strict();
$item2->expects('toArray')->returns(['bar.array']);
$c = new $collection([$item1, $item2]);
$results = $c->jsonSerialize();
diff --git a/tests/Support/SupportComposerTest.php b/tests/Support/SupportComposerTest.php
index 134aa22b2e..766f790e98 100644
--- a/tests/Support/SupportComposerTest.php
+++ b/tests/Support/SupportComposerTest.php
@@ -258,10 +258,12 @@ private function mockComposer(array $expectedProcessArguments, bool $customCompo
{
$directory = __DIR__;
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with($directory . '/composer.phar')->returns($customComposerPhar);
- $process = Double::for(Process::class);
+ $process = Double::for(Process::class)->strict();
+ // Symfony stops the process when the double is destroyed.
+ $process->allows('stop')->with(0.0)->returns(0);
$process->expects('run');
$composer = $this->getMockBuilder(Composer::class)
diff --git a/tests/Support/SupportFacadesEventTest.php b/tests/Support/SupportFacadesEventTest.php
index 5af3bf71c7..54b2736413 100644
--- a/tests/Support/SupportFacadesEventTest.php
+++ b/tests/Support/SupportFacadesEventTest.php
@@ -38,7 +38,7 @@ protected function setUp(): void
{
parent::setUp();
- $this->events = Double::for(Dispatcher::class);
+ $this->events = Double::for(Dispatcher::class)->strict();
$this->events->allows('hasListeners')->returns(true);
$container = new Container;
diff --git a/tests/Support/SupportFacadesQueueTest.php b/tests/Support/SupportFacadesQueueTest.php
index 6bf24c35e5..db6c27794b 100644
--- a/tests/Support/SupportFacadesQueueTest.php
+++ b/tests/Support/SupportFacadesQueueTest.php
@@ -31,7 +31,7 @@ protected function setUp(): void
{
parent::setUp();
- $this->queueManager = Double::for(QueueContract::class, QueueInterface::class);
+ $this->queueManager = Double::for(QueueContract::class, QueueInterface::class)->strict();
$container = new Container;
$container->instance('queue', $this->queueManager);
diff --git a/tests/Support/SupportServiceProviderTest.php b/tests/Support/SupportServiceProviderTest.php
index db582fafd8..63713ec2aa 100644
--- a/tests/Support/SupportServiceProviderTest.php
+++ b/tests/Support/SupportServiceProviderTest.php
@@ -464,7 +464,7 @@ public function testMergeableOptionsDefaultsToEmptyArray(): void
public function testMergeConfigFromSkipsWhenConfigIsCached(): void
{
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->allows('configurationIsCached')->returns(true);
$app->expects('make')->with('config')->never();
$app->expects('make')->with(ConfigMutationTracker::class)->never();
@@ -489,7 +489,7 @@ public function testMergeConfigFromRunsWhenConfigIsNotCached(): void
public function testReplaceConfigRecursivelyFromSkipsWhenCached(): void
{
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->allows('configurationIsCached')->returns(true);
$app->expects('make')->with('config')->never();
$app->expects('make')->with(ConfigMutationTracker::class)->never();
@@ -541,7 +541,7 @@ public function testConfigureUsingComputesAgainAgainstTheRebuiltConfiguration():
public function testConfigureUsingSkipsWhenConfigIsCached(): void
{
- $app = Double::for(Application::class, override: true);
+ $app = Double::for(Application::class, override: true)->strict();
$app->allows('configurationIsCached')->returns(true);
$app->expects('make')->with('config')->never();
$app->expects('make')->with(ConfigMutationTracker::class)->never();
@@ -554,7 +554,7 @@ public function testConfigureUsingSkipsWhenConfigIsCached(): void
#[TestWith([true])]
public function testLoadTranslationsFromWithoutNamespace(bool $alreadyResolved): void
{
- $translator = Double::for(Translator::class);
+ $translator = Double::for(Translator::class)->strict();
$translator->expects('addPath')->with(__DIR__ . '/translations');
$this->app->singleton('translator', fn (): Translator => $translator);
@@ -573,7 +573,7 @@ public function testLoadTranslationsFromWithoutNamespace(bool $alreadyResolved):
#[TestWith([true])]
public function testLoadTranslationsFromWithNamespace(bool $alreadyResolved): void
{
- $translator = Double::for(Translator::class);
+ $translator = Double::for(Translator::class)->strict();
$translator->expects('addNamespace')->with('namespace', __DIR__ . '/translations');
$this->app->singleton('translator', fn (): Translator => $translator);
diff --git a/tests/Support/SupportTestingBusFakeTest.php b/tests/Support/SupportTestingBusFakeTest.php
index b1d0fbc8e5..d3e342d456 100644
--- a/tests/Support/SupportTestingBusFakeTest.php
+++ b/tests/Support/SupportTestingBusFakeTest.php
@@ -23,6 +23,7 @@
use Hypervel\Tests\TestCase;
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 PHPUnit\Framework\ExpectationFailedException;
@@ -165,7 +166,7 @@ public static function fakeReturnMethods(): array
public function testFakeDispatchMethodsAcceptDispatchLockOwnership(string $dispatchMethod): void
{
$command = new BusJobStub;
- DispatchLockContext::registerUnique($command, Double::for(Cache::class), null, 'key', 'owner');
+ DispatchLockContext::registerUnique($command, Double::for(Cache::class)->strict(), null, 'key', 'owner');
$this->assertTrue(DispatchLockContext::has($command));
@@ -723,7 +724,7 @@ public function testFakeChainKeepsTheFirstJobsOwnSettings(): void
public function testDispatchingAfterResponsesCanBeToggledOnTheFake(): void
{
- $dispatcher = Double::for(BusDispatcher::class);
+ $dispatcher = Double::for(BusDispatcher::class)->strict();
$dispatcher->expects('withoutDispatchingAfterResponses')->returns($dispatcher);
$dispatcher->expects('withDispatchingAfterResponses')->returns($dispatcher);
@@ -735,15 +736,15 @@ public function testDispatchingAfterResponsesCanBeToggledOnTheFake(): void
public function testAssertDispatchedWithIgnoreClass(): void
{
- $dispatcher = Double::for(QueueingDispatcher::class);
+ $dispatcher = Double::for(QueueingDispatcher::class)->strict();
$job = new BusJobStub;
- $dispatcher->expects('dispatch')->with($job);
- $dispatcher->expects('dispatchNow')->with($job, null);
+ $dispatcher->expects('dispatch')->with(Argument::same($job));
+ $dispatcher->expects('dispatchNow')->with(Argument::same($job), null);
$otherJob = new OtherBusJobStub;
- $dispatcher->expects('dispatch')->never()->with($otherJob);
- $dispatcher->expects('dispatchNow')->never()->with($otherJob, null);
+ $dispatcher->expects('dispatch')->never()->with(Argument::type(OtherBusJobStub::class));
+ $dispatcher->expects('dispatchNow')->never()->with(Argument::type(OtherBusJobStub::class), null);
$fake = new BusFake($dispatcher, OtherBusJobStub::class);
@@ -759,19 +760,19 @@ public function testAssertDispatchedWithIgnoreClass(): void
public function testDispatchedFakingOnlyGivenJobs(): void
{
- $dispatcher = Double::for(QueueingDispatcher::class);
+ $dispatcher = Double::for(QueueingDispatcher::class)->strict();
$job = new BusJobStub;
- $dispatcher->expects('dispatch')->never()->with($job);
- $dispatcher->expects('dispatchNow')->never()->with($job, null);
+ $dispatcher->expects('dispatch')->never()->with(Argument::type(BusJobStub::class));
+ $dispatcher->expects('dispatchNow')->never()->with(Argument::type(BusJobStub::class), null);
$otherJob = new OtherBusJobStub;
- $dispatcher->expects('dispatch')->with($otherJob);
- $dispatcher->expects('dispatchNow')->with($otherJob, null);
+ $dispatcher->expects('dispatch')->with(Argument::same($otherJob));
+ $dispatcher->expects('dispatchNow')->with(Argument::same($otherJob), null);
$thirdJob = new ThirdJob;
- $dispatcher->expects('dispatch')->never()->with($thirdJob);
- $dispatcher->expects('dispatchNow')->never()->with($thirdJob, null);
+ $dispatcher->expects('dispatch')->never()->with(Argument::type(ThirdJob::class));
+ $dispatcher->expects('dispatchNow')->never()->with(Argument::type(ThirdJob::class), null);
$fake = (new BusFake($dispatcher))->except(OtherBusJobStub::class);
@@ -798,7 +799,7 @@ public function testBulkRecordsEachJob(): void
public function testAssertDispatchedWithIgnoreCallback(): void
{
- $dispatcher = Double::for(QueueingDispatcher::class);
+ $dispatcher = Double::for(QueueingDispatcher::class)->strict();
$job = new BusJobStub;
$otherJob = new OtherBusJobStub;
@@ -1020,7 +1021,7 @@ public static function serializeAndRestoreCommandMethodsDataProvider(): array
public function testSerializedCommandAcceptanceUsesOriginalIdentity(): void
{
$command = new BusFakeJobWithSerialization('hello');
- DispatchLockContext::registerUnique($command, Double::for(Cache::class), null, 'key', 'owner');
+ DispatchLockContext::registerUnique($command, Double::for(Cache::class)->strict(), null, 'key', 'owner');
$serializingBusFake = (clone $this->fake)->serializeAndRestore();
$serializingBusFake->dispatch($command);
@@ -1035,7 +1036,7 @@ public function testSerializationFailureRetainsDispatchLockOwnership(): void
{
$exception = new RuntimeException('Serialization failed.');
$command = new BusFakeJobWithFailingSerialization($exception);
- DispatchLockContext::registerUnique($command, Double::for(Cache::class), null, 'key', 'owner');
+ DispatchLockContext::registerUnique($command, Double::for(Cache::class)->strict(), null, 'key', 'owner');
$serializingBusFake = (clone $this->fake)->serializeAndRestore();
try {
diff --git a/tests/Support/SupportTestingMailFakeTest.php b/tests/Support/SupportTestingMailFakeTest.php
index fceed4b2ad..064efd2c3c 100644
--- a/tests/Support/SupportTestingMailFakeTest.php
+++ b/tests/Support/SupportTestingMailFakeTest.php
@@ -578,7 +578,7 @@ public function testSendNowSendsQueueableMailableSynchronouslyWithPendingRecipie
public function testDefaultMailerIsResolvedWhenEachOperationOccurs(): void
{
- $manager = Double::for(MailManager::class);
+ $manager = Double::for(MailManager::class)->strict();
$manager->expects('getDefaultDriver')->times(2)->returns('smtp', 'ses');
$fake = new MailFake($manager);
@@ -695,7 +695,7 @@ public function testNamedPendingRecipientsMatchTheRealMailer(): void
public function testShouldQueueSendResolvesTheDefaultMailerOnce(): void
{
- $manager = Double::for(MailManager::class);
+ $manager = Double::for(MailManager::class)->strict();
$manager->expects('getDefaultDriver')->returns('smtp');
$fake = new MailFake($manager);
$mailable = new QueueableMailableStub;
diff --git a/tests/Support/SupportTestingQueueFakeTest.php b/tests/Support/SupportTestingQueueFakeTest.php
index a90405f46a..87e3f22989 100644
--- a/tests/Support/SupportTestingQueueFakeTest.php
+++ b/tests/Support/SupportTestingQueueFakeTest.php
@@ -86,7 +86,7 @@ public function testAssertPushedWithIgnore(): void
$job = new JobStub;
$queue = new QueueFakeTestRecordingQueue;
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with(null)->returns($queue);
$fake = new QueueFake(new Application, JobToFakeStub::class, $manager);
@@ -510,7 +510,7 @@ public function testItDoesntFakeJobsPassedViaExcept(): void
$job = new JobStub;
$queue = new QueueFakeTestRecordingQueue;
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with(null)->returns($queue);
$fake = (new QueueFake(new Application, [], $manager))->except(JobStub::class);
@@ -617,7 +617,7 @@ public function testItCanInvokeCallbacksBeforeAndAfterPushingDispatchedJobs(): v
$steps = [];
$queue = new QueueFakeTestRecordingQueue;
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with(null)->returns($queue);
$fake = (new QueueFake(new Application, [], $manager))
@@ -1027,11 +1027,11 @@ public function testPushedRaw(): void
public function testPartialFakePreservesDelayOnTheDefaultConnection(): void
{
$job = new JobStub;
- $queue = Double::for(Queue::class);
+ $queue = Double::for(Queue::class)->strict();
$queue->expects('later')
- ->with(10, $job, ['key' => 'value'], 'emails')
+ ->with(10, Argument::same($job), ['key' => 'value'], 'emails')
->returns('job-id');
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with(null)->returns($queue);
$fake = (new QueueFake(new Application, [], $manager))->except(JobStub::class);
@@ -1043,11 +1043,11 @@ public function testPartialFakePreservesDelayOnTheDefaultConnection(): void
public function testPartialFakeUsesTheJobConnectionAndLaterOnPreservesDelay(): void
{
$job = new JobWithConnectionStub;
- $queue = Double::for(Queue::class);
+ $queue = Double::for(Queue::class)->strict();
$queue->expects('later')
- ->with(15, $job, '', 'emails')
+ ->with(15, Argument::same($job), '', 'emails')
->returns('job-id');
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with('redis')->returns($queue);
$fake = (new QueueFake(new Application, [], $manager))->except(JobWithConnectionStub::class);
@@ -1059,9 +1059,9 @@ public function testPartialFakeUsesTheJobConnectionAndLaterOnPreservesDelay(): v
public function testPartialFakeUsesTheJobConnectionAttribute(): void
{
$job = new JobWithConnectionAttributeStub;
- $queue = Double::for(Queue::class);
- $queue->expects('push')->with($job, '', null)->returns('job-id');
- $manager = Double::for(QueueManager::class);
+ $queue = Double::for(Queue::class)->strict();
+ $queue->expects('push')->with(Argument::same($job), '', null)->returns('job-id');
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with('attribute-connection')->returns($queue);
$fake = (new QueueFake(new Application, [], $manager))->except(JobWithConnectionAttributeStub::class);
@@ -1076,9 +1076,9 @@ public function testPartialFakeUsesTheJobConnectionAttribute(): void
public function testSelectedConnectionWinsOverTheJobConnection(QueueNameEnumStub|string $selected, string $expected): void
{
$job = new JobWithConnectionStub;
- $queue = Double::for(Queue::class);
- $queue->expects('push')->with($job, '', 'emails')->returns('job-id');
- $manager = Double::for(QueueManager::class);
+ $queue = Double::for(Queue::class)->strict();
+ $queue->expects('push')->with(Argument::same($job), '', 'emails')->returns('job-id');
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with($expected)->returns($queue);
$fake = (new QueueFake(new Application, [], $manager))->except(JobWithConnectionStub::class);
@@ -1094,9 +1094,9 @@ public function testPartialFakeSendsBusJobsToTheirRoutedConnection(): void
$app->instance('queue.routes', $routes);
$job = new QueuedJobStub;
- $queue = Double::for(Queue::class);
- $queue->expects('push')->with($job, '', null)->returns('job-id');
- $manager = Double::for(QueueManager::class);
+ $queue = Double::for(Queue::class)->strict();
+ $queue->expects('push')->with(Argument::same($job), '', null)->returns('job-id');
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with('routed-connection')->returns($queue);
$fake = (new QueueFake($app, [], $manager))->except(QueuedJobStub::class);
@@ -1107,9 +1107,9 @@ public function testPartialFakeSendsBusJobsToTheirRoutedConnection(): void
public function testPartialFakeSendsQueuedListenersToTheirSelectedConnection(): void
{
- $queue = Double::for(Queue::class);
+ $queue = Double::for(Queue::class)->strict();
$queue->expects('push')->with(Argument::type(CallQueuedListener::class), '', null)->returns('job-id');
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with('listener-connection')->returns($queue);
$fake = (new QueueFake(new Application, [], $manager))->except(CallQueuedListener::class);
@@ -1124,9 +1124,9 @@ public function testPartialFakeSendsQueuedListenersToTheirSelectedConnection():
public function testSelectedConnectionsShareTheFakesHistory(): void
{
- $queue = Double::for(Queue::class);
+ $queue = Double::for(Queue::class)->strict();
$queue->expects('push')->times(2)->returns('job-id');
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with('redis')->returns($queue);
$manager->expects('connection')->with('sqs')->returns($queue);
@@ -1148,10 +1148,10 @@ public function testSelectedConnectionKeepsItsConnectionForBulkJobs(): void
{
$plainJob = new JobWithRuntimeDelayStub;
$delayedJob = (new JobWithRuntimeDelayStub)->delay(10);
- $queue = Double::for(Queue::class);
- $queue->expects('push')->with($plainJob, '', 'emails')->returns('plain-id');
- $queue->expects('later')->with(10, $delayedJob, '', 'emails')->returns('delayed-id');
- $manager = Double::for(QueueManager::class);
+ $queue = Double::for(Queue::class)->strict();
+ $queue->expects('push')->with(Argument::same($plainJob), '', 'emails')->returns('plain-id');
+ $queue->expects('later')->with(10, Argument::same($delayedJob), '', 'emails')->returns('delayed-id');
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->times(2)->with('redis')->returns($queue);
$fake = (new QueueFake(new Application, [], $manager))->except(JobWithRuntimeDelayStub::class);
@@ -1195,9 +1195,9 @@ public function testBeforeCallbackFailurePreventsPublicationAndAfterCallbacks():
public function testPassThroughFailureDoesNotRunAfterCallbacks(): void
{
$job = new JobStub;
- $queue = Double::for(Queue::class);
+ $queue = Double::for(Queue::class)->strict();
$queue->expects('push')->throws(new RuntimeException('push failed'));
- $manager = Double::for(QueueManager::class);
+ $manager = Double::for(QueueManager::class)->strict();
$manager->expects('connection')->with(null)->returns($queue);
$afterCalled = false;
diff --git a/tests/Support/SupportTimeboxTest.php b/tests/Support/SupportTimeboxTest.php
index 0b0cf61cc2..73410c722c 100644
--- a/tests/Support/SupportTimeboxTest.php
+++ b/tests/Support/SupportTimeboxTest.php
@@ -20,11 +20,9 @@ class SupportTimeboxTest extends TestCase
public function testMakeExecutesCallback(): void
{
- $callback = function (): void {
- $this->assertTrue(true);
- };
+ $result = (new Timebox)->call(fn () => 'completed', 0);
- (new Timebox)->call($callback, 0);
+ $this->assertSame('completed', $result);
}
public function testMakeWaitsForMicroseconds(): void
diff --git a/tests/Support/Testing/Fakes/ExceptionHandlerFakeTest.php b/tests/Support/Testing/Fakes/ExceptionHandlerFakeTest.php
index 2ec7663fea..a2e247da05 100644
--- a/tests/Support/Testing/Fakes/ExceptionHandlerFakeTest.php
+++ b/tests/Support/Testing/Fakes/ExceptionHandlerFakeTest.php
@@ -223,7 +223,7 @@ public function testThrowFirstReportedDoesNothingWhenEmpty(): void
Exceptions::throwFirstReported();
- $this->assertTrue(true); // No exception thrown
+ Exceptions::assertNothingReported();
}
public function testSetHandler(): void
diff --git a/tests/Telescope/Jobs/ProcessPendingUpdatesTest.php b/tests/Telescope/Jobs/ProcessPendingUpdatesTest.php
index 26c2175e03..e4247d8e4e 100644
--- a/tests/Telescope/Jobs/ProcessPendingUpdatesTest.php
+++ b/tests/Telescope/Jobs/ProcessPendingUpdatesTest.php
@@ -9,6 +9,7 @@
use Hypervel\Telescope\Jobs\ProcessPendingUpdates;
use Hypervel\Tests\Telescope\FeatureTestCase;
use JMac\Testing\Double;
+use JMac\Testing\Matching\Argument;
class ProcessPendingUpdatesTest extends FeatureTestCase
{
@@ -26,7 +27,7 @@ public function testPendingUpdates(): void
$repository
->expects('update')
- ->with($pendingUpdates)
+ ->with(Argument::same($pendingUpdates))
->returns($failedUpdates);
(new ProcessPendingUpdates($pendingUpdates))->handle($repository);
@@ -50,7 +51,7 @@ public function testPendingUpdatesMayStayPending(): void
$repository
->expects('update')
- ->with($pendingUpdates)
+ ->with(Argument::same($pendingUpdates))
->returns($failedUpdates);
(new ProcessPendingUpdates($pendingUpdates))->handle($repository);
@@ -76,7 +77,7 @@ public function testPendingUpdatesMayStayPendingOnlyThreeTimes(): void
$repository
->expects('update')
- ->with($pendingUpdates)
+ ->with(Argument::same($pendingUpdates))
->returns($failedUpdates);
(new ProcessPendingUpdates($pendingUpdates, 2))->handle($repository);
@@ -94,7 +95,7 @@ public function testNullableCustomRepositoryResultDoesNotDispatchAnotherUpdate()
$repository = Double::for(EntriesRepository::class)->strict();
$repository->expects('update')
- ->with($pendingUpdates)
+ ->with(Argument::same($pendingUpdates))
->returns(null);
(new ProcessPendingUpdates($pendingUpdates))->handle($repository);
diff --git a/tests/Telescope/Watchers/ScheduleWatcherTest.php b/tests/Telescope/Watchers/ScheduleWatcherTest.php
index 09055c9cba..230cb2049a 100644
--- a/tests/Telescope/Watchers/ScheduleWatcherTest.php
+++ b/tests/Telescope/Watchers/ScheduleWatcherTest.php
@@ -23,6 +23,7 @@
use Hypervel\Testbench\Attributes\WithConfig;
use Hypervel\Tests\Telescope\FeatureTestCase;
use JMac\Testing\Double;
+use JMac\Testing\Matching\Argument;
use RuntimeException;
#[WithConfig('telescope.watchers', [
@@ -288,7 +289,7 @@ protected function makeTask(
$task->allows('wasSkippedDueToOverlapping')->returns($skippedBecauseOverlapping);
$task->expects('getOutput')
->times($outputCalls)
- ->with($this->app)
+ ->with(Argument::same($this->app))
->returns($output ?? $command . ' output');
return $task;
diff --git a/tests/Testbench/Attributes/RequiresDatabaseTest.php b/tests/Testbench/Attributes/RequiresDatabaseTest.php
index be478ed809..96d900b97b 100644
--- a/tests/Testbench/Attributes/RequiresDatabaseTest.php
+++ b/tests/Testbench/Attributes/RequiresDatabaseTest.php
@@ -4,7 +4,6 @@
namespace Hypervel\Tests\Testbench\Attributes;
-use Exception;
use Hypervel\Testbench\Attributes\RequiresDatabase;
use Hypervel\Testbench\Attributes\WithConfig;
use Hypervel\Testbench\TestCase;
@@ -16,49 +15,42 @@ class RequiresDatabaseTest extends TestCase
#[Test]
public function itCanValidateMatchingDatabase(): void
{
- $stub = new RequiresDatabase('sqlite');
-
- $stub->handle($this->app, function (): void {
- throw new Exception;
- });
-
- $this->addToAssertionCount(1);
-
- $stub = new RequiresDatabase(['pgsql', 'sqlite']);
-
- $stub->handle($this->app, function (): void {
- throw new Exception;
- });
-
- $this->addToAssertionCount(1);
+ $actions = [];
+ foreach (['sqlite', ['pgsql', 'sqlite']] as $driver) {
+ (new RequiresDatabase($driver))->handle($this->app, function (string $method) use (&$actions): void {
+ $actions[] = $method;
+ });
+ }
+
+ $this->assertSame([], $actions);
}
#[Test]
public function itCanInvalidateUnmatchedDatabase(): void
{
- $stub = new RequiresDatabase('mysql');
-
- $stub->handle($this->app, function ($method, $parameters): void {
- $this->assertSame('markTestSkipped', $method);
- $this->assertSame(['Requires mysql to be configured for "testing" database connection'], $parameters);
- });
-
- $stub = new RequiresDatabase(['mysql', 'mariadb']);
-
- $stub->handle($this->app, function ($method, $parameters): void {
- $this->assertSame('markTestSkipped', $method);
- $this->assertSame(['Requires [mysql/mariadb] to be configured for "testing" database connection'], $parameters);
- });
+ $actions = [];
+ foreach (['mysql', ['mysql', 'mariadb']] as $driver) {
+ (new RequiresDatabase($driver))->handle($this->app, function (string $method, array $parameters) use (&$actions): void {
+ $actions[] = [$method, $parameters];
+ });
+ }
+
+ $this->assertSame([
+ ['markTestSkipped', ['Requires mysql to be configured for "testing" database connection']],
+ ['markTestSkipped', ['Requires [mysql/mariadb] to be configured for "testing" database connection']],
+ ], $actions);
}
#[Test]
public function itCanInvalidateUnmatchedDatabaseVersion(): void
{
+ $actions = [];
$stub = new RequiresDatabase('sqlite', '<2.0.0');
- $stub->handle($this->app, function ($method, $parameters): void {
- $this->assertSame('markTestSkipped', $method);
- $this->assertSame(['Requires sqlite:<2.0.0 to be configured for "testing" database connection'], $parameters);
+ $stub->handle($this->app, function (string $method, array $parameters) use (&$actions): void {
+ $actions[] = [$method, $parameters];
});
+
+ $this->assertSame([['markTestSkipped', ['Requires sqlite:<2.0.0 to be configured for "testing" database connection']]], $actions);
}
}
diff --git a/tests/Testbench/Attributes/RequiresHypervelTest.php b/tests/Testbench/Attributes/RequiresHypervelTest.php
index 69b79667bf..032a545ad4 100644
--- a/tests/Testbench/Attributes/RequiresHypervelTest.php
+++ b/tests/Testbench/Attributes/RequiresHypervelTest.php
@@ -4,7 +4,6 @@
namespace Hypervel\Tests\Testbench\Attributes;
-use Exception;
use Hypervel\Testbench\Attributes\RequiresHypervel;
use Hypervel\Testbench\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;
@@ -16,13 +15,14 @@ class RequiresHypervelTest extends TestCase
#[DataProvider('compatibleVersionDataProvider')]
public function itCanValidateMatchingHypervelVersions(string $version): void
{
+ $actions = [];
$stub = new RequiresHypervel($version);
- $stub->handle($this->app, function (): void {
- throw new Exception;
+ $stub->handle($this->app, function (string $method, array $parameters) use (&$actions): void {
+ $actions[] = [$method, $parameters];
});
- $this->addToAssertionCount(1);
+ $this->assertSame([], $actions);
}
/**
@@ -38,11 +38,13 @@ public static function compatibleVersionDataProvider(): iterable
#[Test]
public function itCanInvalidateUnmatchedHypervelVersions(): void
{
+ $actions = [];
$stub = new RequiresHypervel('<0.4.0');
- $stub->handle($this->app, function ($method, $parameters): void {
- $this->assertSame('markTestSkipped', $method);
- $this->assertSame(['Requires Hypervel Framework:<0.4.0'], $parameters);
+ $stub->handle($this->app, function (string $method, array $parameters) use (&$actions): void {
+ $actions[] = [$method, $parameters];
});
+
+ $this->assertSame([['markTestSkipped', ['Requires Hypervel Framework:<0.4.0']]], $actions);
}
}
diff --git a/tests/Testbench/CommanderTest.php b/tests/Testbench/CommanderTest.php
index 5c675673f9..351871988b 100644
--- a/tests/Testbench/CommanderTest.php
+++ b/tests/Testbench/CommanderTest.php
@@ -19,6 +19,7 @@
use Hypervel\Tests\Testbench\Fixtures\Providers\MergedConfigServiceProvider;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\RequiresOperatingSystem;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use PHPUnit\Framework\Attributes\Test;
@@ -302,8 +303,8 @@ public function itRendersApplicationThrowablesToTheConsoleErrorOutput(): void
$output->setErrorOutput($errorOutput);
$handler = Double::for(ExceptionHandlerContract::class)->strict();
- $handler->expects('report')->with($exception);
- $handler->expects('renderForConsole')->with($errorOutput, $exception);
+ $handler->expects('report')->with(Argument::same($exception));
+ $handler->expects('renderForConsole')->with(Argument::same($errorOutput), Argument::same($exception));
$this->app->instance(ExceptionHandlerContract::class, $handler);
$commander = new CommanderThrowableHarness([], __DIR__);
@@ -318,7 +319,7 @@ public function itRetainsApplicationThrowableWhenReportingFails(): void
$original = new RuntimeException('Application failure');
$reportingFailure = new RuntimeException('Reporting failure');
$handler = Double::for(ExceptionHandlerContract::class)->strict();
- $handler->expects('report')->with($original)->throws($reportingFailure);
+ $handler->expects('report')->with(Argument::same($original))->throws($reportingFailure);
$handler->expects('renderForConsole')->never();
$this->app->instance(ExceptionHandlerContract::class, $handler);
diff --git a/tests/Testbench/Foundation/Bootstrap/LoadMigrationsFromArrayTest.php b/tests/Testbench/Foundation/Bootstrap/LoadMigrationsFromArrayTest.php
index 752e03d92c..eabc1862cc 100644
--- a/tests/Testbench/Foundation/Bootstrap/LoadMigrationsFromArrayTest.php
+++ b/tests/Testbench/Foundation/Bootstrap/LoadMigrationsFromArrayTest.php
@@ -12,6 +12,7 @@
use InvalidArgumentException;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\Test;
use RuntimeException;
use Workbench\Database\Seeders\TestbenchDatabaseSeeder;
@@ -55,7 +56,7 @@ public function itCanSeedDatabaseAfterRefreshed(): void
$this->instance(TestbenchDatabaseSeeder::class, $seeder = Double::for(TestbenchDatabaseSeeder::class)->strict());
- $seeder->expects('setContainer')->with($this->app)->returns($seeder);
+ $seeder->expects('setContainer')->with(Argument::same($this->app))->returns($seeder);
$seeder->expects('setCommand')->returns($seeder);
$seeder->expects('__invoke');
diff --git a/tests/Testbench/TestbenchTest.php b/tests/Testbench/TestbenchTest.php
index f72a97f491..4bf759d929 100644
--- a/tests/Testbench/TestbenchTest.php
+++ b/tests/Testbench/TestbenchTest.php
@@ -30,7 +30,7 @@ public function itCanHandleCustomQueuePayload(): void
$dispatcher->dispatchToQueue(new CustomPayloadJob);
- $this->addToAssertionCount(1);
+ $this->assertFalse($this->app->bound('one.time.password'));
}
protected function registerCustomQueuePayload(ApplicationContract $app): void
diff --git a/tests/Testing/Concerns/TestDatabasesTest.php b/tests/Testing/Concerns/TestDatabasesTest.php
index 02e26bf40e..53bc6df9a1 100644
--- a/tests/Testing/Concerns/TestDatabasesTest.php
+++ b/tests/Testing/Concerns/TestDatabasesTest.php
@@ -65,7 +65,7 @@ public function testSwitchToDatabaseWithoutUrl(): void
{
$container = Container::getInstance();
- $db = Double::for(DatabaseManager::class);
+ $db = Double::for(DatabaseManager::class)->strict();
$db->expects('purge');
$container->instance('db', $db);
@@ -87,7 +87,7 @@ public function testSwitchToDatabaseWithUrl(
): void {
$container = Container::getInstance();
- $db = Double::for(DatabaseManager::class);
+ $db = Double::for(DatabaseManager::class)->strict();
$db->expects('purge');
$container->instance('db', $db);
@@ -333,7 +333,7 @@ protected function whenNotUsingInMemoryDatabase(
array $configuration = [],
bool $expectsConnectionLookup = true,
): void {
- $db = Double::for(Connection::class);
+ $db = Double::for(Connection::class)->strict();
if ($expectsConnectionLookup) {
$db->allows('getConfig')->with('database')->returns($database);
diff --git a/tests/Testing/TestResponseTest.php b/tests/Testing/TestResponseTest.php
index 329ac0ebeb..b825a64c24 100644
--- a/tests/Testing/TestResponseTest.php
+++ b/tests/Testing/TestResponseTest.php
@@ -3859,7 +3859,7 @@ public function testUnsupportedLoggedContextFallsThroughToJsonErrors(): void
*/
private function makeMockResponse(array $content): TestResponse
{
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
foreach ($content as $method => $value) {
$view->allows($method)->returns($value);
diff --git a/tests/Tinker/TinkerCasterTest.php b/tests/Tinker/TinkerCasterTest.php
index 2728eee95c..f7b9a0b002 100644
--- a/tests/Tinker/TinkerCasterTest.php
+++ b/tests/Tinker/TinkerCasterTest.php
@@ -27,7 +27,8 @@ public function testCanCastCollection(): void
public function testApplicationPropertyErrorsDoNotSuppressLaterValues(): void
{
- $application = Double::for(Application::class, override: true)->strict();
+ // The caster also reads application properties unrelated to this failure.
+ $application = Double::for(Application::class, override: true);
$application->expects('configurationIsCached')->throws(new Error('Unavailable'));
$application->expects('version')->returns('1.0.0');
diff --git a/tests/Translation/TranslationFileLoaderTest.php b/tests/Translation/TranslationFileLoaderTest.php
index a7a3168764..4bcac8654f 100644
--- a/tests/Translation/TranslationFileLoaderTest.php
+++ b/tests/Translation/TranslationFileLoaderTest.php
@@ -19,7 +19,7 @@ class TranslationFileLoaderTest extends TestCase
public function testLoadMethodLoadsTranslationsFromAddedPath(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$loader->addPath(__DIR__ . '/another');
@@ -34,7 +34,7 @@ public function testLoadMethodLoadsTranslationsFromAddedPath(): void
public function testLoadMethodIgnoresLocalesAndGroupsContainingPathTraversal(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->never();
$files->expects('getRequire')->never();
$loader = new FileLoader($files, __DIR__);
@@ -53,7 +53,7 @@ public function testLoadMethodIgnoresLocalesAndGroupsContainingPathTraversal():
public function testLoadMethodAllowsGroupsInSubdirectories(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$files->expects('exists')->with(__DIR__ . '/en/admin/messages.php')->returns(true);
@@ -64,7 +64,7 @@ public function testLoadMethodAllowsGroupsInSubdirectories(): void
public function testLoadMethodHandlesMissingAddedPath(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$loader->addPath(__DIR__ . '/missing');
@@ -78,7 +78,7 @@ public function testLoadMethodHandlesMissingAddedPath(): void
public function testLoadMethodOverwritesExistingKeysFromAddedPath(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$loader->addPath(__DIR__ . '/another');
@@ -93,7 +93,7 @@ public function testLoadMethodOverwritesExistingKeysFromAddedPath(): void
public function testLoadMethodLoadsTranslationsFromMultipleAddedPaths(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$loader->addPath(__DIR__ . '/another');
$loader->addPath(__DIR__ . '/yet-another');
@@ -112,7 +112,7 @@ public function testLoadMethodLoadsTranslationsFromMultipleAddedPaths(): void
public function testLoadMethodWithoutNamespacesProperlyCallsLoader(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$files->expects('exists')->with(__DIR__ . '/en/foo.php')->returns(true);
$files->expects('getRequire')->with(__DIR__ . '/en/foo.php')->returns(['messages']);
@@ -122,7 +122,7 @@ public function testLoadMethodWithoutNamespacesProperlyCallsLoader(): void
public function testLoadMethodWithoutNamespacesProperlyCallsLoaderWithMultiplePaths(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with(__DIR__ . '/en/foo.php')->returns(true);
$files->expects('exists')->with(__DIR__ . '/second/en/foo.php')->returns(true);
$files->expects('getRequire')->with(__DIR__ . '/en/foo.php')->returns(['messages' => 'first']);
@@ -134,7 +134,7 @@ public function testLoadMethodWithoutNamespacesProperlyCallsLoaderWithMultiplePa
public function testLoadMethodWithNamespacesProperlyCallsLoader(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with('bar/en/foo.php')->returns(true);
$files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->returns(false);
$files->expects('getRequire')->with('bar/en/foo.php')->returns(['foo' => 'bar']);
@@ -146,7 +146,7 @@ public function testLoadMethodWithNamespacesProperlyCallsLoader(): void
public function testLoadMethodWithNamespacesProperlyCallsLoaderWithMultiplePaths(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with('test-namespace-dir/en/foo.php')->returns(true);
$files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->returns(false);
$files->expects('exists')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->returns(false);
@@ -159,7 +159,7 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderWithMultiplePaths
public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOverrides(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with('bar/en/foo.php')->returns(true);
$files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->returns(true);
$files->expects('getRequire')->with('bar/en/foo.php')->returns(['foo' => 'bar']);
@@ -172,7 +172,7 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOver
public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOverridesWithMultiplePaths(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with('test-namespace-dir/en/foo.php')->returns(true);
$files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->returns(true);
$files->expects('exists')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->returns(true);
@@ -187,7 +187,7 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOver
public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOverridesWithMultiplePathsWithMissingKey(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with('test-namespace-dir/en/foo.php')->returns(true);
$files->expects('exists')->with(__DIR__ . '/vendor/namespace/en/foo.php')->returns(true);
$files->expects('exists')->with(__DIR__ . '/second/vendor/namespace/en/foo.php')->returns(true);
@@ -203,7 +203,7 @@ public function testLoadMethodWithNamespacesProperlyCallsLoaderAndLoadsLocalOver
#[DataProvider('invalidLocaleProvider')]
public function testInvalidLocalesAreRejectedBeforeFilesystemAccess(string $locale, string $group = 'messages', ?string $namespace = null): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->never();
$files->expects('get')->never();
$files->expects('getRequire')->never();
@@ -237,7 +237,7 @@ public static function invalidLocaleProvider(): array
public function testDotBearingLocalesReachPhpAndJsonTranslationPaths(): void
{
- $loader = new FileLoader($files = Double::for(Filesystem::class), __DIR__);
+ $loader = new FileLoader($files = Double::for(Filesystem::class)->strict(), __DIR__);
$files->expects('exists')->with(__DIR__ . '/en.UTF-8/messages.php')->returns(true);
$files->expects('getRequire')->with(__DIR__ . '/en.UTF-8/messages.php')->returns(['foo' => 'bar']);
@@ -250,7 +250,7 @@ public function testDotBearingLocalesReachPhpAndJsonTranslationPaths(): void
public function testEmptyArraysReturnedWhenFilesDontExist(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with(__DIR__ . '/en/foo.php')->returns(false);
$files->expects('getRequire')->never();
$loader = new FileLoader($files, __DIR__);
@@ -260,7 +260,7 @@ public function testEmptyArraysReturnedWhenFilesDontExist(): void
public function testEmptyArraysReturnedWhenFilesDontExistForNamespacedItems(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('getRequire')->never();
$loader = new FileLoader($files, __DIR__);
@@ -269,7 +269,7 @@ public function testEmptyArraysReturnedWhenFilesDontExistForNamespacedItems(): v
public function testLoadMethodForJSONProperlyCallsLoader(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with(__DIR__ . '/en.json')->returns(true);
$files->expects('get')->with(__DIR__ . '/en.json')->returns('{"foo":"bar"}');
$loader = new FileLoader($files, __DIR__);
@@ -279,7 +279,7 @@ public function testLoadMethodForJSONProperlyCallsLoader(): void
public function testLoadMethodForJsonAcceptsArraysWithNumericKeys(): void
{
- $loader = new FileLoader($files = Double::for(Filesystem::class), __DIR__);
+ $loader = new FileLoader($files = Double::for(Filesystem::class)->strict(), __DIR__);
$files->expects('exists')->with(__DIR__ . '/en.json')->returns(true);
$files->expects('get')->with(__DIR__ . '/en.json')->returns('["first","second"]');
@@ -288,7 +288,7 @@ public function testLoadMethodForJsonAcceptsArraysWithNumericKeys(): void
public function testLoadMethodForJSONProperlyCallsLoaderForMultiplePaths(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$loader->addJsonPath(__DIR__ . '/another');
@@ -302,7 +302,7 @@ public function testLoadMethodForJSONProperlyCallsLoaderForMultiplePaths(): void
public function testLoadMethodForJSONPreservesNumericKeys(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$loader->addJsonPath(__DIR__ . '/another');
@@ -317,7 +317,7 @@ public function testLoadMethodForJSONPreservesNumericKeys(): void
#[DataProvider('invalidJsonRootProvider')]
public function testLoadMethodThrowExceptionWhenProvideInvalidJSON(string $json): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$loader = new FileLoader($files, __DIR__);
$loader->addJsonPath(__DIR__ . '/invalid');
@@ -349,7 +349,7 @@ public static function invalidJsonRootProvider(): array
public function testLoadMethodRejectsScalarJsonTranslationValues(): void
{
- $loader = new FileLoader($files = Double::for(Filesystem::class), __DIR__);
+ $loader = new FileLoader($files = Double::for(Filesystem::class)->strict(), __DIR__);
$files->expects('exists')->with(__DIR__ . '/en.json')->returns(true);
$files->expects('get')->with(__DIR__ . '/en.json')->returns('{"unread":0}');
@@ -363,7 +363,7 @@ public function testLoadMethodRejectsScalarJsonTranslationValues(): void
public function testLoadMethodAllowsNullJsonTranslationValues(): void
{
- $loader = new FileLoader($files = Double::for(Filesystem::class), __DIR__);
+ $loader = new FileLoader($files = Double::for(Filesystem::class)->strict(), __DIR__);
$files->expects('exists')->with(__DIR__ . '/en.json')->returns(true);
$files->expects('get')->with(__DIR__ . '/en.json')->returns('{"untranslated":null}');
@@ -372,7 +372,7 @@ public function testLoadMethodAllowsNullJsonTranslationValues(): void
public function testAllRegisteredNamespaceReturnProperly(): void
{
- $loader = new FileLoader(Double::for(Filesystem::class), __DIR__);
+ $loader = new FileLoader(Double::for(Filesystem::class)->strict(), __DIR__);
$loader->addNamespace('namespace', 'foo');
$loader->addNamespace('namespace2', 'bar');
$this->assertEquals(['namespace' => 'foo', 'namespace2' => 'bar'], $loader->namespaces());
@@ -380,7 +380,7 @@ public function testAllRegisteredNamespaceReturnProperly(): void
public function testAllAddedJsonPathsReturnProperly(): void
{
- $loader = new FileLoader(Double::for(Filesystem::class), __DIR__);
+ $loader = new FileLoader(Double::for(Filesystem::class)->strict(), __DIR__);
$path1 = __DIR__ . '/another';
$path2 = __DIR__ . '/another2';
$loader->addJsonPath($path1);
@@ -390,7 +390,7 @@ public function testAllAddedJsonPathsReturnProperly(): void
public function testAllAddedPathsReturnProperly(): void
{
- $loader = new FileLoader(Double::for(Filesystem::class), __DIR__);
+ $loader = new FileLoader(Double::for(Filesystem::class)->strict(), __DIR__);
$path1 = __DIR__ . '/another';
$path2 = __DIR__ . '/another2';
$loader->addPath($path1);
diff --git a/tests/Translation/TranslationTranslatorTest.php b/tests/Translation/TranslationTranslatorTest.php
index f78dc86a7c..7b6fe86a40 100644
--- a/tests/Translation/TranslationTranslatorTest.php
+++ b/tests/Translation/TranslationTranslatorTest.php
@@ -341,7 +341,7 @@ public function testPendingLinesRemainWhenLoadingFails(): void
{
$exception = new RuntimeException('Unable to load translations.');
$attempts = 0;
- $loader = Double::for(Loader::class);
+ $loader = Double::for(Loader::class)->strict();
$loader->expects('load')->with('en', '*', '*')->returns([]);
$loader->expects('load')->times(2)->with('en', 'messages', '*')->resolves(
static function () use (&$attempts, $exception): array {
@@ -495,7 +495,7 @@ public function testChoiceMethodProperlySelectsLocaleForChoose(): void
]);
$translator = new Translator($loader, 'en');
$translator->setFallback('fr');
- $selector = Double::for(MessageSelector::class);
+ $selector = Double::for(MessageSelector::class)->strict();
$selector->expects('choose')->with('{0} aucun|{1} un|[2,*] :count éléments', 2, 'fr')->returns(':count éléments');
$translator->setSelector($selector);
@@ -571,7 +571,7 @@ public function testGetJsonPreservesFalseyValuesAndHasAgreement(): void
public function testNullJsonTranslationValueIsTreatedAsMissing(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with(__DIR__ . '/en.json')->returns(true);
$files->expects('get')->with(__DIR__ . '/en.json')->returns('{"untranslated":null}');
$files->expects('exists')->with(__DIR__ . '/en/untranslated.php')->returns(false);
@@ -863,7 +863,7 @@ public function testDetermineLocalesUsingMethod(): void
public function testConfiguredInvalidLocaleIsRejectedBeforeFilesystemAccess(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->never();
$this->expectException(InvalidArgumentException::class);
@@ -874,7 +874,7 @@ public function testConfiguredInvalidLocaleIsRejectedBeforeFilesystemAccess(): v
public function testExplicitInvalidLocaleIsRejectedBeforeFilesystemAccess(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->never();
$translator = new Translator(new FileLoader($files, __DIR__), 'en');
@@ -886,7 +886,7 @@ public function testExplicitInvalidLocaleIsRejectedBeforeFilesystemAccess(): voi
public function testInvalidFallbackLocaleIsRejectedBeforeItsFilesystemAccess(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->never();
$translator = new Translator(new FileLoader($files, __DIR__), 'en');
@@ -898,7 +898,7 @@ public function testInvalidFallbackLocaleIsRejectedBeforeItsFilesystemAccess():
public function testInvalidLocaleFromResolverIsRejectedBeforeItsFilesystemAccess(): void
{
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('exists')->with(__DIR__ . '/en.json')->returns(false);
$translator = new Translator(new FileLoader($files, __DIR__), 'en');
$translator->determineLocalesUsing(static fn (array $locales): array => ['en\US']);
@@ -911,7 +911,7 @@ public function testInvalidLocaleFromResolverIsRejectedBeforeItsFilesystemAccess
public function testLocaleSettersRejectInvalidLocaleImmediately(): void
{
- $loader = Double::for(Loader::class);
+ $loader = Double::for(Loader::class)->strict();
$loader->expects('load')->never();
$translator = new Translator($loader, 'en');
@@ -978,7 +978,7 @@ public function testDoubleUnderscoreHelperReturnsNullWhenKeyIsNull(): void
protected function getLoader(): Loader
{
- return Double::for(Loader::class);
+ return Double::for(Loader::class)->strict();
}
protected function missingGroupCount(?MissingTranslationGroups $missingTranslationGroups): int
diff --git a/tests/Validation/ValidationBatchDatabaseCheckerTest.php b/tests/Validation/ValidationBatchDatabaseCheckerTest.php
index aff2cf8c0f..f8a28413ef 100644
--- a/tests/Validation/ValidationBatchDatabaseCheckerTest.php
+++ b/tests/Validation/ValidationBatchDatabaseCheckerTest.php
@@ -35,7 +35,7 @@ public function testUsesTheCompleteQueryShapeAndRetainsCandidateValues(): void
);
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
$presenceVerifier->expects('getExistingValues')
- ->with($query, [1, 2.5])
+ ->with(Argument::same($query), [1, 2.5])
->returns(['1', '2.5']);
$presenceVerifier->expects('getCount')->never();
@@ -65,10 +65,10 @@ public function __toString(): string
$query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions);
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
$presenceVerifier->expects('getExistingValues')
- ->with($query, [1, 2])
+ ->with(Argument::same($query), [1, 2])
->returns(['1', '2']);
$presenceVerifier->expects('getCount')
- ->with($query, Argument::same($stringable))
+ ->with(Argument::same($query), Argument::same($stringable))
->returns(1);
$verifier = BatchDatabaseChecker::buildVerifier($this->batchGroups($query, [[1, 2], 2, $stringable]), $presenceVerifier);
@@ -98,10 +98,10 @@ public function __toString(): string
$candidate = ['safe-in-array', $stringable];
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
$presenceVerifier->expects('getExistingValues')
- ->with($query, ['safe-sibling'])
+ ->with(Argument::same($query), ['safe-sibling'])
->returns(['safe-sibling']);
$presenceVerifier->expects('getMultiCount')
- ->with($query, Argument::same($candidate))
+ ->with(Argument::same($query), Argument::same($candidate))
->returns(1);
$verifier = BatchDatabaseChecker::buildVerifier(
@@ -120,7 +120,7 @@ public function testEqualLookingIntegerAndStringCandidatesShareOneBinding(): voi
$query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions);
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
$presenceVerifier->expects('getExistingValues')
- ->with($query, ['1'])
+ ->with(Argument::same($query), ['1'])
->returns(['1']);
$verifier = BatchDatabaseChecker::buildVerifier(
@@ -147,7 +147,7 @@ public function testChunksLargeValueSetsAndMarksCrossChunkMultiCountsUncertain()
return array_map(strval(...), $chunk);
});
- $presenceVerifier->expects('getMultiCount')->with($query, $values)->returns(1001);
+ $presenceVerifier->expects('getMultiCount')->with(Argument::same($query), $values)->returns(1001);
$verifier = BatchDatabaseChecker::buildVerifier($this->batchGroups($query, $values), $presenceVerifier);
@@ -176,7 +176,7 @@ public function testSoleNonExactDatabaseMatchIsKnownPresentWithoutASecondQuery()
{
$query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions);
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
- $presenceVerifier->expects('getExistingValues')->with($query, ['Case'])->returns(['case']);
+ $presenceVerifier->expects('getExistingValues')->with(Argument::same($query), ['Case'])->returns(['case']);
$verifier = BatchDatabaseChecker::buildVerifier(
$this->batchGroups($query, ['Case']),
@@ -193,10 +193,10 @@ public function testMultipleNonExactMatchesDelegateWithoutRepeatingTheGroupedQue
$query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions);
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
$presenceVerifier->expects('getExistingValues')
- ->with($query, ['Case', 'Other'])
+ ->with(Argument::same($query), ['Case', 'Other'])
->returns(['case', 'other']);
- $presenceVerifier->expects('getCount')->with($query, 'Case')->returns(1);
- $presenceVerifier->expects('getCount')->with($query, 'Other')->returns(1);
+ $presenceVerifier->expects('getCount')->with(Argument::same($query), 'Case')->returns(1);
+ $presenceVerifier->expects('getCount')->with(Argument::same($query), 'Other')->returns(1);
$verifier = BatchDatabaseChecker::buildVerifier(
$this->batchGroups($query, ['Case', 'Other']),
@@ -212,8 +212,8 @@ public function testSecondStageProvesMissesAbsentAfterAnExactHit(): void
{
$query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions);
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
- $presenceVerifier->expects('getExistingValues')->with($query, ['exact', 'missing'])->returns(['exact']);
- $presenceVerifier->expects('getExistingValues')->with($query, ['missing'])->returns([]);
+ $presenceVerifier->expects('getExistingValues')->with(Argument::same($query), ['exact', 'missing'])->returns(['exact']);
+ $presenceVerifier->expects('getExistingValues')->with(Argument::same($query), ['missing'])->returns([]);
$verifier = BatchDatabaseChecker::buildVerifier(
$this->batchGroups($query, ['exact', 'missing']),
@@ -229,9 +229,9 @@ public function testSecondStageExactMatchesBecomeScalarKnownFacts(): void
{
$query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions);
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
- $presenceVerifier->expects('getExistingValues')->with($query, ['exact', 'Case', 'unknown'])->returns(['exact', 'case']);
- $presenceVerifier->expects('getExistingValues')->with($query, ['Case', 'unknown'])->returns(['Case']);
- $presenceVerifier->expects('getCount')->with($query, 'unknown')->returns(0);
+ $presenceVerifier->expects('getExistingValues')->with(Argument::same($query), ['exact', 'Case', 'unknown'])->returns(['exact', 'case']);
+ $presenceVerifier->expects('getExistingValues')->with(Argument::same($query), ['Case', 'unknown'])->returns(['Case']);
+ $presenceVerifier->expects('getCount')->with(Argument::same($query), 'unknown')->returns(0);
$verifier = BatchDatabaseChecker::buildVerifier(
$this->batchGroups($query, ['exact', 'Case', 'unknown']),
@@ -247,7 +247,7 @@ public function testUnsupportedCandidateDoesNotDisableSafeSiblings(): void
{
$query = new PresenceQuery(null, 'users', 'id', new DatabaseConditions);
$presenceVerifier = Double::for(DatabasePresenceVerifier::class)->strict();
- $presenceVerifier->expects('getExistingValues')->with($query, ['safe'])->returns(['safe']);
+ $presenceVerifier->expects('getExistingValues')->with(Argument::same($query), ['safe'])->returns(['safe']);
$verifier = BatchDatabaseChecker::buildVerifier(
$this->batchGroups($query, [[1, new stdClass], false, 'safe']),
diff --git a/tests/Validation/ValidationDatabasePresenceVerifierTest.php b/tests/Validation/ValidationDatabasePresenceVerifierTest.php
index 892b4a4100..1c955b2c24 100644
--- a/tests/Validation/ValidationDatabasePresenceVerifierTest.php
+++ b/tests/Validation/ValidationDatabasePresenceVerifierTest.php
@@ -30,11 +30,11 @@ class ValidationDatabasePresenceVerifierTest extends TestCase
public function testBasicCount(): void
{
- $db = Double::for(ConnectionResolverInterface::class);
+ $db = Double::for(ConnectionResolverInterface::class)->strict();
$verifier = new DatabasePresenceVerifier($db);
- $conn = Double::for(Connection::class);
+ $conn = Double::for(Connection::class)->strict();
$db->expects('connection')->with('connection')->returns($conn);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$conn->expects('table')->with('table')->returns($builder);
$builder->expects('useWritePdo')->returns($builder);
$builder->expects('where')->with('column', '=', 'value')->returns($builder);
@@ -61,11 +61,11 @@ public function testBasicCount(): void
public function testBasicCountWithClosures(): void
{
- $db = Double::for(ConnectionResolverInterface::class);
+ $db = Double::for(ConnectionResolverInterface::class)->strict();
$verifier = new DatabasePresenceVerifier($db);
- $conn = Double::for(Connection::class);
+ $conn = Double::for(Connection::class)->strict();
$db->expects('connection')->with('connection')->returns($conn);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$conn->expects('table')->with('table')->returns($builder);
$builder->expects('useWritePdo')->returns($builder);
$builder->expects('where')->with('column', '=', 'value')->returns($builder);
@@ -98,11 +98,11 @@ public function testBasicCountWithClosures(): void
public function testGetCountWithValidExcludeId(): void
{
- $db = Double::for(ConnectionResolverInterface::class);
+ $db = Double::for(ConnectionResolverInterface::class)->strict();
$verifier = new DatabasePresenceVerifier($db);
- $conn = Double::for(Connection::class);
+ $conn = Double::for(Connection::class)->strict();
$db->expects('connection')->with('connection')->returns($conn);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$conn->expects('table')->with('table')->returns($builder);
$builder->expects('useWritePdo')->returns($builder);
$builder->expects('where')->with('column', '=', 'value')->returns($builder);
@@ -114,11 +114,11 @@ public function testGetCountWithValidExcludeId(): void
public function testIntegersAndBooleansAreComparedAsStrings(): void
{
- $db = Double::for(ConnectionResolverInterface::class);
- $connection = Double::for(Connection::class);
+ $db = Double::for(ConnectionResolverInterface::class)->strict();
+ $connection = Double::for(Connection::class)->strict();
$db->expects('connection')->with('connection')->times(3)->returns($connection);
$verifier = new DatabasePresenceVerifier($db);
- $builder = Double::for(Builder::class);
+ $builder = Double::for(Builder::class)->strict();
$connection->expects('table')->with('table')->times(3)->returns($builder);
$builder->expects('useWritePdo')->times(3)->returns($builder);
$builder->expects('where')->with('column', '=', '0')->returns($builder);
@@ -140,9 +140,9 @@ public function testIntegersAndBooleansAreComparedAsStrings(): void
#[DataProvider('connections')]
public function testGetExistingValuesUsesRequestedConnectionAndReturnsDistinctValues(?string $connection): void
{
- $verifier = new DatabasePresenceVerifier($db = Double::for(ConnectionResolverInterface::class));
- $db->expects('connection')->with($connection)->returns($database = Double::for(Connection::class));
- $database->expects('table')->with('table')->returns($builder = Double::for(Builder::class));
+ $verifier = new DatabasePresenceVerifier($db = Double::for(ConnectionResolverInterface::class)->strict());
+ $db->expects('connection')->with($connection)->returns($database = Double::for(Connection::class)->strict());
+ $database->expects('table')->with('table')->returns($builder = Double::for(Builder::class)->strict());
$builder->expects('useWritePdo')->returns($builder);
$builder->expects('whereIn')->with('column', ['first', 'second'])->returns($builder);
$builder->expects('where')->with('uuid', '<>', 'ignored')->returns($builder);
@@ -170,7 +170,7 @@ public static function connections(): array
public function testNestedValidationCannotChangeTheOuterConnection(): void
{
- $resolver = Double::for(ConnectionResolverInterface::class);
+ $resolver = Double::for(ConnectionResolverInterface::class)->strict();
$verifier = new DatabasePresenceVerifier($resolver);
$translator = new Translator(new ArrayLoader, 'en');
$inner = new Validator($translator, ['email' => 'inner@example.com'], [
@@ -202,8 +202,8 @@ public function queryConditions(): DatabaseConditions
$outer->setPresenceVerifier($verifier);
foreach (['inner' => 1, 'outer' => 0] as $name => $count) {
- $connection = Double::for(Connection::class);
- $builder = Double::for(Builder::class);
+ $connection = Double::for(Connection::class)->strict();
+ $builder = Double::for(Builder::class)->strict();
$resolver->expects('connection')->with($name)->returns($connection);
$connection->expects('table')->with('users')->returns($builder);
$builder->expects('useWritePdo')->returns($builder);
diff --git a/tests/Validation/ValidationExcludeIfTest.php b/tests/Validation/ValidationExcludeIfTest.php
index ce5c778407..7a25861d79 100644
--- a/tests/Validation/ValidationExcludeIfTest.php
+++ b/tests/Validation/ValidationExcludeIfTest.php
@@ -42,11 +42,11 @@ public function testItReturnsStringVersionOfRuleWhenCast(): void
public function testItAcceptsCallableAndBooleanArguments(): void
{
+ $this->expectNotToPerformAssertions();
+
new ExcludeIf(false);
new ExcludeIf(true);
new ExcludeIf(fn (): bool => true);
-
- $this->addToAssertionCount(1);
}
#[DataProvider('dataProviderItRejectsNonCallableNonBooleanArguments')]
diff --git a/tests/Validation/ValidationExcludeUnlessRuleTest.php b/tests/Validation/ValidationExcludeUnlessRuleTest.php
index 74b0e340b3..9b740f1d57 100644
--- a/tests/Validation/ValidationExcludeUnlessRuleTest.php
+++ b/tests/Validation/ValidationExcludeUnlessRuleTest.php
@@ -90,7 +90,7 @@ public function testInvalidConditionThrows(): void
Rule::excludeUnless($condition);
$this->fail('The ExcludeUnless constructor must not accept ' . gettype($condition));
} catch (TypeError) {
- $this->assertTrue(true);
+ $this->addToAssertionCount(1);
}
}
}
diff --git a/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php b/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php
index 709f860c45..e86be2a132 100644
--- a/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php
+++ b/tests/Validation/ValidationPrecomputedPresenceVerifierTest.php
@@ -130,7 +130,7 @@ public function __toString(): string
$presenceQuery = new PresenceQuery(null, 'users', 'id', new DatabaseConditions);
$fallback->expects('getCount')
- ->with($presenceQuery, Argument::same($stringable))
+ ->with(Argument::same($presenceQuery), Argument::same($stringable))
->returns(1);
$verifier = new PrecomputedPresenceVerifier($fallback);
$verifier->addLookup(
@@ -157,22 +157,22 @@ public function testUnknownScalarFallbackCountsAreMemoizedPerQueryShapeAndValue(
$activeQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions(new DatabaseCondition('status', DatabaseConditionOperator::Equals, 'active')));
$fallback->expects('getCount')
- ->with($activeQuery, 'shared')
+ ->with(Argument::same($activeQuery), 'shared')
->returns(1);
$inactiveQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions(new DatabaseCondition('status', DatabaseConditionOperator::Equals, 'inactive')));
$fallback->expects('getCount')
- ->with($inactiveQuery, 'shared')
+ ->with(Argument::same($inactiveQuery), 'shared')
->returns(0);
$adminQuery = new PresenceQuery(null, 'admins', 'email', new DatabaseConditions);
$fallback->expects('getCount')
- ->with($adminQuery, 'shared')
+ ->with(Argument::same($adminQuery), 'shared')
->returns(2);
$unfilteredQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions);
$fallback->expects('getCount')
- ->with($unfilteredQuery, Argument::same('1'))
+ ->with(Argument::same($unfilteredQuery), Argument::same('1'))
->returns(1);
$verifier = new PrecomputedPresenceVerifier($fallback);
@@ -197,13 +197,13 @@ public function testUnregisteredAndUnsupportedScalarShapesDelegateWithoutMemoiza
$unregisteredQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions(new DatabaseCondition('status', DatabaseConditionOperator::Equals, 'active')));
$fallback->expects('getCount')
- ->with($unregisteredQuery, 'unregistered')
+ ->with(Argument::same($unregisteredQuery), 'unregistered')
->times(2)
->returns(1);
$registeredQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions);
$fallback->expects('getCount')
- ->with($registeredQuery, $unsupported)
+ ->with(Argument::same($registeredQuery), $unsupported)
->times(2)
->returns(0);
@@ -221,7 +221,7 @@ public function testConnectionIsPartOfTheLookupAndForwardedToTheFallback(): void
$fallback = Double::for(PresenceVerifierInterface::class)->strict();
$presenceQuery = new PresenceQuery('tenant', 'users', 'email', new DatabaseConditions);
- $fallback->expects('getCount')->with($presenceQuery, 'unknown')->returns(1);
+ $fallback->expects('getCount')->with(Argument::same($presenceQuery), 'unknown')->returns(1);
$verifier = new PrecomputedPresenceVerifier($fallback);
$verifier->addLookup(
@@ -257,7 +257,7 @@ public function testMultiCountUsesKnownPresentOnlyForASoleDistinctInput(): void
$fallback = Double::for(PresenceVerifierInterface::class)->strict();
$presenceQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions);
- $fallback->expects('getMultiCount')->with($presenceQuery, ['case', 'exact'])->returns(1);
+ $fallback->expects('getMultiCount')->with(Argument::same($presenceQuery), ['case', 'exact'])->returns(1);
$verifier = new PrecomputedPresenceVerifier($fallback);
$verifier->addLookup(
self::lookupKey($presenceQuery),
@@ -289,12 +289,12 @@ public function __toString(): string
$fallback = Double::for(PresenceVerifierInterface::class)->strict();
$presenceQuery = new PresenceQuery(null, 'users', 'email', new DatabaseConditions);
- $fallback->expects('getMultiCount')->with($presenceQuery, ['unknown'])->returns(1);
- $fallback->expects('getMultiCount')->with($presenceQuery, [false])->returns(0);
+ $fallback->expects('getMultiCount')->with(Argument::same($presenceQuery), ['unknown'])->returns(1);
+ $fallback->expects('getMultiCount')->with(Argument::same($presenceQuery), [false])->returns(0);
$fallback->expects('getMultiCount')
- ->with($presenceQuery, Argument::same([$stringable]))
+ ->with(Argument::same($presenceQuery), Argument::same([$stringable]))
->returns(1);
- $fallback->expects('getMultiCount')->with($presenceQuery, ['exact'])->returns(1);
+ $fallback->expects('getMultiCount')->with(Argument::same($presenceQuery), ['exact'])->returns(1);
$verifier = new PrecomputedPresenceVerifier($fallback);
$verifier->addLookup(
self::lookupKey($presenceQuery),
@@ -323,7 +323,7 @@ public function __toString(): string
$presenceQuery = new PresenceQuery(null, 'users', 'created_at', new DatabaseConditions);
$fallback->expects('getCount')
- ->with($presenceQuery, $value)
+ ->with(Argument::same($presenceQuery), Argument::same($value))
->returns(1);
$verifier = new PrecomputedPresenceVerifier($fallback);
$verifier->addLookup(self::lookupKey($presenceQuery), [], [], [], true);
diff --git a/tests/Validation/ValidationProhibitedIfTest.php b/tests/Validation/ValidationProhibitedIfTest.php
index 0a48cfb53b..5a36e2698a 100644
--- a/tests/Validation/ValidationProhibitedIfTest.php
+++ b/tests/Validation/ValidationProhibitedIfTest.php
@@ -42,11 +42,11 @@ public function testItReturnsStringVersionOfRuleWhenCast(): void
public function testItAcceptsCallableAndBooleanArguments(): void
{
+ $this->expectNotToPerformAssertions();
+
new ProhibitedIf(false);
new ProhibitedIf(true);
new ProhibitedIf(fn (): bool => true);
-
- $this->addToAssertionCount(1);
}
#[DataProvider('dataProviderItRejectsNonCallableNonBooleanArguments')]
diff --git a/tests/Validation/ValidationProhibitedUnlessRuleTest.php b/tests/Validation/ValidationProhibitedUnlessRuleTest.php
index 034e870f2c..6213bfd2f6 100644
--- a/tests/Validation/ValidationProhibitedUnlessRuleTest.php
+++ b/tests/Validation/ValidationProhibitedUnlessRuleTest.php
@@ -88,7 +88,7 @@ public function testInvalidConditionThrows(): void
Rule::prohibitedUnless($condition);
$this->fail('The ProhibitedUnless constructor must not accept ' . gettype($condition));
} catch (TypeError) {
- $this->assertTrue(true);
+ $this->addToAssertionCount(1);
}
}
}
diff --git a/tests/Validation/ValidationRequiredIfTest.php b/tests/Validation/ValidationRequiredIfTest.php
index 36245cd615..ef72b2b53a 100644
--- a/tests/Validation/ValidationRequiredIfTest.php
+++ b/tests/Validation/ValidationRequiredIfTest.php
@@ -54,7 +54,7 @@ public function testItOnlyCallableAndBooleanAreAcceptableArgumentsOfTheRule(): v
new RequiredIf($condition);
$this->fail('The RequiredIf constructor must not accept ' . gettype($condition));
} catch (TypeError) {
- $this->assertTrue(true);
+ $this->addToAssertionCount(1);
}
}
}
diff --git a/tests/Validation/ValidationRequiredUnlessRuleTest.php b/tests/Validation/ValidationRequiredUnlessRuleTest.php
index 8ecf0389a9..35f1d4091a 100644
--- a/tests/Validation/ValidationRequiredUnlessRuleTest.php
+++ b/tests/Validation/ValidationRequiredUnlessRuleTest.php
@@ -94,7 +94,7 @@ public function testInvalidConditionThrows(): void
Rule::requiredUnless($condition);
$this->fail('The RequiredUnless constructor must not accept ' . gettype($condition));
} catch (TypeError) {
- $this->assertTrue(true);
+ $this->addToAssertionCount(1);
}
}
}
diff --git a/tests/Validation/ValidationValidatorTest.php b/tests/Validation/ValidationValidatorTest.php
index 454badf359..517bac965a 100755
--- a/tests/Validation/ValidationValidatorTest.php
+++ b/tests/Validation/ValidationValidatorTest.php
@@ -1581,14 +1581,14 @@ public function testArrayValidationAcceptsLiteralKeysWhenCalledDirectly(): void
public function testValidateCurrentPassword(): void
{
// Fails when user is not logged in.
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->expects('guest')->returns(true);
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->expects('guard')->returns($guard);
- $hasher = Double::for(Hasher::class);
+ $hasher = Double::for(Hasher::class)->strict();
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('make')->with('auth')->returns($auth);
$container->expects('make')->with('hash')->returns($hasher);
@@ -1602,19 +1602,19 @@ public function testValidateCurrentPassword(): void
$this->assertFalse($v->passes());
// Fails when password is incorrect.
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthPassword');
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->expects('guest')->returns(false);
$guard->expects('user')->returns($user);
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->expects('guard')->returns($guard);
- $hasher = Double::for(Hasher::class);
+ $hasher = Double::for(Hasher::class)->strict();
$hasher->expects('check')->returns(false);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('make')->with('auth')->returns($auth);
$container->expects('make')->with('hash')->returns($hasher);
@@ -1628,19 +1628,19 @@ public function testValidateCurrentPassword(): void
$this->assertFalse($v->passes());
// Succeeds when password is correct.
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthPassword');
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->expects('guest')->returns(false);
$guard->expects('user')->returns($user);
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->expects('guard')->returns($guard);
- $hasher = Double::for(Hasher::class);
+ $hasher = Double::for(Hasher::class)->strict();
$hasher->expects('check')->returns(true);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('make')->with('auth')->returns($auth);
$container->expects('make')->with('hash')->returns($hasher);
@@ -1653,19 +1653,19 @@ public function testValidateCurrentPassword(): void
$this->assertTrue($v->passes());
// We can use a specific guard.
- $user = Double::for(Authenticatable::class);
+ $user = Double::for(Authenticatable::class)->strict();
$user->expects('getAuthPassword');
- $guard = Double::for(Guard::class);
+ $guard = Double::for(Guard::class)->strict();
$guard->expects('guest')->returns(false);
$guard->expects('user')->returns($user);
- $auth = Double::for(AuthFactory::class);
+ $auth = Double::for(AuthFactory::class)->strict();
$auth->expects('guard')->with('custom')->returns($guard);
- $hasher = Double::for(Hasher::class);
+ $hasher = Double::for(Hasher::class)->strict();
$hasher->expects('check')->returns(true);
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$container->expects('make')->with('auth')->returns($auth);
$container->expects('make')->with('hash')->returns($hasher);
@@ -2575,7 +2575,7 @@ public function testFailedFileUploads(string $fileClass): void
// If file is not successfully uploaded validation should fail with a
// 'uploaded' error message instead of the original rule.
- $file = Double::for($fileClass);
+ $file = Double::for($fileClass)->strict();
$file->expects('isValid')->returns(false);
$file->expects('getSize')->never();
$v = new Validator($trans, ['photo' => $file], ['photo' => 'Max:10']);
@@ -2583,7 +2583,7 @@ public function testFailedFileUploads(string $fileClass): void
$this->assertEquals(['validation.uploaded'], $v->errors()->get('photo'));
// Even "required" will not run if the file failed to upload.
- $file = Double::for($fileClass);
+ $file = Double::for($fileClass)->strict();
$file->expects('isValid')->returns(false);
$v = new Validator($trans, ['photo' => $file], ['photo' => 'required']);
$this->assertTrue($v->fails());
@@ -2591,14 +2591,14 @@ public function testFailedFileUploads(string $fileClass): void
// It should only fail with that rule if a validation rule implies it's
// a file. Otherwise it should fail with the regular rule.
- $file = Double::for($fileClass);
+ $file = Double::for($fileClass)->strict();
$file->expects('isValid')->returns(false);
$v = new Validator($trans, ['photo' => $file], ['photo' => 'string']);
$this->assertTrue($v->fails());
$this->assertEquals(['validation.string'], $v->errors()->get('photo'));
// Validation shouldn't continue if a file failed to upload.
- $file = Double::for($fileClass);
+ $file = Double::for($fileClass)->strict();
$file->expects('isValid')->returns(false);
$v = new Validator($trans, ['photo' => $file], ['photo' => 'file|mimes:pdf|min:10']);
$this->assertTrue($v->fails());
@@ -2609,7 +2609,7 @@ public function testFailedFileUploads(string $fileClass): void
#[TestWith([SymfonyUploadedFile::class])]
public function testDirectFileRulesRejectFailedUploads(string $fileClass): void
{
- $file = Double::for($fileClass);
+ $file = Double::for($fileClass)->strict();
$file->expects('isValid')->times(2)->returns(false);
$file->expects('getSize')->never();
$validator = new Validator($this->getArrayTranslator(), [], []);
@@ -5082,37 +5082,37 @@ public function testValidateUnique(): void
{
$trans = $this->getArrayTranslator();
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions)), 'foo')->returns(0);
$v->setPresenceVerifier($mock);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:connection.users']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery('connection', 'users', 'email', new DatabaseConditions)), 'foo')->returns(0);
$v->setPresenceVerifier($mock);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users,email_addr,1']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions, '1', 'id')), 'foo')->returns(1);
$v->setPresenceVerifier($mock);
$this->assertFalse($v->passes());
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users,email_addr,1,id_col']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions, '1', 'id_col')), 'foo')->returns(2);
$v->setPresenceVerifier($mock);
$this->assertFalse($v->passes());
$v = new Validator($trans, ['users' => [['id' => 1, 'email' => 'foo']]], ['users.*.email' => 'Unique:users,email,[users.*.id]']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions, '1', 'id')), 'foo')->returns(1);
$v->setPresenceVerifier($mock);
$this->assertFalse($v->passes());
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Unique:users,email_addr,NULL,id_col,foo,bar']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with(
$this->matchingPresenceQuery(new PresenceQuery(
null,
@@ -5137,7 +5137,7 @@ public function testValidateUniquePreservesNullAndZeroIgnoredIds(): void
['email' => 'foo'],
['email' => [$rule]],
);
- $verifier = Double::for(PresenceVerifierInterface::class);
+ $verifier = Double::for(PresenceVerifierInterface::class)->strict();
$verifier->expects('getCount')
->with($this->matchingPresenceQuery(new PresenceQuery(
null,
@@ -5161,7 +5161,7 @@ public function testValidateUniqueAndExistsSendsCorrectFieldNameToDBWithArrays()
$v = new Validator($trans, [['email' => 'foo', 'type' => 'bar']], [
'*.email' => 'unique:users', '*.type' => 'exists:user_types',
]);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions)), 'foo')->returns(0);
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'user_types', 'type', new DatabaseConditions)), 'bar')->returns(1);
$v->setPresenceVerifier($mock);
@@ -5174,7 +5174,7 @@ public function testValidateUniqueAndExistsSendsCorrectFieldNameToDBWithArrays()
'*.email' => (new Unique('users'))->where($closure),
'*.type' => (new Exists('user_types'))->where($closure),
]);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(
new PresenceQuery(null, 'users', 'email', new DatabaseConditions($closure), null, 'id'),
), 'foo')->returns(0);
@@ -5189,38 +5189,38 @@ public function testValidationExists(): void
{
$trans = $this->getArrayTranslator();
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:users']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions)), 'foo')->returns(1);
$v->setPresenceVerifier($mock);
$this->assertTrue($v->passes());
$trans = $this->getArrayTranslator();
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:users,email,account_id,1,name,taylor']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email', new DatabaseConditions(new DatabaseCondition('account_id', DatabaseConditionOperator::Equals, 1), new DatabaseCondition('name', DatabaseConditionOperator::Equals, 'taylor')))), 'foo')->returns(1);
$v->setPresenceVerifier($mock);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:users,email_addr']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions)), 'foo')->returns(0);
$v->setPresenceVerifier($mock);
$this->assertFalse($v->passes());
$v = new Validator($trans, ['email' => ['foo']], ['email' => 'Exists:users,email_addr']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getMultiCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions)), ['foo'])->returns(0);
$v->setPresenceVerifier($mock);
$this->assertFalse($v->passes());
$v = new Validator($trans, ['email' => 'foo'], ['email' => 'Exists:connection.users']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery('connection', 'users', 'email', new DatabaseConditions)), 'foo')->returns(1);
$v->setPresenceVerifier($mock);
$this->assertTrue($v->passes());
$v = new Validator($trans, ['email' => ['foo', 'foo']], ['email' => 'exists:users,email_addr']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getMultiCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'email_addr', new DatabaseConditions)), ['foo', 'foo'])->returns(1);
$v->setPresenceVerifier($mock);
$this->assertTrue($v->passes());
@@ -5240,7 +5240,7 @@ public function testValidationExists(): void
['status', [PureEnum::one, 'one'], true],
] as [$column, $values, $passes]) {
$validator = new Validator($trans, ['values' => $values], ['values' => [new Exists('records', $column)]]);
- $verifier = Double::for(PresenceVerifierInterface::class);
+ $verifier = Double::for(PresenceVerifierInterface::class)->strict();
$verifier->expects('getMultiCount')
->with($this->matchingPresenceQuery(new PresenceQuery(null, 'records', $column, new DatabaseConditions)), $values)
->returns(1);
@@ -5254,14 +5254,14 @@ public function testValidationExistsIsNotCalledUnnecessarily(): void
{
$trans = $this->getArrayTranslator();
$v = new Validator($trans, ['id' => 'foo'], ['id' => 'Integer|Exists:users,id']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->never();
$v->setPresenceVerifier($mock);
$this->assertFalse($v->passes());
$trans = $this->getArrayTranslator();
$v = new Validator($trans, ['id' => '1'], ['id' => 'Integer|Exists:users,id']);
- $mock = Double::for(PresenceVerifierInterface::class);
+ $mock = Double::for(PresenceVerifierInterface::class)->strict();
$mock->expects('getCount')->with($this->matchingPresenceQuery(new PresenceQuery(null, 'users', 'id', new DatabaseConditions)), '1')->returns(1);
$v->setPresenceVerifier($mock);
$this->assertTrue($v->passes());
@@ -8691,9 +8691,9 @@ public function testCustomReplacersReceiveDecodedFieldPaths(bool $classBased): v
};
if ($classBased) {
- $container = Double::for(ContainerContract::class, override: true);
+ $container = Double::for(ContainerContract::class, override: true)->strict();
$validator->setContainer($container->instance());
- $replacer = Double::for(ClassBasedValidatorStub::class);
+ $replacer = Double::for(ClassBasedValidatorStub::class)->strict();
$container->expects('make')->with('LiteralFieldReplacer')->returns($replacer);
$replacer->expects('replace')->resolves($callback);
$validator->addReplacer('accepted_if', 'LiteralFieldReplacer');
@@ -11565,7 +11565,7 @@ protected function uploadedFile(
*/
protected function getTranslator(): TranslatorContract&DoubleInterface
{
- return Double::for(TranslatorContract::class);
+ return Double::for(TranslatorContract::class)->strict();
}
/**
diff --git a/tests/View/Blade/AbstractBladeTestCase.php b/tests/View/Blade/AbstractBladeTestCase.php
index f97f9e5cb9..36ac34fd15 100644
--- a/tests/View/Blade/AbstractBladeTestCase.php
+++ b/tests/View/Blade/AbstractBladeTestCase.php
@@ -28,6 +28,6 @@ protected function setUp(): void
*/
protected function getFiles(): Filesystem
{
- return Double::for(Filesystem::class);
+ return Double::for(Filesystem::class)->strict();
}
}
diff --git a/tests/View/Blade/BladeComponentTagCompilerTest.php b/tests/View/Blade/BladeComponentTagCompilerTest.php
index 270d852dae..4b03ad2a53 100644
--- a/tests/View/Blade/BladeComponentTagCompilerTest.php
+++ b/tests/View/Blade/BladeComponentTagCompilerTest.php
@@ -167,9 +167,9 @@ public function testBasicComponentParsing(): void
public function testNestedDefaultComponentParsing(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
Container::setInstance($container);
@@ -428,7 +428,7 @@ public function testClassesCanBeFoundByComponents(): void
public function testClassNamesCanBeGuessed(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$app->expects('getNamespace')->returns('App\\');
$container->instance(ApplicationContract::class, $app->instance());
Container::setInstance($container);
@@ -441,7 +441,7 @@ public function testClassNamesCanBeGuessed(): void
public function testClassNamesCanBeGuessedWithNamespaces(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
$app->expects('getNamespace')->returns('App\\');
Container::setInstance($container);
@@ -560,9 +560,9 @@ public function testPairedComponentTags(): void
public function testClasslessComponents(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->returns(true);
@@ -581,9 +581,9 @@ public function testClasslessComponents(): void
public function testClasslessComponentsWithIndexView(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(2)->returns(false, true);
@@ -602,9 +602,9 @@ public function testClasslessComponentsWithIndexView(): void
public function testClasslessComponentsWithComponentView(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(3)->returns(false, false, true);
@@ -623,9 +623,9 @@ public function testClasslessComponentsWithComponentView(): void
public function testPackagesClasslessComponents(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->returns(true);
@@ -644,9 +644,9 @@ public function testPackagesClasslessComponents(): void
public function testClasslessComponentsWithAnonymousComponentNamespace(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(4)->resolves(function (string $arg): bool {
@@ -677,9 +677,9 @@ public function testClasslessComponentsWithAnonymousComponentNamespace(): void
public function testClasslessComponentsWithAnonymousComponentNamespaceWithIndexView(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(5)->resolves(function (string $viewNameBeingCheckedForExistence): bool {
@@ -710,9 +710,9 @@ public function testClasslessComponentsWithAnonymousComponentNamespaceWithIndexV
public function testClasslessComponentsWithAnonymousComponentNamespaceWithComponentView(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(6)->resolves(function (string $viewNameBeingCheckedForExistence): bool {
@@ -743,9 +743,9 @@ public function testClasslessComponentsWithAnonymousComponentNamespaceWithCompon
public function testClasslessComponentsWithAnonymousComponentPath(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(5)->resolves(function (string $arg): bool {
@@ -774,7 +774,7 @@ public function testClasslessComponentsWithAnonymousComponentPath(): void
public function testAnonymousComponentPathGeneratesXxh128PrefixHash(): void
{
$expectedHash = hash('xxh128', 'test-directory');
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$factory->expects('addNamespace')->with($expectedHash, 'test-directory')->returns($factory);
$container = new TestBladeApplication('base_path');
@@ -797,9 +797,9 @@ public function testAnonymousComponentPathGeneratesXxh128PrefixHash(): void
public function testClasslessComponentsWithAnonymousComponentPathComponentName(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(6)->resolves(function (string $arg): bool {
@@ -828,9 +828,9 @@ public function testClasslessComponentsWithAnonymousComponentPathComponentName()
public function testClasslessIndexComponentsWithAnonymousComponentPath(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(4)->resolves(function (string $arg): bool {
@@ -895,9 +895,9 @@ public function testItThrowsAnExceptionForNonExistingAliases(): void
public function testItThrowsAnExceptionForNonExistingClass(): void
{
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$app->expects('getNamespace')->returns('App\\');
$factory->expects('exists')->times(3)->returns(false);
@@ -910,11 +910,11 @@ public function testItThrowsAnExceptionForNonExistingClass(): void
public function testAttributesTreatedAsPropsAreRemovedFromFinalAttributes(): void
{
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$factory->expects('exists')->never();
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
$app->expects('getNamespace')->never();
$container->instance(Factory::class, $factory);
@@ -924,7 +924,7 @@ public function testAttributesTreatedAsPropsAreRemovedFromFinalAttributes(): voi
$attributes = new ComponentAttributeBag(['userId' => 'bar', 'other' => 'ok']);
- $component = Double::for(TestProfileComponent::class);
+ $component = Double::for(TestProfileComponent::class)->strict();
$component->expects('withName')->with('profile')->returns($component);
$component->expects('shouldRender')->returns(true);
$component->expects('resolveView')->returns('');
@@ -933,7 +933,7 @@ public function testAttributesTreatedAsPropsAreRemovedFromFinalAttributes(): voi
Component::resolveComponentsUsing(fn () => $component);
- $__env = Double::for(ViewFactory::class);
+ $__env = Double::for(ViewFactory::class)->strict();
$__env->expects('startComponent');
$__env->expects('renderComponent');
@@ -950,11 +950,11 @@ public function testAttributesTreatedAsPropsAreRemovedFromFinalAttributes(): voi
public function testOriginalAttributesAreRestoredAfterRenderingChildComponentWithProps(): void
{
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$factory->expects('exists')->never();
$container = new Container;
- $app = Double::for(ApplicationContract::class, override: true);
+ $app = Double::for(ApplicationContract::class, override: true)->strict();
$container->instance(ApplicationContract::class, $app->instance());
$app->expects('getNamespace')->never();
$container->instance(Factory::class, $factory);
@@ -964,14 +964,14 @@ public function testOriginalAttributesAreRestoredAfterRenderingChildComponentWit
$attributes = new ComponentAttributeBag(['userId' => 'bar', 'other' => 'ok']);
- $containerComponent = Double::for(TestContainerComponent::class);
+ $containerComponent = Double::for(TestContainerComponent::class)->strict();
$containerComponent->expects('withName')->with('container')->returns($containerComponent);
$containerComponent->expects('shouldRender')->returns(true);
$containerComponent->expects('resolveView')->returns('');
$containerComponent->expects('data')->returns([]);
$containerComponent->expects('withAttributes')->returns($containerComponent);
- $profileComponent = Double::for(TestProfileComponent::class);
+ $profileComponent = Double::for(TestProfileComponent::class)->strict();
$profileComponent->expects('withName')->with('profile')->returns($profileComponent);
$profileComponent->expects('shouldRender')->returns(true);
$profileComponent->expects('resolveView')->returns('');
@@ -983,7 +983,7 @@ public function testOriginalAttributesAreRestoredAfterRenderingChildComponentWit
TestProfileComponent::class => $profileComponent,
});
- $__env = Double::for(ViewFactory::class);
+ $__env = Double::for(ViewFactory::class)->strict();
$__env->expects('startComponent')->times(2);
$__env->expects('renderComponent')->times(2);
@@ -1007,7 +1007,7 @@ public function testOriginalAttributesAreRestoredAfterRenderingChildComponentWit
protected function mockViewFactory(bool $existsSucceeds = true): void
{
$container = new Container;
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$container->instance(Factory::class, $factory);
$container->alias(Factory::class, 'view');
$factory->allows('exists')->returns($existsSucceeds);
diff --git a/tests/View/ComponentTest.php b/tests/View/ComponentTest.php
index 48a38e154e..606bb607aa 100644
--- a/tests/View/ComponentTest.php
+++ b/tests/View/ComponentTest.php
@@ -39,8 +39,8 @@ protected function setUp(): void
{
parent::setUp();
- $this->viewFactory = Double::for(Factory::class);
- $this->config = Double::for(Config::class);
+ $this->viewFactory = Double::for(Factory::class)->strict();
+ $this->config = Double::for(Config::class)->strict();
$this->filesystem = new Filesystem;
$this->compiledPath = ParallelTesting::tempDir('ViewComponentTest');
$this->filesystem->deleteDirectory($this->compiledPath);
@@ -76,7 +76,7 @@ public function testInlineViewsUseAtomicFilesystemPublication(): void
{
$contents = 'Atomically published';
$viewFile = $this->compiledPath . '/' . hash('xxh128', $contents) . '.blade.php';
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('exists')->with($viewFile)->returns(false);
$filesystem->expects('ensureDirectoryExists')->with($this->compiledPath);
@@ -97,7 +97,7 @@ public function testCompleteInlineViewsAreNotRepublished(): void
{
$contents = 'Already published';
$viewFile = $this->compiledPath . '/' . hash('xxh128', $contents) . '.blade.php';
- $filesystem = Double::for(Filesystem::class);
+ $filesystem = Double::for(Filesystem::class)->strict();
$filesystem->expects('exists')->with($viewFile)->returns(true);
$filesystem->expects('size')->with($viewFile)->returns(strlen($contents));
@@ -147,7 +147,7 @@ public function testTruncatedInlineViewsAreReplaced(): void
public function testRegularViewsGetReturnedUsingViewHelper(): void
{
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$this->viewFactory->expects('make')->with('alert', [], [])->returns($view);
$component = new TestRegularViewComponentUsingViewHelper;
@@ -193,7 +193,7 @@ public function render(): ViewContract|Htmlable|Closure|string
public function testRegularViewsGetReturnedUsingViewMethod(): void
{
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$this->viewFactory->expects('make')->with('alert', [], [])->returns($view);
$component = new TestRegularViewComponentUsingViewMethod;
@@ -440,7 +440,7 @@ public function testFactoryGetsSharedBetweenComponents(): void
$this->assertSame($this->viewFactory, $getFactory($regular));
- $replacement = Double::for(Factory::class);
+ $replacement = Double::for(Factory::class)->strict();
Container::getInstance()->instance(FactoryContract::class, $replacement);
$this->assertSame($this->viewFactory, $getFactory($inline));
diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php
index f31db295d1..123f4d83ed 100644
--- a/tests/View/ViewBladeCompilerTest.php
+++ b/tests/View/ViewBladeCompilerTest.php
@@ -667,7 +667,7 @@ public function testAnonymousComponentNamespacesCanBeStored(): void
*/
protected function getFiles(): Filesystem&DoubleInterface
{
- return Double::for(Filesystem::class);
+ return Double::for(Filesystem::class)->strict();
}
}
diff --git a/tests/View/ViewCompilerEngineTest.php b/tests/View/ViewCompilerEngineTest.php
index a17d9f5329..1ab6c8791d 100755
--- a/tests/View/ViewCompilerEngineTest.php
+++ b/tests/View/ViewCompilerEngineTest.php
@@ -62,7 +62,7 @@ public function testCancellationIsNotWrappedAndCompiledPathIsPopped(): void
$path = __DIR__ . '/Fixtures/foo.php';
$compiled = __DIR__ . '/Fixtures/basic.php';
$cancellation = new CanceledException;
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$files->expects('getRequire')->with($compiled, [])->throws($cancellation);
$engine = $this->getEngine($files);
@@ -115,7 +115,7 @@ public function testViewsAreRecompiledWhenCompiledViewIsMissingViaFileNotFoundEx
$compiled = __DIR__ . '/Fixtures/basic.php';
$path = __DIR__ . '/Fixtures/foo.php';
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$engine = $this->getEngine($files);
$calls = 0;
@@ -152,7 +152,7 @@ public function testViewsAreRecompiledWhenCompiledViewIsMissingViaRequireExcepti
$compiled = __DIR__ . '/Fixtures/basic.php';
$path = __DIR__ . '/Fixtures/foo.php';
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$engine = $this->getEngine($files);
$calls = 0;
@@ -189,7 +189,7 @@ public function testViewsAreRecompiledJustOnceWhenCompiledViewIsMissing(): void
$compiled = __DIR__ . '/Fixtures/basic.php';
$path = __DIR__ . '/Fixtures/foo.php';
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$engine = $this->getEngine($files);
$requires = 0;
@@ -226,7 +226,7 @@ public function testViewsAreNotRecompiledOnRegularViewException(): void
$compiled = __DIR__ . '/Fixtures/basic.php';
$path = __DIR__ . '/Fixtures/foo.php';
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$engine = $this->getEngine($files);
$files->expects('getRequire')
@@ -257,7 +257,7 @@ public function testViewsAreNotRecompiledIfTheyWereJustCompiled(): void
$compiled = __DIR__ . '/Fixtures/basic.php';
$path = __DIR__ . '/Fixtures/foo.php';
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$engine = $this->getEngine($files);
$files->expects('getRequire')
@@ -300,7 +300,7 @@ public function testExpiredViewsAreCheckedAndCompiledOnEveryRender(): void
public function testEachCompiledVariantHasItsOwnFreshnessCheck(): void
{
$path = '/views/example.blade.php';
- $files = Double::for(Filesystem::class);
+ $files = Double::for(Filesystem::class)->strict();
$engine = $this->getEngine($files);
$engine->getCompiler()->expects('getCompiledPath')->times(2)->with($path)
@@ -354,6 +354,6 @@ public function testCompiledPathIsPoppedAfterCaughtRenderFailure(): void
*/
protected function getEngine(?Filesystem $filesystem = null): CompilerEngine
{
- return new CompilerEngine(Double::for(CompilerInterface::class), $filesystem ?: new Filesystem);
+ return new CompilerEngine(Double::for(CompilerInterface::class)->strict(), $filesystem ?: new Filesystem);
}
}
diff --git a/tests/View/ViewFactoryTest.php b/tests/View/ViewFactoryTest.php
index 61224756ba..15bafb4cbc 100755
--- a/tests/View/ViewFactoryTest.php
+++ b/tests/View/ViewFactoryTest.php
@@ -41,9 +41,9 @@ class ViewFactoryTest extends TestCase
public function testCloneIsolatesFinderAndSharedEnvironment(): void
{
$factory = new Factory(
- Double::for(EngineResolver::class),
+ Double::for(EngineResolver::class)->strict(),
new FileViewFinder(new Filesystem, [__DIR__ . '/Fixtures']),
- Double::for(DispatcherContract::class)
+ Double::for(DispatcherContract::class)->strict()
);
$clone = clone $factory;
@@ -67,7 +67,7 @@ public function testMakeCreatesNewViewInstanceWithProperPathAndEngine(): void
$factory = $this->getFactory();
$factory->getFinder()->expects('find')->with('view')->returns('path.php');
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$factory->getEngineResolver()->expects('resolve')->with('php')->returns($engine);
$factory->getFinder()->expects('addExtension')->with('php');
$factory->setDispatcher($this->createEventDispatcher());
@@ -118,7 +118,7 @@ public function testFirstCreatesNewViewInstanceWithProperPath(): void
$factory = $this->getFactory();
$factory->getFinder()->expects('find')->times(2)->with('view')->returns('path.php');
$factory->getFinder()->expects('find')->with('bar')->throws(new InvalidArgumentException);
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$factory->getEngineResolver()->expects('resolve')->with('php')->returns($engine);
$factory->getFinder()->expects('addExtension')->with('php');
$factory->setDispatcher($this->createEventDispatcher());
@@ -139,7 +139,7 @@ public function testFirstAcceptsZeroAsAViewName(): void
{
$factory = $this->getFactory();
$factory->getFinder()->expects('find')->times(2)->with('0')->returns('0.php');
- $factory->getEngineResolver()->expects('resolve')->with('php')->returns(Double::for(Engine::class));
+ $factory->getEngineResolver()->expects('resolve')->with('php')->returns(Double::for(Engine::class)->strict());
$factory->getDispatcher()->expects('hasListeners')->with('creating: 0')->returns(false);
$this->assertSame('0', $factory->first(['0'])->name());
@@ -160,9 +160,9 @@ public function testFirstThrowsInvalidArgumentExceptionIfNoneFound(): void
public function testRenderEachCreatesViewForEachItemInArray(): void
{
$factory = Double::for(Factory::class)->passthru(new Factory(...$this->getFactoryArgs()));
- $mockView1 = Double::for(ViewContract::class);
+ $mockView1 = Double::for(ViewContract::class)->strict();
$factory->expects('make')->with('foo', ['key' => 'bar', 'value' => 'baz'])->returns($mockView1);
- $mockView2 = Double::for(ViewContract::class);
+ $mockView2 = Double::for(ViewContract::class)->strict();
$factory->expects('make')->with('foo', ['key' => 'breeze', 'value' => 'boom'])->returns($mockView2);
$mockView1->expects('render')->returns('dayle');
$mockView2->expects('render')->returns('rees');
@@ -175,7 +175,7 @@ public function testRenderEachCreatesViewForEachItemInArray(): void
public function testEmptyViewsCanBeReturnedFromRenderEach(): void
{
$factory = Double::for(Factory::class)->passthru(new Factory(...$this->getFactoryArgs()));
- $mockView = Double::for(ViewContract::class);
+ $mockView = Double::for(ViewContract::class)->strict();
$factory->expects('make')->with('foo')->returns($mockView);
$mockView->expects('render')->returns('empty');
@@ -195,9 +195,9 @@ public function testEnvironmentAddsExtensionWithCustomResolver(): void
};
$factory->getFinder()->expects('addExtension')->with('foo');
- $factory->getEngineResolver()->expects('register')->with('bar', $resolver);
+ $factory->getEngineResolver()->expects('register')->with('bar', Argument::same($resolver));
$factory->getFinder()->expects('find')->with('view')->returns('path.foo');
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$factory->getEngineResolver()->expects('resolve')->with('bar')->returns($engine);
$factory->getDispatcher()->expects('hasListeners')->returns(false);
@@ -247,7 +247,7 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessary(): void
->expects('dispatch')
->with('creating: name', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('name');
$factory->creator('name', fn () => true);
@@ -269,7 +269,7 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessaryUsingNamespaced
->expects('dispatch')
->with('creating: namespaced::my-package-view', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('namespaced::my-package-view');
$factory->creator('namespaced::*', fn () => true);
@@ -295,7 +295,7 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessaryUsingNamespaced
->expects('dispatch')
->with('creating: namespaced::my-package-view', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('namespaced::my-package-view');
$factory->creator(['namespaced::*', 'welcome'], fn () => true);
@@ -317,7 +317,7 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessaryUsingWildcards(
->expects('dispatch')
->with('creating: name', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('name');
$factory->creator('*', fn () => true);
@@ -339,7 +339,7 @@ public function testCallCreatorsDoesDispatchEventsWhenIsNecessaryUsingNormalized
->expects('dispatch')
->with('creating: components/button', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')
->returns('components/button');
@@ -362,7 +362,7 @@ public function testCallComposerDoesDispatchEventsWhenIsNecessary(): void
->expects('dispatch')
->with('composing: name', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('name');
$factory->composer('name', fn () => true);
@@ -384,7 +384,7 @@ public function testCallComposerDoesDispatchEventsWhenIsNecessaryAndUsingTheArra
->expects('dispatch')
->with('composing: name', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('name');
$factory->composer(['name'], fn () => true);
@@ -406,7 +406,7 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingNamespace
->expects('dispatch')
->with('composing: namespaced::my-package-view', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('namespaced::my-package-view');
$factory->composer('namespaced::*', fn () => true);
@@ -431,7 +431,7 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingNamespace
->expects('dispatch')
->with('composing: namespaced::my-package-view', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('namespaced::my-package-view');
$factory->composer(['namespaced::*', 'welcome'], fn () => true);
@@ -453,7 +453,7 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingWildcards
->expects('dispatch')
->with('composing: name', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('name');
$factory->composer('*', fn () => true);
@@ -475,7 +475,7 @@ public function testCallComposersDoesDispatchEventsWhenIsNecessaryUsingNormalize
->expects('dispatch')
->with('composing: components/button', Argument::type('array'));
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('name')->returns('components/button');
$factory->composer('components.button', fn () => true);
@@ -540,8 +540,8 @@ public function testClassCallbacksWithMethods(): void
public function testCallComposerCallsProperEvent(): void
{
$factory = $this->getFactory();
- $view = Double::for(View::class);
- $dispatcher = Double::for(DispatcherContract::class);
+ $view = Double::for(View::class)->strict();
+ $dispatcher = Double::for(DispatcherContract::class)->strict();
$factory->setDispatcher($dispatcher);
$dispatcher->expects('listen')->with('composing: name', Argument::type(Closure::class));
@@ -588,7 +588,7 @@ public function testYieldDefaultIsEscaped(): void
public function testYieldDefaultViewIsNotEscapedTwice(): void
{
$factory = $this->getFactory();
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('render')->returns('hi
<p>already escaped</p>');
$this->assertSame('hi
<p>already escaped</p>', $factory->yieldContent('foo', $view));
}
@@ -599,7 +599,7 @@ public function testExistingSectionDoesNotRenderDefaultView(): void
$factory->getDispatcher()->allows('hasListeners')->returns(false);
$factory->startSection('foo', 'section');
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->allows('get')->resolves(function () use ($factory): string {
$factory->startPush('default');
echo 'unused';
@@ -657,7 +657,7 @@ public function testBasicSectionDefaultIsEscaped(): void
public function testBasicSectionDefaultViewIsNotEscapedTwice(): void
{
$factory = $this->getFactory();
- $view = Double::for(View::class);
+ $view = Double::for(View::class)->strict();
$view->expects('render')->returns('hi
<p>already escaped</p>');
$factory->startSection('foo', $view);
$this->assertSame('hi
<p>already escaped</p>', $factory->getSections()['foo']);
@@ -781,7 +781,7 @@ public function testFlushStateResetsSlots(): void
public function testTranslation(): void
{
$container = new ContainerInstance;
- $translator = Double::for(Translator::class);
+ $translator = Double::for(Translator::class)->strict();
$translator->expects('get')->with('Foo', ['name' => 'taylor'])->returns('Bar');
$container->instance('translator', $translator);
$factory = $this->getFactory();
@@ -927,7 +927,7 @@ public function testMakeWithSlashAndDot(): void
{
$factory = $this->getFactory();
$factory->getFinder()->expects('find')->times(2)->with('foo.bar')->returns('path.php');
- $factory->getEngineResolver()->expects('resolve')->times(2)->with('php')->returns(Double::for(Engine::class));
+ $factory->getEngineResolver()->expects('resolve')->times(2)->with('php')->returns(Double::for(Engine::class)->strict());
$factory->getDispatcher()->expects('hasListeners')->times(2)->returns(false);
$factory->make('foo/bar');
$factory->make('foo.bar');
@@ -937,7 +937,7 @@ public function testNamespacedViewNamesAreNormalizedProperly(): void
{
$factory = $this->getFactory();
$factory->getFinder()->expects('find')->times(2)->with('vendor/package::foo.bar')->returns('path.php');
- $factory->getEngineResolver()->expects('resolve')->times(2)->with('php')->returns(Double::for(Engine::class));
+ $factory->getEngineResolver()->expects('resolve')->times(2)->with('php')->returns(Double::for(Engine::class)->strict());
$factory->getDispatcher()->expects('hasListeners')->times(2)->returns(false);
$factory->make('vendor/package::foo/bar');
$factory->make('vendor/package::foo.bar');
@@ -956,7 +956,7 @@ public function testExceptionsInSectionsAreThrown(): void
{
$this->expectExceptionObject(new ErrorException('section exception message'));
- $engine = new CompilerEngine(Double::for(CompilerInterface::class), new Filesystem);
+ $engine = new CompilerEngine(Double::for(CompilerInterface::class)->strict(), new Filesystem);
$engine->getCompiler()->expects('getCompiledPath')->times(2)->resolves(function (string $path): string {
return $path;
});
@@ -1170,7 +1170,7 @@ public function testFailedRenderFlushesLoopState(): void
$factory = $this->getFactory();
$factory->getDispatcher()->allows('hasListeners')->returns(false);
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->resolves(function () use ($factory): never {
$factory->addLoop([1]);
@@ -1202,9 +1202,9 @@ public function testMacro(): void
protected function getFactory(): Factory
{
return new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- Double::for(DispatcherContract::class)
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ Double::for(DispatcherContract::class)->strict()
);
}
@@ -1216,9 +1216,9 @@ protected function getFactory(): Factory
protected function getFactoryArgs(): array
{
return [
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- Double::for(DispatcherContract::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ Double::for(DispatcherContract::class)->strict(),
];
}
}
diff --git a/tests/View/ViewFileViewFinderTest.php b/tests/View/ViewFileViewFinderTest.php
index c38d77053c..55df5f2dd0 100755
--- a/tests/View/ViewFileViewFinderTest.php
+++ b/tests/View/ViewFileViewFinderTest.php
@@ -182,6 +182,6 @@ public function testNormalizedNamespaceHints(): void
*/
protected function getFinder(): FileViewFinder
{
- return new FileViewFinder(Double::for(Filesystem::class), [__DIR__]);
+ return new FileViewFinder(Double::for(Filesystem::class)->strict(), [__DIR__]);
}
}
diff --git a/tests/View/ViewTest.php b/tests/View/ViewTest.php
index 044c7ffd56..ea8a372778 100755
--- a/tests/View/ViewTest.php
+++ b/tests/View/ViewTest.php
@@ -22,6 +22,7 @@
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 Swoole\Coroutine\CanceledException;
@@ -47,8 +48,8 @@ public function testRenderProperlyRendersView(): void
{
$view = $this->getView(['foo' => 'bar']);
$view->getFactory()->expects('incrementRender')->ordered();
- $view->getFactory()->expects('callComposer')->ordered()->with($view);
- $view->getFactory()->expects('notifyRendering')->ordered()->with($view);
+ $view->getFactory()->expects('callComposer')->ordered()->with(Argument::same($view));
+ $view->getFactory()->expects('notifyRendering')->ordered()->with(Argument::same($view));
$view->getFactory()->expects('notifyRendered')->never();
$view->getFactory()->expects('mergeSharedData')->with(['foo' => 'bar'])->returns(['foo' => 'bar', 'shared' => 'foo']);
$view->getEngine()->expects('get')->with('path', ['foo' => 'bar', 'shared' => 'foo'])->returns('contents');
@@ -70,8 +71,8 @@ public function testRenderPreservesCancellationWhileFlushingFactoryState(): void
$cancellation = new CanceledException;
$view = $this->getView();
$view->getFactory()->expects('incrementRender');
- $view->getFactory()->expects('callComposer')->with($view);
- $view->getFactory()->expects('notifyRendering')->with($view);
+ $view->getFactory()->expects('callComposer')->with(Argument::same($view));
+ $view->getFactory()->expects('notifyRendering')->with(Argument::same($view));
$view->getFactory()->expects('mergeSharedData')->with([])->returns([]);
$view->getEngine()->expects('get')->with('path', [])->throws($cancellation);
$view->getFactory()->expects('flushState');
@@ -89,7 +90,7 @@ public function testRenderHandlingCallbackReturnValues(): void
$view = $this->getView();
$view->getFactory()->expects('incrementRender')->times(4);
$view->getFactory()->expects('callComposer')->times(4);
- $view->getFactory()->expects('notifyRendering')->times(4)->with($view);
+ $view->getFactory()->expects('notifyRendering')->times(4)->with(Argument::same($view));
$view->getFactory()->expects('mergeSharedData')->times(4)->with([])->returns(['shared' => 'foo']);
$view->getEngine()->expects('get')->times(4)->returns('contents');
$view->getFactory()->expects('decrementRender')->times(4);
@@ -115,8 +116,8 @@ public function testRenderHandlingCallbackReturnValues(): void
public function testRenderSectionsReturnsEnvironmentSections(): void
{
$view = new TestView(
- $factory = Double::for(Factory::class),
- Double::for(Engine::class),
+ $factory = Double::for(Factory::class)->strict(),
+ Double::for(Engine::class)->strict(),
'view',
'path',
[],
@@ -132,8 +133,8 @@ public function testSectionsAreNotFlushedWhenNotDoneRendering(): void
{
$view = $this->getView(['foo' => 'bar']);
$view->getFactory()->expects('incrementRender')->times(2);
- $view->getFactory()->expects('callComposer')->times(2)->with($view);
- $view->getFactory()->expects('notifyRendering')->times(2)->with($view);
+ $view->getFactory()->expects('callComposer')->times(2)->with(Argument::same($view));
+ $view->getFactory()->expects('notifyRendering')->times(2)->with(Argument::same($view));
$view->getFactory()->expects('mergeSharedData')->times(2)->with(['foo' => 'bar'])->returns(['foo' => 'bar', 'shared' => 'foo']);
$view->getEngine()->expects('get')->times(2)->with('path', ['foo' => 'bar', 'shared' => 'foo'])->returns('contents');
$view->getFactory()->expects('decrementRender')->times(2);
@@ -230,13 +231,13 @@ public function testViewGatherDataWithRenderable(): void
{
$view = $this->getView();
$view->getFactory()->expects('incrementRender')->ordered();
- $view->getFactory()->expects('callComposer')->ordered()->with($view);
- $view->getFactory()->expects('notifyRendering')->ordered()->with($view);
+ $view->getFactory()->expects('callComposer')->ordered()->with(Argument::same($view));
+ $view->getFactory()->expects('notifyRendering')->ordered()->with(Argument::same($view));
$view->getEngine()->expects('get')->returns('contents');
$view->getFactory()->expects('decrementRender')->ordered();
$view->getFactory()->expects('flushStateIfDoneRendering');
- $view->renderable = Double::for(Renderable::class);
+ $view->renderable = Double::for(Renderable::class)->strict();
$view->renderable->expects('render')->returns('text');
$view->getFactory()->expects('mergeSharedData')->with(['renderable' => $view->renderable])->returns([
'shared' => 'foo',
@@ -249,8 +250,8 @@ public function testViewRenderSections(): void
{
$view = $this->getView();
$view->getFactory()->expects('incrementRender')->ordered();
- $view->getFactory()->expects('callComposer')->ordered()->with($view);
- $view->getFactory()->expects('notifyRendering')->ordered()->with($view);
+ $view->getFactory()->expects('callComposer')->ordered()->with(Argument::same($view));
+ $view->getFactory()->expects('notifyRendering')->ordered()->with(Argument::same($view));
$view->getFactory()->expects('mergeSharedData')->with([])->returns(['shared' => 'foo']);
$view->getEngine()->expects('get')->returns('contents');
$view->getFactory()->expects('decrementRender')->ordered();
@@ -286,9 +287,9 @@ public function testWithErrors(): void
public function testRenderingObserverIsCalled(): void
{
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$observedView = null;
@@ -296,7 +297,7 @@ public function testRenderingObserverIsCalled(): void
$observedView = $view;
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->returns('contents');
$events->allows('hasListeners')->returns(false);
@@ -309,9 +310,9 @@ public function testRenderingObserverIsCalled(): void
public function testRenderingObserversNotClearedByFlushState(): void
{
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$observerCalled = false;
@@ -321,7 +322,7 @@ public function testRenderingObserversNotClearedByFlushState(): void
$factory->flushState();
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->returns('contents');
$events->allows('hasListeners')->returns(false);
@@ -334,9 +335,9 @@ public function testRenderingObserversNotClearedByFlushState(): void
public function testMultipleRenderingObserversAreAllCalled(): void
{
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$order = [];
@@ -347,7 +348,7 @@ public function testMultipleRenderingObserversAreAllCalled(): void
$order[] = 'second';
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->returns('contents');
$events->allows('hasListeners')->returns(false);
@@ -360,9 +361,9 @@ public function testMultipleRenderingObserversAreAllCalled(): void
public function testRenderedObserverRunsAfterEngineAtTheSameRenderDepth(): void
{
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$order = [];
@@ -379,7 +380,7 @@ public function testRenderedObserverRunsAfterEngineAtTheSameRenderDepth(): void
$this->assertFalse($factory->doneRendering());
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->resolves(function () use (&$order): string {
$order[] = 'engine';
@@ -399,9 +400,9 @@ public function testRenderedObserverRunsAfterEngineAtTheSameRenderDepth(): void
public function testRenderSectionsUsesCompletionObservers(): void
{
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$order = [];
@@ -415,7 +416,7 @@ public function testRenderSectionsUsesCompletionObservers(): void
$this->assertNull($exception);
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->resolves(function () use (&$order): string {
$order[] = 'engine';
@@ -434,9 +435,9 @@ public function testRenderingFailureRemainsPrimaryAfterEveryRenderedObserverRuns
$renderingException = new RuntimeException('rendering failed');
$completionException = new RuntimeException('completion failed');
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$observed = [];
@@ -456,7 +457,7 @@ public function testRenderingFailureRemainsPrimaryAfterEveryRenderedObserverRuns
}
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->never();
$events->allows('hasListeners')->returns(false);
$reported = [];
@@ -480,9 +481,9 @@ public function testEngineFailureIsPassedToRenderedObservers(): void
{
$renderingException = new RuntimeException('engine failed');
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$observedException = null;
@@ -490,7 +491,7 @@ public function testEngineFailureIsPassedToRenderedObservers(): void
$observedException = $exception;
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->throws($renderingException);
$events->allows('hasListeners')->returns(false);
@@ -509,9 +510,9 @@ public function testFirstRenderedObserverFailureIsThrownAfterEveryObserverRunsAn
$firstException = new RuntimeException('first completion failed');
$secondException = new RuntimeException('second completion failed');
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$order = [];
@@ -529,10 +530,10 @@ public function testFirstRenderedObserverFailureIsThrownAfterEveryObserverRunsAn
$order[] = 'third';
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->returns('contents');
$events->allows('hasListeners')->returns(false);
- $this->bindReportingHandler()->expects('report')->with($secondException);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($secondException));
try {
(new View($factory, $engine, 'test', 'path'))->render();
@@ -553,9 +554,9 @@ public function testPreRenderCancellationIsPassedToCompletionObserversAndClearsS
$cancellation = new RuntimeException('Render cleanup failed.', previous: $cancellation);
}
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$factory->inject('content', 'value');
@@ -568,7 +569,7 @@ public function testPreRenderCancellationIsPassedToCompletionObserversAndClearsS
$observed = $exception;
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->never();
$events->allows('hasListeners')->returns(false);
@@ -594,9 +595,9 @@ public function testRenderSectionsEngineCancellationIsPassedToCompletionObserver
$cancellation = new RuntimeException('Engine cleanup failed.', previous: $cancellation);
}
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$observed = null;
@@ -604,7 +605,7 @@ public function testRenderSectionsEngineCancellationIsPassedToCompletionObserver
$observed = $exception;
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->throws($cancellation);
$events->allows('hasListeners')->returns(false);
@@ -628,9 +629,9 @@ public function testRenderedObserverCancellationNotifiesRemainingObserversAndRep
$cancellation = new RuntimeException('Observer cleanup failed.', previous: $cancellation);
}
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$order = [];
@@ -645,10 +646,10 @@ public function testRenderedObserverCancellationNotifiesRemainingObserversAndRep
$order[] = 'second';
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->returns('contents');
$events->allows('hasListeners')->returns(false);
- $this->bindReportingHandler()->expects('report')->with($earlierFailure);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($earlierFailure));
try {
(new View($factory, $engine, 'test', 'path'))->render();
@@ -670,9 +671,9 @@ public function testRenderedObserverCancellationSupersedesAndReportsTheRendering
$cancellation = new RuntimeException('Observer cleanup failed.', previous: $cancellation);
}
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$factory->observeRendering(function () use ($renderingException): never {
@@ -684,10 +685,10 @@ public function testRenderedObserverCancellationSupersedesAndReportsTheRendering
throw $cancellation;
});
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->never();
$events->allows('hasListeners')->returns(false);
- $this->bindReportingHandler()->expects('report')->with($renderingException);
+ $this->bindReportingHandler()->expects('report')->with(Argument::same($renderingException));
try {
(new View($factory, $engine, 'test', 'path'))->render();
@@ -700,9 +701,9 @@ public function testRenderedObserverCancellationSupersedesAndReportsTheRendering
public function testRenderedObserversAreNotClearedByFlushState(): void
{
$factory = new Factory(
- Double::for(EngineResolver::class),
- Double::for(ViewFinderInterface::class),
- $events = Double::for(Dispatcher::class),
+ Double::for(EngineResolver::class)->strict(),
+ Double::for(ViewFinderInterface::class)->strict(),
+ $events = Double::for(Dispatcher::class)->strict(),
);
$observerCalled = false;
@@ -711,7 +712,7 @@ public function testRenderedObserversAreNotClearedByFlushState(): void
});
$factory->flushState();
- $engine = Double::for(Engine::class);
+ $engine = Double::for(Engine::class)->strict();
$engine->expects('get')->returns('contents');
$events->allows('hasListeners')->returns(false);
@@ -725,12 +726,12 @@ public function testRenderedObserversAreNotClearedByFlushState(): void
*/
protected function getView(mixed $data = []): View
{
- $factory = Double::for(Factory::class);
+ $factory = Double::for(Factory::class)->strict();
$factory->allows('hasRenderedObservers')->returns(false);
return new View(
$factory,
- Double::for(Engine::class),
+ Double::for(Engine::class)->strict(),
'view',
'path',
$data
@@ -744,7 +745,7 @@ private function bindReportingHandler(): ExceptionHandler&DoubleInterface
{
$container = new Container;
Container::setInstance($container);
- $handler = Double::for(ExceptionHandler::class);
+ $handler = Double::for(ExceptionHandler::class)->strict();
$container->instance(ExceptionHandler::class, $handler);
return $handler;
diff --git a/tests/Watcher/ServerRestartStrategyTest.php b/tests/Watcher/ServerRestartStrategyTest.php
index e1db8913b8..05f03648e6 100644
--- a/tests/Watcher/ServerRestartStrategyTest.php
+++ b/tests/Watcher/ServerRestartStrategyTest.php
@@ -383,7 +383,7 @@ public function testCloseFailureClearsLifecycleOwnershipAndAllowsRetry(): void
{
$failure = new RuntimeException('expected close failure');
$handler = Double::for(ExceptionHandlerContract::class)->strict();
- $handler->expects('report')->with($failure);
+ $handler->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandlerContract::class, $handler);
$strategy = $this->createProbeStrategy();
$strategy->closeFailures = [$failure, null];
@@ -401,7 +401,7 @@ public function testMalformedEnvironmentDuringRestartClearsOwnershipAndAllowsRet
{
$failure = new RuntimeException('malformed environment');
$handler = Double::for(ExceptionHandlerContract::class)->strict();
- $handler->expects('report')->with($failure);
+ $handler->expects('report')->with(Argument::same($failure));
$this->app->instance(ExceptionHandlerContract::class, $handler);
$strategy = $this->createProbeStrategy();
$strategy->reloadFailures = [null, $failure, null];
diff --git a/tests/WebSocketServer/ServerHandshakeTest.php b/tests/WebSocketServer/ServerHandshakeTest.php
index 89463fc167..75411b4c7f 100644
--- a/tests/WebSocketServer/ServerHandshakeTest.php
+++ b/tests/WebSocketServer/ServerHandshakeTest.php
@@ -71,7 +71,7 @@ public function testAcceptedHandshakeTerminatesAfterOpenAndDrainsOnce(string $ou
$container = $this->container($events);
$reporter = Double::for(ExceptionHandler::class)->strict();
if ($outcome === 'failed' || $outcome === 'wrapped') {
- $reporter->expects('report')->with($exception);
+ $reporter->expects('report')->with(Argument::same($exception));
} else {
$reporter->expects('report')->never();
}
@@ -197,7 +197,7 @@ public function testHandledHandshakeExceptionUsesTheRenderedStatusForDeferredWor
$container = $this->container($events);
$container->expects('make')->with(SafeCaller::class)->returns(new SafeCaller($container->instance()));
$handler = Double::for(WebSocketExceptionHandler::class)->strict();
- $handler->expects('handle')->with($exception, Argument::type(Response::class))->returns(new Response('', 302));
+ $handler->expects('handle')->with(Argument::same($exception), Argument::type(Response::class))->returns(new Response('', 302));
$container->expects('make')->with(WebSocketExceptionHandler::class)->returns($handler);
$server = new HandshakeLifecycleServer($container->instance(), Double::for(Router::class)->strict(), Double::for(SwooleWebSocketServer::class)->strict());
@@ -358,9 +358,9 @@ public function testUnsupportedWebSocketVersionIsRejectedBeforeRouting(): void
$container = $this->container($events);
$container->expects('make')->with(Security::class)->returns(new Security);
$container->expects('make')->with(SafeCaller::class)->returns(new SafeCaller($container->instance()));
- $container->expects('make')->with(WebSocketExceptionHandler::class)->returns(
- new WebSocketExceptionHandler(Double::for(StdoutLoggerInterface::class)),
- );
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
+ $logger->allows('warning');
+ $container->expects('make')->with(WebSocketExceptionHandler::class)->returns(new WebSocketExceptionHandler($logger));
$router = Double::for(Router::class)->strict();
$router->expects('dispatchToCallback')->never();
$nativeServer = Double::for(SwooleWebSocketServer::class)->strict();
@@ -455,7 +455,7 @@ public function testHandshakeCancellationReportsTheHeldFailure(): void
$container = $this->container($events);
$container->allows('make')->with(Security::class)->returns(new Security);
$reporter = Double::for(ExceptionHandler::class)->strict();
- $reporter->expects('report')->with($heldFailure);
+ $reporter->expects('report')->with(Argument::same($heldFailure));
$reportingContainer = new BaseContainer;
$reportingContainer->instance(ExceptionHandler::class, $reporter);
BaseContainer::setInstance($reportingContainer);
@@ -540,8 +540,9 @@ public function testConnectionOpeningCancellationSkipsFallbackEmissionAndRelease
protected function container(?Dispatcher $events = null, bool $middlewareDisabled = false): OverriddenDouble
{
$container = Double::for(Container::class, override: true)->strict();
- $container->expects('make')->with(StdoutLoggerInterface::class)
- ->returns(Double::for(StdoutLoggerInterface::class));
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
+ $logger->allows('debug');
+ $container->expects('make')->with(StdoutLoggerInterface::class)->returns($logger);
$container->expects('bound')->with('events')->returns($events !== null);
$container->allows('bound')->with('middleware.disable')->returns($middlewareDisabled);
@@ -561,7 +562,7 @@ protected function router(int $status, array $middleware = []): Router
$route->allows('getControllerClass')->returns(WebSocketStub::class);
$router = Double::for(Router::class)->strict();
- $router->allows('gatherRouteMiddleware')->with($route)->returns($middleware);
+ $router->allows('gatherRouteMiddleware')->with(Argument::same($route))->returns($middleware);
$router->expects('dispatchToCallback')
->with(Argument::type(HttpRequest::class), Argument::type(Closure::class))
->resolves(function (HttpRequest $request) use ($route, $status): Response {
diff --git a/tests/WebSocketServer/ServerTest.php b/tests/WebSocketServer/ServerTest.php
index 59d594d2bf..4778ddc0f6 100644
--- a/tests/WebSocketServer/ServerTest.php
+++ b/tests/WebSocketServer/ServerTest.php
@@ -4,9 +4,8 @@
namespace Hypervel\Tests\WebSocketServer;
-use Hypervel\Container\Container as BaseContainer;
+use Hypervel\Container\Container;
use Hypervel\Context\CoroutineContext;
-use Hypervel\Contracts\Container\Container;
use Hypervel\Contracts\Debug\ExceptionHandler as ExceptionHandlerContract;
use Hypervel\Contracts\Events\Dispatcher as EventDispatcherContract;
use Hypervel\Contracts\Log\StdoutLoggerInterface;
@@ -34,9 +33,9 @@
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
use JMac\Testing\Matching\Argument;
-use JMac\Testing\OverriddenDouble;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
+use Psr\Log\NullLogger;
use RuntimeException;
use Swoole\Coroutine\CanceledException;
use Swoole\Http\Request as SwooleRequest;
@@ -56,7 +55,7 @@ protected function setUp(): void
{
parent::setUp();
- BaseContainer::getInstance()->scoped(DeferredCallbackCollection::class);
+ Container::getInstance()->scoped(DeferredCallbackCollection::class);
}
protected function tearDown(): void
@@ -77,7 +76,7 @@ public function testDeferOnOpenCallsOnOpen(): void
WebSocketStub::$coroutineId = 0;
$container = $this->createContainer();
- $server = new Server($container->instance());
+ $server = new Server($container);
$invoker = new ClassInvoker($server);
$swooleServer = Double::for(WebSocketSwooleServer::class)->strict();
@@ -95,13 +94,13 @@ public function testDeferOnOpenCallsOnOpen(): void
public function testDeferOnOpenLogsExceptionFromOnOpen(): void
{
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('error')->with(Argument::satisfies(
fn (string $message): bool => str_contains($message, 'onOpen failed')
));
$container = $this->createContainer($logger);
- $server = new Server($container->instance());
+ $server = new Server($container);
$invoker = new ClassInvoker($server);
$swooleServer = Double::for(WebSocketSwooleServer::class)->strict();
@@ -120,7 +119,7 @@ public function testConnectionOpenedEventIsDispatched(): void
));
$container = $this->createContainer(dispatcher: $dispatcher);
- $server = new Server($container->instance());
+ $server = new Server($container);
$invoker = new ClassInvoker($server);
$swooleServer = Double::for(WebSocketSwooleServer::class)->strict();
@@ -137,7 +136,7 @@ public function testConnectionOpenedEventNotDispatchedWithoutListeners(): void
$dispatcher->expects('dispatch')->never();
$container = $this->createContainer(dispatcher: $dispatcher);
- $server = new Server($container->instance());
+ $server = new Server($container);
$invoker = new ClassInvoker($server);
$swooleServer = Double::for(WebSocketSwooleServer::class)->strict();
@@ -149,7 +148,7 @@ public function testConnectionOpenedEventNotDispatchedWithoutListeners(): void
public function testConnectionOpenedEventDispatchedEvenWhenOnOpenThrows(): void
{
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('error');
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
@@ -159,7 +158,7 @@ public function testConnectionOpenedEventDispatchedEvenWhenOnOpenThrows(): void
));
$container = $this->createContainer($logger, $dispatcher);
- $server = new Server($container->instance());
+ $server = new Server($container);
$invoker = new ClassInvoker($server);
$swooleServer = Double::for(WebSocketSwooleServer::class)->strict();
@@ -173,14 +172,14 @@ public function testOnOpenRunsWhenConnectionOpenedEventThrows(): void
{
WebSocketStub::$coroutineId = 0;
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('error')->with(Argument::type('string'));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
$dispatcher->allows('hasListeners')->with(ConnectionOpened::class)->returns(true);
$dispatcher->expects('dispatch')->throws(new RuntimeException('event failed'));
- $server = new Server($this->createContainer($logger, $dispatcher)->instance());
+ $server = new Server($this->createContainer($logger, $dispatcher));
$invoker = new ClassInvoker($server);
$swooleServer = Double::for(WebSocketSwooleServer::class)->strict();
@@ -224,12 +223,12 @@ public function testMessageDeferredWorkFollowsTheCallbackOutcome(?string $failur
}
});
$container = $this->createContainer(dispatcher: $dispatcher);
- $container->allows('make')->with(OnMessageInterface::class)->returns($handler);
+ $container->instance(OnMessageInterface::class, $handler);
FdCollector::set(1, OnMessageInterface::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertSame($expected, $calls);
}
@@ -271,7 +270,7 @@ public function testOpenDeferredWorkRunsAfterTheHandler(bool $fail): void
throw new RuntimeException('open failed');
}
});
- $server = new Server($this->createContainer(dispatcher: $dispatcher)->instance());
+ $server = new Server($this->createContainer(dispatcher: $dispatcher));
$native = Double::for(WebSocketSwooleServer::class)->strict();
(new Waiter(1))->wait(fn () => (new ClassInvoker($server))->deferOnOpen(
@@ -305,12 +304,12 @@ public function testCloseDeferredWorkRunsBeforeConnectionContextIsReleased(bool
}
});
$container = $this->createContainer(dispatcher: $dispatcher);
- $container->allows('make')->with(OnCloseInterface::class)->returns($handler);
+ $container->instance(OnCloseInterface::class, $handler);
FdCollector::set(1, OnCloseInterface::class);
CoroutineContext::set(WebSocketContext::FD, 1);
WebSocketContext::set('value', 'context');
- (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ (new Server($container))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
$this->assertSame($fail ? ['closed', 'context'] : ['closed', 'deferred', 'context'], $calls);
$this->assertNull(WebSocketContext::get('value', fd: 1));
@@ -334,12 +333,12 @@ public function testCancellationDuringDeferredWorkStillReleasesConnectionContext
defer(function () use (&$calls): void { $calls[] = 'later'; })->always();
});
$container = $this->createContainer();
- $container->allows('make')->with(OnCloseInterface::class)->returns($handler);
+ $container->instance(OnCloseInterface::class, $handler);
FdCollector::set(1, OnCloseInterface::class);
CoroutineContext::set(WebSocketContext::FD, 1);
WebSocketContext::set('value', 'context');
- (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ (new Server($container))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
$this->assertSame([], $calls);
$this->assertNull(WebSocketContext::get('value', fd: 1));
@@ -363,11 +362,10 @@ public function testMessageLifecycleEventsAreDispatchedInOrder(): void
))->ordered();
$container = $this->createContainer(dispatcher: $dispatcher);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
- $server = new Server($container->instance());
+ $server = new Server($container);
$swooleServer = Double::for(WebSocketSwooleServer::class)->strict();
$frame = new Frame;
@@ -387,11 +385,10 @@ public function testMessageReceivedEventNotDispatchedWithoutListeners(): void
$dispatcher->expects('dispatch')->never();
$container = $this->createContainer(dispatcher: $dispatcher);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
- $server = new Server($container->instance());
+ $server = new Server($container);
$swooleServer = Double::for(WebSocketSwooleServer::class)->strict();
$frame = new Frame;
@@ -408,7 +405,7 @@ public function testMessageHandlerRunsWhenMessageReceivedEventThrows(): void
$exception = new RuntimeException('event failed');
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
- $exceptionHandler->expects('report')->with($exception);
+ $exceptionHandler->expects('report')->with(Argument::same($exception));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
$dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(true);
@@ -420,13 +417,12 @@ public function testMessageHandlerRunsWhenMessageReceivedEventThrows(): void
));
$container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertTrue(WebSocketMessageStub::$messageHandled);
}
@@ -439,7 +435,7 @@ public function testMessageReceivedCancellationSkipsTheHandlerAndCompletesWithTh
? new RuntimeException('received cleanup failed', previous: new CanceledException)
: new CanceledException;
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
- $exceptionHandler->expects('report')->times($wrapped ? 1 : 0)->with($cancellation);
+ $exceptionHandler->expects('report')->times($wrapped ? 1 : 0)->with(Argument::same($cancellation));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
$dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(true);
$dispatcher->expects('dispatch')->with(Argument::type(MessageReceived::class))->throws($cancellation);
@@ -449,13 +445,12 @@ public function testMessageReceivedCancellationSkipsTheHandlerAndCompletesWithTh
));
$container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertFalse(WebSocketMessageStub::$messageHandled);
}
@@ -465,11 +460,11 @@ public function testMessageHandlerFailuresAreReportedWithoutEscaping(): void
$exception = new RuntimeException('message failed');
WebSocketMessageStub::$messageException = $exception;
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('error')->never();
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
- $exceptionHandler->expects('report')->with($exception);
+ $exceptionHandler->expects('report')->with(Argument::same($exception));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
$dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(false);
@@ -479,13 +474,12 @@ public function testMessageHandlerFailuresAreReportedWithoutEscaping(): void
));
$container = $this->createContainer($logger, $dispatcher, $exceptionHandler);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertTrue(WebSocketMessageStub::$messageHandled);
}
@@ -513,13 +507,12 @@ function (Throwable $throwable) use (&$reported): void {
));
$container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertSame([$receivedException, $messageException], $reported);
}
@@ -533,7 +526,7 @@ public function testMessageHandlerCancellationCompletesWithTheKnownOutcome(bool
WebSocketMessageStub::$messageException = $cancellation;
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
- $exceptionHandler->expects('report')->times($receivedFails ? 1 : 0)->with($receivedFailure);
+ $exceptionHandler->expects('report')->times($receivedFails ? 1 : 0)->with(Argument::same($receivedFailure));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
$dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns($receivedFails);
@@ -546,13 +539,12 @@ public function testMessageHandlerCancellationCompletesWithTheKnownOutcome(bool
));
$container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertTrue(WebSocketMessageStub::$messageHandled);
}
@@ -565,7 +557,7 @@ public function testCanceledMessageCompletionContainsListenerFailures(bool $canc
$listenerFailure = $cancel ? new CanceledException : new RuntimeException('completion failed');
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
- $exceptionHandler->expects('report')->times($cancel ? 0 : 1)->with($listenerFailure);
+ $exceptionHandler->expects('report')->times($cancel ? 0 : 1)->with(Argument::same($listenerFailure));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
$dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(false);
@@ -573,13 +565,12 @@ public function testCanceledMessageCompletionContainsListenerFailures(bool $canc
$dispatcher->expects('dispatch')->with(Argument::type(MessageHandled::class))->throws($listenerFailure);
$container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertTrue(WebSocketMessageStub::$messageHandled);
}
@@ -589,7 +580,7 @@ public function testMessageHandledFailureIsReportedWithoutEscaping(): void
$exception = new RuntimeException('completion failed');
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
- $exceptionHandler->expects('report')->with($exception);
+ $exceptionHandler->expects('report')->with(Argument::same($exception));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
$dispatcher->expects('hasListeners')->with(MessageReceived::class)->returns(false);
@@ -597,20 +588,19 @@ public function testMessageHandledFailureIsReportedWithoutEscaping(): void
$dispatcher->expects('dispatch')->with(Argument::type(MessageHandled::class))->throws($exception);
$container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertTrue(WebSocketMessageStub::$messageHandled);
}
public function testMessageHandledCancellationIsContained(): void
{
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
$logger->expects('error')->never();
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
@@ -619,13 +609,12 @@ public function testMessageHandledCancellationIsContained(): void
$dispatcher->expects('dispatch')->with(Argument::type(MessageHandled::class))->throws(new CanceledException);
$container = $this->createContainer($logger, $dispatcher);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
$frame = new Frame;
$frame->fd = 1;
- (new Server($container->instance()))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
+ (new Server($container))->onMessage(Double::for(WebSocketSwooleServer::class)->strict(), $frame);
$this->assertTrue(WebSocketMessageStub::$messageHandled);
}
@@ -649,11 +638,10 @@ public function testConnectionLifecycleEventsAreDispatchedAroundTheCloseHandler(
))->ordered();
$container = $this->createContainer(dispatcher: $dispatcher);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
- $server = new Server($container->instance());
+ $server = new Server($container);
$swooleServer = Double::for(SwooleServer::class)->strict();
$server->onClose($swooleServer, 1, 0);
@@ -669,11 +657,10 @@ public function testConnectionClosedEventNotDispatchedWithoutListeners(): void
$dispatcher->expects('dispatch')->never();
$container = $this->createContainer(dispatcher: $dispatcher);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
FdCollector::set(1, WebSocketMessageStub::class);
- $server = new Server($container->instance());
+ $server = new Server($container);
$swooleServer = Double::for(SwooleServer::class)->strict();
$server->onClose($swooleServer, 1, 0);
@@ -685,7 +672,7 @@ public function testConnectionClosingFailureDoesNotSkipCloseCallbacksOrCleanup()
{
$exception = new RuntimeException('closing event failed');
$exceptionHandler = Double::for(ExceptionHandlerContract::class)->strict();
- $exceptionHandler->expects('report')->with($exception);
+ $exceptionHandler->expects('report')->with(Argument::same($exception));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
$dispatcher->allows('hasListeners')->with(ConnectionClosing::class)->returns(true);
$dispatcher->expects('dispatch')
@@ -697,12 +684,11 @@ public function testConnectionClosingFailureDoesNotSkipCloseCallbacksOrCleanup()
dispatcher: $dispatcher,
exceptionHandler: $exceptionHandler,
);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
CoroutineContext::set(WebSocketContext::FD, 1);
WebSocketContext::set('connection.id', 'one');
FdCollector::set(1, WebSocketMessageStub::class);
- (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ (new Server($container))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
$this->assertTrue(WebSocketMessageStub::$closeHandled);
$this->assertNull(FdCollector::get(1));
@@ -730,13 +716,13 @@ public function testConnectionClosingCancellationSkipsCloseCallbacksButCompletes
$dispatcher->allows('hasListeners')->with(ConnectionClosed::class)->returns(true);
$dispatcher->expects('dispatch')->with(Argument::type(ConnectionClosed::class))->throws($listenerFailure);
$container = $this->createContainer(dispatcher: $dispatcher, exceptionHandler: $exceptionHandler);
- $container->expects('make')->never()->with(WebSocketMessageStub::class);
CoroutineContext::set(WebSocketContext::FD, 1);
WebSocketContext::set('connection.id', 'one');
FdCollector::set(1, WebSocketMessageStub::class);
- (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ (new Server($container))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ $this->assertFalse($container->resolved(WebSocketMessageStub::class));
$this->assertSame($wrapped ? [$cancellation, $listenerFailure] : [$listenerFailure], $reported);
$this->assertFalse(WebSocketMessageStub::$closeHandled);
$this->assertNull(FdCollector::get(1));
@@ -748,7 +734,7 @@ public function testCloseWithoutCollectorStillReleasesConnectionContext(): void
CoroutineContext::set(WebSocketContext::FD, 1);
WebSocketContext::set('connection.id', 'one');
- (new Server($this->createContainer()->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ (new Server($this->createContainer()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
$this->assertArrayNotHasKey(1, WebSocketContext::getStorage());
}
@@ -757,7 +743,8 @@ public function testCloseHandlerFailureDoesNotSkipEventOrCleanup(): void
{
WebSocketMessageStub::$closeException = new RuntimeException('close failed');
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
+ $logger->allows('debug');
$logger->expects('error')->with(Argument::type('string'));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
@@ -766,13 +753,12 @@ public function testCloseHandlerFailureDoesNotSkipEventOrCleanup(): void
$dispatcher->expects('dispatch');
$container = $this->createContainer($logger, $dispatcher);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
CoroutineContext::set(WebSocketContext::FD, 1);
WebSocketContext::set('connection.id', 'one');
FdCollector::set(1, WebSocketMessageStub::class);
- (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ (new Server($container))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
$this->assertTrue(WebSocketMessageStub::$closeHandled);
$this->assertNull(FdCollector::get(1));
@@ -781,7 +767,8 @@ public function testCloseHandlerFailureDoesNotSkipEventOrCleanup(): void
public function testCloseEventFailureDoesNotSkipCleanup(): void
{
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
+ $logger->allows('debug');
$logger->expects('error')->with(Argument::type('string'));
$dispatcher = Double::for(EventDispatcherContract::class)->strict();
@@ -790,13 +777,12 @@ public function testCloseEventFailureDoesNotSkipCleanup(): void
$dispatcher->expects('dispatch')->throws(new RuntimeException('event failed'));
$container = $this->createContainer($logger, $dispatcher);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
CoroutineContext::set(WebSocketContext::FD, 1);
WebSocketContext::set('connection.id', 'one');
FdCollector::set(1, WebSocketMessageStub::class);
- (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ (new Server($container))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
$this->assertTrue(WebSocketMessageStub::$closeHandled);
$this->assertNull(FdCollector::get(1));
@@ -807,17 +793,17 @@ public function testCloseCancellationIsContainedAfterCleanup(): void
{
WebSocketMessageStub::$closeException = new CanceledException;
- $logger = Double::for(StdoutLoggerInterface::class);
+ $logger = Double::for(StdoutLoggerInterface::class)->strict();
+ $logger->allows('debug');
$logger->expects('error')->never();
$container = $this->createContainer($logger);
- $container->allows('make')->with(WebSocketMessageStub::class)->returns(new WebSocketMessageStub);
CoroutineContext::set(WebSocketContext::FD, 1);
WebSocketContext::set('connection.id', 'one');
FdCollector::set(1, WebSocketMessageStub::class);
- (new Server($container->instance()))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
+ (new Server($container))->onClose(Double::for(SwooleServer::class)->strict(), 1, 0);
$this->assertTrue(WebSocketMessageStub::$closeHandled);
$this->assertNull(FdCollector::get(1));
@@ -830,17 +816,15 @@ public function testExceptionHandlerResponseSuppressesHandshakeException(): void
$response = new Response('Unauthorized', Response::HTTP_UNAUTHORIZED);
$handler = Double::for(WebSocketExceptionHandler::class)->strict();
$handler->expects('handle')
- ->with($original, Argument::type(Response::class))
+ ->with(Argument::same($original), Argument::type(Response::class))
->returns($response);
$container = $this->createContainer();
- $container->expects('make')
- ->with(WebSocketExceptionHandler::class)
- ->returns($handler);
+ $container->instance(WebSocketExceptionHandler::class, $handler);
$this->assertSame(
$response,
- (new ClassInvoker(new Server($container->instance())))->handleException($original)
+ (new ClassInvoker(new Server($container)))->handleException($original)
);
}
@@ -850,16 +834,14 @@ public function testExceptionHandlerFailureRetainsHandshakeException(): void
$handlingFailure = new RuntimeException('exception handler failed');
$handler = Double::for(WebSocketExceptionHandler::class)->strict();
$handler->expects('handle')
- ->with($original, Argument::type(Response::class))
+ ->with(Argument::same($original), Argument::type(Response::class))
->throws($handlingFailure);
$container = $this->createContainer();
- $container->expects('make')
- ->with(WebSocketExceptionHandler::class)
- ->returns($handler);
+ $container->instance(WebSocketExceptionHandler::class, $handler);
try {
- (new ClassInvoker(new Server($container->instance())))->handleException($original);
+ (new ClassInvoker(new Server($container)))->handleException($original);
$this->fail('Expected exception handling to fail.');
} catch (RuntimeException $exception) {
$this->assertSame($handlingFailure, $exception);
@@ -884,29 +866,21 @@ private function waitForCoroutine(int $coroutineId, float $timeout = 1.0): void
}
/**
- * Create a container mock with logger and optional event dispatcher.
+ * Create a container with the services used by the WebSocket server.
*/
protected function createContainer(
?StdoutLoggerInterface $logger = null,
?EventDispatcherContract $dispatcher = null,
?ExceptionHandlerContract $exceptionHandler = null,
- ): OverriddenDouble {
- $logger ??= Double::for(StdoutLoggerInterface::class);
-
- $container = Double::for(Container::class, override: true)->strict();
- $container->allows('make')->with(StdoutLoggerInterface::class)->returns($logger);
+ ): Container {
+ $container = new Container;
+ $container->instance(StdoutLoggerInterface::class, $logger ?? new class extends NullLogger implements StdoutLoggerInterface {});
if ($exceptionHandler !== null) {
- $container->allows('make')
- ->with(ExceptionHandlerContract::class)
- ->returns($exceptionHandler);
+ $container->instance(ExceptionHandlerContract::class, $exceptionHandler);
}
-
- if ($dispatcher) {
- $container->allows('bound')->with('events')->returns(true);
- $container->allows('make')->with('events')->returns($dispatcher);
- } else {
- $container->allows('bound')->with('events')->returns(false);
+ if ($dispatcher !== null) {
+ $container->instance('events', $dispatcher);
}
return $container;
diff --git a/tests/WebSocketServer/WebSocketServerServiceProviderTest.php b/tests/WebSocketServer/WebSocketServerServiceProviderTest.php
index e3393636fc..92121be293 100644
--- a/tests/WebSocketServer/WebSocketServerServiceProviderTest.php
+++ b/tests/WebSocketServer/WebSocketServerServiceProviderTest.php
@@ -35,7 +35,7 @@ public function testResolvesPipeListenerOnlyForWebSocketSenderMessages(): void
$message = new SenderPipeMessage('disconnect', [42]);
$listener = Double::for(OnPipeMessageListener::class)->strict();
- $listener->expects('handle')->with($message);
+ $listener->expects('handle')->with(Argument::same($message));
$application = Double::for(Application::class, override: true)->strict();
$application->expects('make')->with('events')->returns($events);